blob: cdae2ffe49da5773572d557834b23db86ad01459 [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 // }
688 AutoMutex lock(mLock);
689 requestExit();
690 mWaitWorkCV.broadcast();
691 }
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());
Eric Laurent81784c32012-11-19 14:55:58 -0800700 Mutex::Autolock _l(mLock);
701
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);
Eric Laurent81784c32012-11-19 14:55:58 -0800719 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700720 mLock.unlock();
721 {
722 Mutex::Autolock _l(event->mLock);
723 while (event->mWaitStatus) {
724 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
725 event->mStatus = TIMED_OUT;
726 event->mWaitStatus = false;
727 }
728 }
729 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
Eric Laurent10351942014-05-08 18:49:52 -0700731 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800732 return status;
733}
734
Andy Hung71742ab2023-07-07 13:47:37 -0700735void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700736 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800737{
738 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700739 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800740}
741
742// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700743void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700744 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800745{
Andy Hungd0979812019-02-21 15:51:44 -0800746 // The audio statistics history is exponentially weighted to forget events
747 // about five or more seconds in the past. In order to have
748 // crisper statistics for mediametrics, we reset the statistics on
749 // an IoConfigEvent, to reflect different properties for a new device.
750 mIoJitterMs.reset();
751 mLatencyMs.reset();
752 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000753 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100754 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800755
Eric Laurent09f1ed22019-04-24 17:45:17 -0700756 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700757 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Andy Hung71742ab2023-07-07 13:47:37 -0700760void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700761{
762 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800763 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700764}
765
Eric Laurent81784c32012-11-19 14:55:58 -0800766// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700767void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800768 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800769{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800770 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700771 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800772}
773
Eric Laurent10351942014-05-08 18:49:52 -0700774// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700775status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800776{
Andy Hung2ddee192015-12-18 17:34:44 -0800777 sp<ConfigEvent> configEvent;
778 AudioParameter param(keyValuePair);
779 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700780 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800781 setMasterMono_l(value != 0);
782 if (param.size() == 1) {
783 return NO_ERROR; // should be a solo parameter - we don't pass down
784 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700785 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800786 configEvent = new SetParameterConfigEvent(param.toString());
787 } else {
788 configEvent = new SetParameterConfigEvent(keyValuePair);
789 }
Eric Laurent10351942014-05-08 18:49:52 -0700790 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700791}
792
Andy Hung71742ab2023-07-07 13:47:37 -0700793status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700794 const struct audio_patch *patch,
795 audio_patch_handle_t *handle)
796{
797 Mutex::Autolock _l(mLock);
798 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
799 status_t status = sendConfigEvent_l(configEvent);
800 if (status == NO_ERROR) {
801 CreateAudioPatchConfigEventData *data =
802 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
803 *handle = data->mHandle;
804 }
805 return status;
806}
807
Andy Hung71742ab2023-07-07 13:47:37 -0700808status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700809 const audio_patch_handle_t handle)
810{
811 Mutex::Autolock _l(mLock);
812 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
813 return sendConfigEvent_l(configEvent);
814}
815
Andy Hung71742ab2023-07-07 13:47:37 -0700816status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700817 const DeviceDescriptorBaseVector& outDevices)
818{
819 if (type() != RECORD) {
820 // The update out device operation is only for record thread.
821 return INVALID_OPERATION;
822 }
823 Mutex::Autolock _l(mLock);
824 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
825 return sendConfigEvent_l(configEvent);
826}
827
Andy Hung71742ab2023-07-07 13:47:37 -0700828void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200829{
830 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
831 sp<ConfigEvent> configEvent =
832 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
833 sendConfigEvent_l(configEvent);
834}
Eric Laurent1c333e22014-05-20 10:48:17 -0700835
Andy Hung71742ab2023-07-07 13:47:37 -0700836void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200837{
838 Mutex::Autolock _l(mLock);
839 sendCheckOutputStageEffectsEvent_l();
840}
841
Andy Hung71742ab2023-07-07 13:47:37 -0700842void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200843{
844 sp<ConfigEvent> configEvent =
845 (ConfigEvent *)new CheckOutputStageEffectsEvent();
846 sendConfigEvent_l(configEvent);
847}
848
Andy Hung71742ab2023-07-07 13:47:37 -0700849void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent6f9534f2022-05-03 18:15:04 +0200850{
851 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
852 sendConfigEvent_l(configEvent);
853}
854
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700855// post condition: mConfigEvents.isEmpty()
Andy Hung71742ab2023-07-07 13:47:37 -0700856void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700857{
Eric Laurent10351942014-05-08 18:49:52 -0700858 bool configChanged = false;
859
Eric Laurent81784c32012-11-19 14:55:58 -0800860 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700861 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700862 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800863 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700864 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700865 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700866 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
867 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800868 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700869 true /*asynchronous*/);
870 if (err != 0) {
871 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700872 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700873 }
874 } break;
875 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700876 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700877 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700878 } break;
879 case CFG_EVENT_SET_PARAMETER: {
880 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
881 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
882 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700883 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000884 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700885 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700886 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700887 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700888 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700889 CreateAudioPatchConfigEventData *data =
890 (CreateAudioPatchConfigEventData *)event->mData.get();
891 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700892 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200893 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700894 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
895 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
896 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700897 } break;
898 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700899 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700900 ReleaseAudioPatchConfigEventData *data =
901 (ReleaseAudioPatchConfigEventData *)event->mData.get();
902 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700903 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200904 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700905 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
906 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
907 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
908 } break;
909 case CFG_EVENT_UPDATE_OUT_DEVICE: {
910 UpdateOutDevicesConfigEventData *data =
911 (UpdateOutDevicesConfigEventData *)event->mData.get();
912 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700913 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200914 case CFG_EVENT_RESIZE_BUFFER: {
915 ResizeBufferConfigEventData *data =
916 (ResizeBufferConfigEventData *)event->mData.get();
917 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
918 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200919
920 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
921 setCheckOutputStageEffects();
922 } break;
923
Eric Laurent6f9534f2022-05-03 18:15:04 +0200924 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
925 onHalLatencyModesChanged_l();
926 } break;
927
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700928 default:
Eric Laurent10351942014-05-08 18:49:52 -0700929 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700930 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
Eric Laurent10351942014-05-08 18:49:52 -0700932 {
933 Mutex::Autolock _l(event->mLock);
934 if (event->mWaitStatus) {
935 event->mWaitStatus = false;
936 event->mCond.signal();
937 }
938 }
939 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
940 }
941
942 if (configChanged) {
943 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800944 }
Eric Laurent81784c32012-11-19 14:55:58 -0800945}
946
Marco Nelissenb2208842014-02-07 14:00:50 -0800947String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
948 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700949 const audio_channel_representation_t representation =
950 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700951
952 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800953 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700954 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
955 if (output) {
956 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
957 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
958 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700959 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700960 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
961 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
962 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
963 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
964 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
965 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
966 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
967 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
968 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
969 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
970 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700972 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
977 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
978 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700979 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700980 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
981 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700982 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
983 } else {
984 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
985 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
986 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
987 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
988 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
989 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
990 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
991 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
992 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
993 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
994 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
995 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700996 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
997 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
998 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700999 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001000 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1001 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001002 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1003 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1004 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1005 }
1006 const int len = s.length();
1007 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001008 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001009 s.unlockBuffer(len - 2); // remove trailing ", "
1010 }
1011 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001012 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001013 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1014 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1015 return s;
1016 default:
1017 s.appendFormat("unknown mask, representation:%d bits:%#x",
1018 representation, audio_channel_mask_get_bits(mask));
1019 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001020 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001021}
1022
Andy Hung71742ab2023-07-07 13:47:37 -07001023void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-10-06 12:09:49 -07001024NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001025{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001026 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1027 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1028
Andy Hung21ff9672023-07-18 20:54:44 -07001029 const bool locked = afutils::dumpTryLock(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08001030 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001031 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001032 }
1033
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001034 dumpBase_l(fd, args);
1035 dumpInternals_l(fd, args);
1036 dumpTracks_l(fd, args);
1037 dumpEffectChains_l(fd, args);
1038
1039 if (locked) {
1040 mLock.unlock();
1041 }
1042
1043 dprintf(fd, " Local log:\n");
1044 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001045
1046 // --all does the statistics
1047 bool dumpAll = false;
1048 for (const auto &arg : args) {
1049 if (arg == String16("--all")) {
1050 dumpAll = true;
1051 }
1052 }
1053 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001054 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001055 if (!sched.empty()) {
1056 (void)write(fd, sched.c_str(), sched.size());
1057 }
1058 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001059}
1060
Andy Hung71742ab2023-07-07 13:47:37 -07001061void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001062{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001063 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001064 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001065 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001066 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung4d693a32023-07-19 12:47:35 -07001067 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1068 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001069 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001070 dprintf(fd, " Channel count: %u\n", mChannelCount);
1071 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00001072 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung4d693a32023-07-19 12:47:35 -07001073 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1074 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001075 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001076 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001077 size_t numConfig = mConfigEvents.size();
1078 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001079 const size_t SIZE = 256;
1080 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001081 for (size_t i = 0; i < numConfig; i++) {
1082 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001083 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001084 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001085 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001086 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001087 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001088 }
Andy Hung293558a2017-03-21 12:19:20 -07001089 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001090 dprintf(fd, " Output devices: %s (%s)\n",
1091 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1092 dprintf(fd, " Input device: %#x (%s)\n",
1093 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001094 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001095
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001096 // Dump timestamp statistics for the Thread types that support it.
1097 if (mType == RECORD
1098 || mType == MIXER
1099 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001100 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001101 || mType == OFFLOAD
1102 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001103 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001104 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001105 }
1106
Andy Hung446f4df2019-02-21 12:26:41 -08001107 if (mLastIoBeginNs > 0) { // MMAP may not set this
1108 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1109 isOutput() ? "write" : "read",
1110 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1111 }
1112
1113 if (mProcessTimeMs.getN() > 0) {
1114 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1115 }
1116
1117 if (mIoJitterMs.getN() > 0) {
1118 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1119 isOutput() ? "write" : "read",
1120 mIoJitterMs.toString().c_str());
1121 }
1122
Andy Hunge6c37112019-02-26 17:38:10 -08001123 if (mLatencyMs.getN() > 0) {
1124 dprintf(fd, " Threadloop %s latency stats: %s\n",
1125 isOutput() ? "write" : "read",
1126 mLatencyMs.toString().c_str());
1127 }
Robert Wu06db0a32021-08-10 19:05:34 +00001128
1129 if (mMonopipePipeDepthStats.getN() > 0) {
1130 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1131 isOutput() ? "write" : "read",
1132 mMonopipePipeDepthStats.toString().c_str());
1133 }
Eric Laurent81784c32012-11-19 14:55:58 -08001134}
1135
Andy Hung71742ab2023-07-07 13:47:37 -07001136void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001137{
1138 const size_t SIZE = 256;
1139 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001140
Marco Nelissenb2208842014-02-07 14:00:50 -08001141 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001142 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001143 write(fd, buffer, strlen(buffer));
1144
Marco Nelissenb2208842014-02-07 14:00:50 -08001145 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hungbd72c542023-06-20 18:56:17 -07001146 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001147 if (chain != 0) {
1148 chain->dump(fd, args);
1149 }
1150 }
1151}
1152
Andy Hung71742ab2023-07-07 13:47:37 -07001153void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001154{
1155 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001156 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001157}
1158
Andy Hung71742ab2023-07-07 13:47:37 -07001159String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001160{
1161 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001162 case MIXER:
1163 return String16("AudioMix");
1164 case DIRECT:
1165 return String16("AudioDirectOut");
1166 case DUPLICATING:
1167 return String16("AudioDup");
1168 case RECORD:
1169 return String16("AudioIn");
1170 case OFFLOAD:
1171 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001172 case MMAP_PLAYBACK:
1173 return String16("MmapPlayback");
1174 case MMAP_CAPTURE:
1175 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001176 case SPATIALIZER:
1177 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001178 default:
1179 ALOG_ASSERT(false);
1180 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001181 }
1182}
1183
Andy Hung71742ab2023-07-07 13:47:37 -07001184void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001185{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001186 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001187 if (mPowerManager != 0) {
1188 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001189 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001190 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1191 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001192 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001193 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001194 {} /* workSource */,
1195 {} /* historyTag */);
1196 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001197 mWakeLockToken = binder;
1198 }
Chris Ye6597d732020-02-28 22:38:25 -08001199 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001200 }
Wei Jia3f273d12015-11-24 09:06:49 -08001201
Andy Hung3f0c9022016-01-15 17:49:46 -08001202 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001203 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1204 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001205}
1206
Andy Hung71742ab2023-07-07 13:47:37 -07001207void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001208{
1209 Mutex::Autolock _l(mLock);
1210 releaseWakeLock_l();
1211}
1212
Andy Hung71742ab2023-07-07 13:47:37 -07001213void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001214{
Andy Hung3f0c9022016-01-15 17:49:46 -08001215 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001216 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001217 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001218 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001219 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001220 }
1221 mWakeLockToken.clear();
1222 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001223}
1224
Andy Hung71742ab2023-07-07 13:47:37 -07001225void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001226 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001227 // use checkService() to avoid blocking if power service is not up yet
1228 sp<IBinder> binder =
1229 defaultServiceManager()->checkService(String16("power"));
1230 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001231 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001232 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001233 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001234 binder->linkToDeath(mDeathRecipient);
1235 }
1236 }
1237}
1238
Andy Hung71742ab2023-07-07 13:47:37 -07001239void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001240 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001241
1242#if !LOG_NDEBUG
1243 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001244 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001245 s << uid << " ";
1246 }
1247 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1248#endif
1249
Andy Hung438e7572015-12-14 15:51:17 -08001250 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1251 if (mSystemReady) {
1252 ALOGE("no wake lock to update, but system ready!");
1253 } else {
1254 ALOGW("no wake lock to update, system not ready yet");
1255 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001256 return;
1257 }
1258 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001259 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001260 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1261 mWakeLockToken, uidsAsInt);
1262 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001263 }
1264}
1265
Andy Hung71742ab2023-07-07 13:47:37 -07001266void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001267{
1268 Mutex::Autolock _l(mLock);
1269 releaseWakeLock_l();
1270 mPowerManager.clear();
1271}
1272
Andy Hung71742ab2023-07-07 13:47:37 -07001273void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001274 const DeviceDescriptorBaseVector& outDevices __unused)
1275{
1276 ALOGE("%s should only be called in RecordThread", __func__);
1277}
1278
Andy Hung71742ab2023-07-07 13:47:37 -07001279void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001280{
1281 ALOGE("%s should only be called in RecordThread", __func__);
1282}
1283
Andy Hung71742ab2023-07-07 13:47:37 -07001284void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001285{
1286 sp<ThreadBase> thread = mThread.promote();
1287 if (thread != 0) {
1288 thread->clearPowerManager();
1289 }
1290 ALOGW("power manager service died !!!");
1291}
1292
Andy Hung71742ab2023-07-07 13:47:37 -07001293void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001294 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001295{
Andy Hungbd72c542023-06-20 18:56:17 -07001296 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001297 if (chain != 0) {
1298 if (type != NULL) {
1299 chain->setEffectSuspended_l(type, suspend);
1300 } else {
1301 chain->setEffectSuspendedAll_l(suspend);
1302 }
1303 }
1304
1305 updateSuspendedSessions_l(type, suspend, sessionId);
1306}
1307
Andy Hung71742ab2023-07-07 13:47:37 -07001308void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001309{
1310 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1311 if (index < 0) {
1312 return;
1313 }
1314
1315 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1316 mSuspendedSessions.valueAt(index);
1317
1318 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001319 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001320 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hungbd72c542023-06-20 18:56:17 -07001321 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001322 chain->setEffectSuspendedAll_l(true);
1323 } else {
1324 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1325 desc->mType.timeLow);
1326 chain->setEffectSuspended_l(&desc->mType, true);
1327 }
1328 }
1329 }
1330}
1331
Andy Hung71742ab2023-07-07 13:47:37 -07001332void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001333 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001334 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001335{
1336 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1337
1338 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1339
1340 if (suspend) {
1341 if (index >= 0) {
1342 sessionEffects = mSuspendedSessions.valueAt(index);
1343 } else {
1344 mSuspendedSessions.add(sessionId, sessionEffects);
1345 }
1346 } else {
1347 if (index < 0) {
1348 return;
1349 }
1350 sessionEffects = mSuspendedSessions.valueAt(index);
1351 }
1352
1353
Andy Hungbd72c542023-06-20 18:56:17 -07001354 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001355 if (type != NULL) {
1356 key = type->timeLow;
1357 }
1358 index = sessionEffects.indexOfKey(key);
1359
1360 sp<SuspendedSessionDesc> desc;
1361 if (suspend) {
1362 if (index >= 0) {
1363 desc = sessionEffects.valueAt(index);
1364 } else {
1365 desc = new SuspendedSessionDesc();
1366 if (type != NULL) {
1367 desc->mType = *type;
1368 }
1369 sessionEffects.add(key, desc);
1370 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1371 }
1372 desc->mRefCount++;
1373 } else {
1374 if (index < 0) {
1375 return;
1376 }
1377 desc = sessionEffects.valueAt(index);
1378 if (--desc->mRefCount == 0) {
1379 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1380 sessionEffects.removeItemsAt(index);
1381 if (sessionEffects.isEmpty()) {
1382 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1383 sessionId);
1384 mSuspendedSessions.removeItem(sessionId);
1385 }
1386 }
1387 }
1388 if (!sessionEffects.isEmpty()) {
1389 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1390 }
1391}
1392
Andy Hung71742ab2023-07-07 13:47:37 -07001393void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001394 audio_session_t sessionId,
Andy Hung71ba4b32022-10-06 12:09:49 -07001395 bool threadLocked)
1396NO_THREAD_SAFETY_ANALYSIS // manual locking
1397{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001398 if (!threadLocked) {
1399 mLock.lock();
1400 }
Eric Laurent81784c32012-11-19 14:55:58 -08001401
Eric Laurent81784c32012-11-19 14:55:58 -08001402 if (mType != RECORD) {
1403 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1404 // another session. This gives the priority to well behaved effect control panels
1405 // and applications not using global effects.
1406 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1407 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001408 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001409 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1410 }
1411 }
1412
Eric Laurent6b446ce2019-12-13 10:56:31 -08001413 if (!threadLocked) {
1414 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001415 }
1416}
1417
Eric Laurent4c415062016-06-17 16:14:16 -07001418// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001419status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001420 const effect_descriptor_t *desc, audio_session_t sessionId)
1421{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001422 // No global output effect sessions on record threads
1423 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1424 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001425 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1426 desc->name, mThreadName);
1427 return BAD_VALUE;
1428 }
1429 // only pre processing effects on record thread
1430 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1431 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1432 desc->name, mThreadName);
1433 return BAD_VALUE;
1434 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001435
1436 // always allow effects without processing load or latency
1437 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1438 return NO_ERROR;
1439 }
1440
Eric Laurent4c415062016-06-17 16:14:16 -07001441 audio_input_flags_t flags = mInput->flags;
1442 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1443 if (flags & AUDIO_INPUT_FLAG_RAW) {
1444 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1445 desc->name, mThreadName);
1446 return BAD_VALUE;
1447 }
1448 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1449 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1450 desc->name, mThreadName);
1451 return BAD_VALUE;
1452 }
1453 }
jiabineb3bda02020-06-30 14:07:03 -07001454
Andy Hungbd72c542023-06-20 18:56:17 -07001455 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001456 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1457 return BAD_VALUE;
1458 }
Eric Laurent4c415062016-06-17 16:14:16 -07001459 return NO_ERROR;
1460}
1461
1462// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001463status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001464 const effect_descriptor_t *desc, audio_session_t sessionId)
1465{
1466 // no preprocessing on playback threads
1467 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001468 ALOGW("%s: pre processing effect %s created on playback"
1469 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001470 return BAD_VALUE;
1471 }
1472
Eric Laurent3e4de772017-07-16 16:55:08 -07001473 // always allow effects without processing load or latency
1474 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1475 return NO_ERROR;
1476 }
1477
Andy Hungbd72c542023-06-20 18:56:17 -07001478 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001479 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1480 __func__);
1481 return BAD_VALUE;
1482 }
1483
Eric Laurentf690c462021-09-17 14:47:03 +02001484 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1485 && mType != SPATIALIZER) {
1486 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1487 __func__, mType);
1488 return BAD_VALUE;
1489 }
1490
Eric Laurent4c415062016-06-17 16:14:16 -07001491 switch (mType) {
1492 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001493 audio_output_flags_t flags = mOutput->flags;
1494 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1495 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1496 // global effects are applied only to non fast tracks if they are SW
1497 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1498 break;
1499 }
1500 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1501 // only post processing on output stage session
1502 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001503 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1504 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001505 return BAD_VALUE;
1506 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001507 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1508 // only post processing on output stage session
1509 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001510 ALOGW("%s: non post processing effect %s not allowed on device session",
1511 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001512 return BAD_VALUE;
1513 }
Eric Laurent4c415062016-06-17 16:14:16 -07001514 } else {
1515 // no restriction on effects applied on non fast tracks
1516 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1517 break;
1518 }
1519 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001520
Eric Laurent4c415062016-06-17 16:14:16 -07001521 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001522 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001523 return BAD_VALUE;
1524 }
1525 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001526 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1527 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001528 return BAD_VALUE;
1529 }
1530 }
1531 } break;
1532 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001533 // nothing actionable on offload threads, if the effect:
1534 // - is offloadable: the effect can be created
1535 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1536 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001537 break;
1538 case DIRECT:
1539 // Reject any effect on Direct output threads for now, since the format of
1540 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001541 ALOGW("%s: effect %s on DIRECT output thread %s",
1542 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001543 return BAD_VALUE;
1544 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001545 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001546 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1547 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001548 return BAD_VALUE;
1549 }
1550 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001551 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1552 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001553 return BAD_VALUE;
1554 }
1555 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001556 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1557 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001558 return BAD_VALUE;
1559 }
1560 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001561 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001562 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1563 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1564 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1565 // are supported and added after the spatializer.
1566 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1567 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1568 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001569 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001570 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1571 // only post processing , downmixer or spatializer effects on output stage session
1572 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1573 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1574 break;
1575 }
1576 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1577 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1578 __func__, desc->name);
1579 return BAD_VALUE;
1580 }
1581 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1582 // only post processing on output stage session
1583 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1584 ALOGW("%s: non post processing effect %s not allowed on device session",
1585 __func__, desc->name);
1586 return BAD_VALUE;
1587 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001588 }
1589 break;
jiabinc658e452022-10-21 20:52:21 +00001590 case BIT_PERFECT:
1591 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1592 // Allow HW accelerated effects of tunnel type
1593 break;
1594 }
1595 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1596 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1597 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1598 // 3) there is any bit-perfect track with the given session id.
1599 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1600 sessionId == AUDIO_SESSION_DEVICE) {
1601 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1602 __func__, desc->name, mThreadName);
1603 return BAD_VALUE;
1604 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1605 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1606 __func__, desc->name, sessionId);
1607 return BAD_VALUE;
1608 }
1609 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001610 default:
1611 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1612 }
1613
1614 return NO_ERROR;
1615}
1616
Eric Laurent81784c32012-11-19 14:55:58 -08001617// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001618sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hungd65869f2023-06-27 17:05:02 -07001619 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001620 const sp<IEffectClient>& effectClient,
1621 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001622 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001623 effect_descriptor_t *desc,
1624 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001625 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001626 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001627 bool probe,
1628 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001629{
Andy Hungbd72c542023-06-20 18:56:17 -07001630 sp<IAfEffectModule> effect;
1631 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001632 status_t lStatus;
Andy Hungbd72c542023-06-20 18:56:17 -07001633 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001634 bool chainCreated = false;
1635 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001636 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001637
1638 lStatus = initCheck();
1639 if (lStatus != NO_ERROR) {
1640 ALOGW("createEffect_l() Audio driver not initialized.");
1641 goto Exit;
1642 }
1643
Eric Laurent81784c32012-11-19 14:55:58 -08001644 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1645
1646 { // scope for mLock
1647 Mutex::Autolock _l(mLock);
1648
Eric Laurent4c415062016-06-17 16:14:16 -07001649 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001650 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001651 goto Exit;
1652 }
1653
Eric Laurent81784c32012-11-19 14:55:58 -08001654 // check for existing effect chain with the requested audio session
1655 chain = getEffectChain_l(sessionId);
1656 if (chain == 0) {
1657 // create a new chain for this session
1658 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001659 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001660 addEffectChain_l(chain);
1661 chain->setStrategy(getStrategyForSession_l(sessionId));
1662 chainCreated = true;
1663 } else {
1664 effect = chain->getEffectFromDesc_l(desc);
1665 }
1666
1667 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1668
1669 if (effect == 0) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001670 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001671 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001672 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001673 if (lStatus != NO_ERROR) {
1674 goto Exit;
1675 }
1676 effectCreated = true;
1677
jiabinc52b1ff2019-10-31 17:20:42 -07001678 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001679 effect->setDevices(outDeviceTypeAddrs());
1680 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001681 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001682 effect->setAudioSource(mAudioSource);
1683 }
jiabin1319f5a2021-03-30 22:21:24 +00001684 if (effect->isHapticGenerator()) {
1685 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1686 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001687 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung2cbc2722023-07-17 17:05:00 -07001688 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001689 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001690 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001691 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001692 }
1693 }
Eric Laurent81784c32012-11-19 14:55:58 -08001694 // create effect handle and connect it to effect module
Andy Hungbd72c542023-06-20 18:56:17 -07001695 handle = IAfEffectHandle::create(
1696 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001697 lStatus = handle->initCheck();
1698 if (lStatus == OK) {
1699 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001700 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001701 }
Eric Laurent81784c32012-11-19 14:55:58 -08001702 if (enabled != NULL) {
1703 *enabled = (int)effect->isEnabled();
1704 }
1705 }
1706
1707Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001708 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001709 Mutex::Autolock _l(mLock);
1710 if (effectCreated) {
1711 chain->removeEffect_l(effect);
1712 }
Eric Laurent81784c32012-11-19 14:55:58 -08001713 if (chainCreated) {
1714 removeEffectChain_l(chain);
1715 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001716 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001717 }
1718
Glenn Kasten9156ef32013-08-06 15:39:08 -07001719 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001720 return handle;
1721}
1722
Andy Hung71742ab2023-07-07 13:47:37 -07001723void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001724 bool unpinIfLast)
1725{
1726 bool remove = false;
Andy Hungbd72c542023-06-20 18:56:17 -07001727 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001728 {
1729 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07001730 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001731 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001732 return;
1733 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001734 effect = effectBase->asEffectModule();
1735 if (effect == nullptr) {
1736 return;
1737 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001738 // restore suspended effects if the disconnected handle was enabled and the last one.
1739 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1740 if (remove) {
1741 removeEffect_l(effect, true);
1742 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001743 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001744 }
1745 if (remove) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001746 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001748 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001749 }
1750 }
1751}
1752
Andy Hung71742ab2023-07-07 13:47:37 -07001753void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001754 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001755 Mutex::Autolock _l(mLock);
1756 broadcast_l();
1757 }
1758 if (!effect->isOffloadable()) {
1759 if (mType == ThreadBase::OFFLOAD) {
1760 PlaybackThread *t = (PlaybackThread *)this;
1761 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1762 }
1763 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001764 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001765 }
1766 }
1767}
1768
Andy Hung71742ab2023-07-07 13:47:37 -07001769void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001770 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001771 Mutex::Autolock _l(mLock);
1772 broadcast_l();
1773 }
1774}
1775
Andy Hung71742ab2023-07-07 13:47:37 -07001776sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001777 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001778{
1779 Mutex::Autolock _l(mLock);
1780 return getEffect_l(sessionId, effectId);
1781}
1782
Andy Hung71742ab2023-07-07 13:47:37 -07001783sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001784 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001785{
Andy Hungbd72c542023-06-20 18:56:17 -07001786 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001787 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1788}
1789
Andy Hung71742ab2023-07-07 13:47:37 -07001790std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001791{
Andy Hungbd72c542023-06-20 18:56:17 -07001792 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001793 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1794}
1795
Eric Laurent81784c32012-11-19 14:55:58 -08001796// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1797// PlaybackThread::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001798status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001799{
1800 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001801 audio_session_t sessionId = effect->sessionId();
Andy Hungbd72c542023-06-20 18:56:17 -07001802 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001803 bool chainCreated = false;
1804
Eric Laurent5baf2af2013-09-12 17:37:00 -07001805 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001806 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001807 this, effect->desc().name, effect->desc().flags);
1808
Eric Laurent81784c32012-11-19 14:55:58 -08001809 if (chain == 0) {
1810 // create a new chain for this session
1811 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001812 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001813 addEffectChain_l(chain);
1814 chain->setStrategy(getStrategyForSession_l(sessionId));
1815 chainCreated = true;
1816 }
1817 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1818
1819 if (chain->getEffectFromId_l(effect->id()) != 0) {
1820 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1821 this, effect->desc().name, chain.get());
1822 return BAD_VALUE;
1823 }
1824
Eric Laurent5baf2af2013-09-12 17:37:00 -07001825 effect->setOffloaded(mType == OFFLOAD, mId);
1826
Eric Laurent81784c32012-11-19 14:55:58 -08001827 status_t status = chain->addEffect_l(effect);
1828 if (status != NO_ERROR) {
1829 if (chainCreated) {
1830 removeEffectChain_l(chain);
1831 }
1832 return status;
1833 }
1834
jiabin8f278ee2019-11-11 12:16:27 -08001835 effect->setDevices(outDeviceTypeAddrs());
1836 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001837 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001838 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001839
Eric Laurent81784c32012-11-19 14:55:58 -08001840 return NO_ERROR;
1841}
1842
Andy Hung71742ab2023-07-07 13:47:37 -07001843void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001844
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001845 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001846 effect_descriptor_t desc = effect->desc();
1847 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1848 detachAuxEffect_l(effect->id());
1849 }
1850
Andy Hungbd72c542023-06-20 18:56:17 -07001851 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001852 if (chain != 0) {
1853 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001854 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001855 removeEffectChain_l(chain);
1856 }
1857 } else {
1858 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1859 }
1860}
1861
Andy Hung71742ab2023-07-07 13:47:37 -07001862void ThreadBase::lockEffectChains_l(
Andy Hungbd72c542023-06-20 18:56:17 -07001863 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001864NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001865{
1866 effectChains = mEffectChains;
1867 for (size_t i = 0; i < mEffectChains.size(); i++) {
1868 mEffectChains[i]->lock();
1869 }
1870}
1871
Andy Hung71742ab2023-07-07 13:47:37 -07001872void ThreadBase::unlockEffectChains(
Andy Hungbd72c542023-06-20 18:56:17 -07001873 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001874NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001875{
1876 for (size_t i = 0; i < effectChains.size(); i++) {
1877 effectChains[i]->unlock();
1878 }
1879}
1880
Andy Hung71742ab2023-07-07 13:47:37 -07001881sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001882{
1883 Mutex::Autolock _l(mLock);
1884 return getEffectChain_l(sessionId);
1885}
1886
Andy Hung71742ab2023-07-07 13:47:37 -07001887sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001888 const
Eric Laurent81784c32012-11-19 14:55:58 -08001889{
1890 size_t size = mEffectChains.size();
1891 for (size_t i = 0; i < size; i++) {
1892 if (mEffectChains[i]->sessionId() == sessionId) {
1893 return mEffectChains[i];
1894 }
1895 }
1896 return 0;
1897}
1898
Andy Hung71742ab2023-07-07 13:47:37 -07001899void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001900{
1901 Mutex::Autolock _l(mLock);
1902 size_t size = mEffectChains.size();
1903 for (size_t i = 0; i < size; i++) {
1904 mEffectChains[i]->setMode_l(mode);
1905 }
1906}
1907
Andy Hung71742ab2023-07-07 13:47:37 -07001908void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001909{
1910 config->type = AUDIO_PORT_TYPE_MIX;
1911 config->ext.mix.handle = mId;
1912 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001913 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001914 config->channel_mask = mChannelMask;
1915 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1916 AUDIO_PORT_CONFIG_FORMAT;
1917}
1918
Andy Hung71742ab2023-07-07 13:47:37 -07001919void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001920{
1921 Mutex::Autolock _l(mLock);
1922 if (mSystemReady) {
1923 return;
1924 }
1925 mSystemReady = true;
1926
1927 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1928 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1929 }
1930 mPendingConfigEvents.clear();
1931}
1932
Andy Hungdae27702016-10-31 14:01:16 -07001933template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001934ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001935 ssize_t index = mActiveTracks.indexOf(track);
1936 if (index >= 0) {
1937 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1938 return index;
1939 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001940 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001941 mActiveTracksGeneration++;
1942 mLatestActiveTrack = track;
1943 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001944 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001945 return mActiveTracks.add(track);
1946}
1947
1948template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001949ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001950 ssize_t index = mActiveTracks.remove(track);
1951 if (index < 0) {
1952 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1953 return index;
1954 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001955 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001956 mActiveTracksGeneration++;
1957 --mBatteryCounter[track->uid()].second;
1958 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001959 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001960#ifdef TEE_SINK
1961 track->dumpTee(-1 /* fd */, "_REMOVE");
1962#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001963 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001964 return index;
1965}
1966
1967template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001968void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001969 for (const sp<T> &track : mActiveTracks) {
1970 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001971 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001972 }
1973 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001974 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001975 mActiveTracks.clear();
1976 mLatestActiveTrack.clear();
1977 mBatteryCounter.clear();
1978}
1979
1980template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001981void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001982 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001983 // Updates ActiveTracks client uids to the thread wakelock.
1984 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1985 thread->updateWakeLockUids_l(getWakeLockUids());
1986 mLastActiveTracksGeneration = mActiveTracksGeneration;
1987 }
1988
1989 // Updates BatteryNotifier uids
1990 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1991 const uid_t uid = it->first;
1992 ssize_t &previous = it->second.first;
1993 ssize_t &current = it->second.second;
1994 if (current > 0) {
1995 if (previous == 0) {
1996 BatteryNotifier::getInstance().noteStartAudio(uid);
1997 }
1998 previous = current;
1999 ++it;
2000 } else if (current == 0) {
2001 if (previous > 0) {
2002 BatteryNotifier::getInstance().noteStopAudio(uid);
2003 }
2004 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
2005 } else /* (current < 0) */ {
2006 LOG_ALWAYS_FATAL("negative battery count %zd", current);
2007 }
2008 }
2009}
Eric Laurent83b88082014-06-20 18:31:16 -07002010
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002011template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002012bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002013 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002014 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002015
2016 for (const sp<T> &track : mActiveTracks) {
2017 // Do not short-circuit as all hasChanged states must be reset
2018 // as all the metadata are going to be sent
2019 hasChanged |= track->readAndClearHasChanged();
2020 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002021 return hasChanged;
2022}
2023
2024template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002025void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002026 const char *funcName, const sp<T> &track) const {
2027 if (mLocalLog != nullptr) {
2028 String8 result;
2029 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002030 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002031 }
2032}
2033
Andy Hung71742ab2023-07-07 13:47:37 -07002034void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002035{
2036 // Thread could be blocked waiting for async
2037 // so signal it to handle state changes immediately
2038 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2039 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2040 mSignalPending = true;
2041 mWaitWorkCV.broadcast();
2042}
2043
Andy Hungd0979812019-02-21 15:51:44 -08002044// Call only from threadLoop() or when it is idle.
2045// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung71742ab2023-07-07 13:47:37 -07002046void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08002047{
2048 // Do not log if we have no stats.
2049 // We choose the timestamp verifier because it is the most likely item to be present.
2050 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2051 if (nstats == 0) {
2052 return;
2053 }
2054
2055 // Don't log more frequently than once per 12 hours.
2056 // We use BOOTTIME to include suspend time.
2057 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2058 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2059 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2060 return;
2061 }
2062
2063 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2064 mLastRecordedTimeNs = timeNs;
2065
Ray Essickf27e9872019-12-07 06:28:46 -08002066 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002067
2068#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2069
2070 // thread configuration
2071 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2072 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2073 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2074 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2075 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2076 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2077 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002078 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2079 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002080
2081 // thread statistics
2082 if (mIoJitterMs.getN() > 0) {
2083 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2084 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2085 }
2086 if (mProcessTimeMs.getN() > 0) {
2087 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2088 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2089 }
2090 const auto tsjitter = mTimestampVerifier.getJitterMs();
2091 if (tsjitter.getN() > 0) {
2092 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2093 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2094 }
2095 if (mLatencyMs.getN() > 0) {
2096 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2097 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2098 }
Robert Wu06db0a32021-08-10 19:05:34 +00002099 if (mMonopipePipeDepthStats.getN() > 0) {
2100 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2101 mMonopipePipeDepthStats.getMean());
2102 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2103 mMonopipePipeDepthStats.getStdDev());
2104 }
Andy Hungd0979812019-02-21 15:51:44 -08002105
2106 item->selfrecord();
2107}
2108
Andy Hung71742ab2023-07-07 13:47:37 -07002109product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002110{
Andy Hung2cbc2722023-07-17 17:05:00 -07002111 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002112 return PRODUCT_STRATEGY_NONE;
2113 }
2114 return AudioSystem::getStrategyForStream(stream);
2115}
2116
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002117// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002118void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002119 const sp<audio_utils::MelProcessor>& /*processor*/)
2120{
2121 // Do nothing
2122 ALOGW("%s: ThreadBase does not support CSD", __func__);
2123}
2124
2125// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002126void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002127{
2128 // Do nothing
2129 ALOGW("%s: ThreadBase does not support CSD", __func__);
2130}
2131
Eric Laurent81784c32012-11-19 14:55:58 -08002132// ----------------------------------------------------------------------------
2133// Playback
2134// ----------------------------------------------------------------------------
2135
Andy Hung2cbc2722023-07-17 17:05:00 -07002136PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002137 AudioStreamOut* output,
2138 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002139 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002140 bool systemReady,
2141 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07002142 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002143 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungf8ab4692023-07-20 21:44:14 -07002144 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002145 mMixerBuffer(NULL),
2146 mMixerBufferSize(0),
2147 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2148 mMixerBufferValid(false),
Andy Hungf8ab4692023-07-20 21:44:14 -07002149 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002150 mEffectBuffer(NULL),
2151 mEffectBufferSize(0),
2152 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2153 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002154 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002155 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002156 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002157 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002158 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002159 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002160 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002161 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002162 mMixerStatus(MIXER_IDLE),
2163 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung18bef9b2023-07-20 21:31:38 -07002164 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002165 mBytesRemaining(0),
2166 mCurrentWriteLength(0),
2167 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002168 mWriteAckSequence(0),
2169 mDrainSequence(0),
Andy Hung01b29482023-07-19 16:22:58 -07002170 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002171 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002172 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002173 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002174 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002175 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002176 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002177{
Glenn Kastend7dca052015-03-05 16:05:54 -08002178 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07002179 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002180
2181 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2182 // it would be safer to explicitly pass initial masterVolume/masterMute as
2183 // parameter.
2184 //
2185 // If the HAL we are using has support for master volume or master mute,
2186 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2187 // and the mute set to false).
Andy Hung2cbc2722023-07-17 17:05:00 -07002188 mMasterVolume = afThreadCallback->masterVolume_l();
2189 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002190 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002191 if (mOutput->audioHwDev->canSetMasterVolume()) {
2192 mMasterVolume = 1.0;
2193 }
2194
2195 if (mOutput->audioHwDev->canSetMasterMute()) {
2196 mMasterMute = false;
2197 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002198 mIsMsdDevice = strcmp(
2199 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002200 }
2201
Eric Laurentf1f22e72021-07-13 14:04:14 +02002202 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2203 mMixerChannelMask = mixerConfig->channel_mask;
2204 }
2205
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002206 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002207
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002208 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002209 && mMixerChannelMask != mChannelMask) {
2210 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2211 mChannelMask, mMixerChannelMask);
2212 }
2213
Andy Hungc8fddf32018-08-08 18:32:37 -07002214 // TODO: We may also match on address as well as device type for
2215 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002216 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002217 // TODO: This property should be ensure that only contains one single device type.
2218 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2219 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002220 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2221 : AUDIO_DEVICE_NONE));
2222 }
2223
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002224 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2225 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002226 mStreamTypes[stream].volume = 0.0f;
Andy Hung2cbc2722023-07-17 17:05:00 -07002227 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002228 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002229 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002230 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2231 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002232 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2233 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002234}
2235
Andy Hung71742ab2023-07-07 13:47:37 -07002236PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002237{
Andy Hung2cbc2722023-07-17 17:05:00 -07002238 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002239 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002240 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002241 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002242 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002245// Thread virtuals
2246
Andy Hung71742ab2023-07-07 13:47:37 -07002247void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002248{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002249 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002250 ALOGE("The stream is not open yet"); // This should not happen.
2251 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002252 // Callbacks take strong or weak pointers as a parameter.
2253 // Since PlaybackThread passes itself as a callback handler, it can only
2254 // be done outside of the constructor. Creating weak and especially strong
2255 // pointers to a refcounted object in its own constructor is strongly
2256 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2257 // Even if a function takes a weak pointer, it is possible that it will
2258 // need to convert it to a strong pointer down the line.
2259 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2260 mOutput->stream->setCallback(this) == OK) {
2261 mUseAsyncWrite = true;
Andy Hung71742ab2023-07-07 13:47:37 -07002262 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002263 }
2264
jiabinf6eb4c32020-02-25 14:06:25 -08002265 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002266 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002267 }
2268 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002269 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002270 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002271}
2272
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002273// ThreadBase virtuals
Andy Hung71742ab2023-07-07 13:47:37 -07002274void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002275{
2276 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002277 status_t result = mOutput->stream->exit();
2278 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002279}
2280
Andy Hung71742ab2023-07-07 13:47:37 -07002281void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002282{
Eric Laurent81784c32012-11-19 14:55:58 -08002283 String8 result;
2284
Marco Nelissenb2208842014-02-07 14:00:50 -08002285 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002286 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2287 const stream_type_t *st = &mStreamTypes[i];
2288 if (i > 0) {
2289 result.appendFormat(", ");
2290 }
2291 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2292 if (st->mute) {
2293 result.append("M");
2294 }
2295 }
2296 result.append("\n");
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002297 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002298 result.clear();
2299
Eric Laurent81784c32012-11-19 14:55:58 -08002300 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2301 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002302 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002303 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002304
2305 size_t numtracks = mTracks.size();
2306 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002307 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002308 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002309 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002310 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002311 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002312 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002313 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002314 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002315 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002316 if (track != 0) {
2317 bool active = mActiveTracks.indexOf(track) >= 0;
2318 if (active) {
2319 numactiveseen++;
2320 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002321 result.append(prefix);
2322 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002323 }
2324 }
2325 } else {
2326 result.append("\n");
2327 }
2328 if (numactiveseen != numactive) {
2329 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002330 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002331 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002332 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002333 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002334 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002335 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002336 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002337 result.append(prefix);
2338 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002339 }
2340 }
2341 }
2342
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002343 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002344}
2345
Andy Hung71742ab2023-07-07 13:47:37 -07002346void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002347{
Andy Hung04cb8f72020-03-20 13:44:33 -07002348 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002349 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002350 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2351 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002352 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2353 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2354 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2355 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002356 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002357 dprintf(fd, " Total writes: %d\n", mNumWrites);
2358 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2359 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2360 dprintf(fd, " Suspend count: %d\n", mSuspended);
2361 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2362 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2363 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2364 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002365 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002366 AudioStreamOut *output = mOutput;
2367 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002368 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002369 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002370 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2371 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2372 if (mPipeSink.get() != nullptr) {
2373 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2374 }
2375 if (output != nullptr) {
2376 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002377 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002378 }
Eric Laurent81784c32012-11-19 14:55:58 -08002379}
2380
Eric Laurent81784c32012-11-19 14:55:58 -08002381// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002382sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07002383 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002384 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002385 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002386 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002387 audio_format_t format,
2388 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002389 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002390 size_t *pNotificationFrameCount,
2391 uint32_t notificationsPerBuffer,
2392 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002393 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002394 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002395 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002396 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002397 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002398 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002399 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002400 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002401 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002402 bool isSpatialized,
2403 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002404{
Glenn Kasten74935e42013-12-19 08:56:45 -08002405 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002406 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07002407 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002408 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002409 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002410 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002411 uint32_t sampleRate;
2412
2413 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2414 lStatus = BAD_VALUE;
2415 goto Exit;
2416 }
Eric Laurent21da6472017-11-09 16:29:26 -08002417
2418 if (*pSampleRate == 0) {
2419 *pSampleRate = mSampleRate;
2420 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002421 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002422
2423 // special case for FAST flag considered OK if fast mixer is present
2424 if (hasFastMixer()) {
2425 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2426 }
2427
2428 // Check if requested flags are compatible with output stream flags
2429 if ((*flags & outputFlags) != *flags) {
2430 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2431 *flags, outputFlags);
2432 *flags = (audio_output_flags_t)(*flags & outputFlags);
2433 }
Eric Laurent81784c32012-11-19 14:55:58 -08002434
jiabinc658e452022-10-21 20:52:21 +00002435 if (isBitPerfect) {
Andy Hungbd72c542023-06-20 18:56:17 -07002436 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002437 if (chain.get() != nullptr) {
2438 // Bit-perfect is required according to the configuration and preferred mixer
2439 // attributes, but it is not in the output flag from the client's request. Explicitly
2440 // adding bit-perfect flag to check the compatibility
2441 audio_output_flags_t flagsToCheck =
2442 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2443 chain->checkOutputFlagCompatibility(&flagsToCheck);
2444 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2445 ALOGE("%s cannot create track as there is data-processing effect attached to "
2446 "given session id(%d)", __func__, sessionId);
2447 lStatus = BAD_VALUE;
2448 goto Exit;
2449 }
2450 *flags = flagsToCheck;
2451 }
2452 }
2453
Eric Laurent81784c32012-11-19 14:55:58 -08002454 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002455 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002456 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002457 // PCM data
2458 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002459 // TODO: extract as a data library function that checks that a computationally
2460 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002461 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002462 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2463 (channelMask == AUDIO_CHANNEL_OUT_MONO
2464 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002465 // hardware sample rate
2466 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002467 // normal mixer has an associated fast mixer
2468 hasFastMixer() &&
2469 // there are sufficient fast track slots available
2470 (mFastTrackAvailMask != 0)
2471 // FIXME test that MixerThread for this fast track has a capable output HAL
2472 // FIXME add a permission test also?
2473 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002474 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2475 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002476 // read the fast track multiplier property the first time it is needed
2477 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2478 if (ok != 0) {
2479 ALOGE("%s pthread_once failed: %d", __func__, ok);
2480 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002481 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002482 }
Eric Laurent4c415062016-06-17 16:14:16 -07002483
2484 // check compatibility with audio effects.
2485 { // scope for mLock
2486 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002487 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002488 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002489 AUDIO_SESSION_OUTPUT_STAGE,
2490 AUDIO_SESSION_OUTPUT_MIX,
2491 sessionId,
2492 }) {
Andy Hungbd72c542023-06-20 18:56:17 -07002493 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002494 if (chain.get() != nullptr) {
2495 audio_output_flags_t old = *flags;
2496 chain->checkOutputFlagCompatibility(flags);
2497 if (old != *flags) {
2498 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2499 (int)session, (int)old, (int)*flags);
2500 }
Eric Laurent4c415062016-06-17 16:14:16 -07002501 }
2502 }
2503 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002504 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002505 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2506 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002507 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002508 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002509 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002510 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002511 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002512 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002513 audio_is_linear_pcm(format), channelMask, sampleRate,
2514 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002515 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002516 }
2517 }
Eric Laurent21da6472017-11-09 16:29:26 -08002518
2519 if (!audio_has_proportional_frames(format)) {
2520 if (sharedBuffer != 0) {
2521 // Same comment as below about ignoring frameCount parameter for set()
2522 frameCount = sharedBuffer->size();
2523 } else if (frameCount == 0) {
2524 frameCount = mNormalFrameCount;
2525 }
2526 if (notificationFrameCount != frameCount) {
2527 notificationFrameCount = frameCount;
2528 }
2529 } else if (sharedBuffer != 0) {
2530 // FIXME: Ensure client side memory buffers need
2531 // not have additional alignment beyond sample
2532 // (e.g. 16 bit stereo accessed as 32 bit frame).
2533 size_t alignment = audio_bytes_per_sample(format);
2534 if (alignment & 1) {
2535 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2536 alignment = 1;
2537 }
2538 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2539 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2540 if (channelCount > 1) {
2541 // More than 2 channels does not require stronger alignment than stereo
2542 alignment <<= 1;
2543 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002544 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002545 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002546 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002547 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002548 goto Exit;
2549 }
Eric Laurent21da6472017-11-09 16:29:26 -08002550
2551 // When initializing a shared buffer AudioTrack via constructors,
2552 // there's no frameCount parameter.
2553 // But when initializing a shared buffer AudioTrack via set(),
2554 // there _is_ a frameCount parameter. We silently ignore it.
2555 frameCount = sharedBuffer->size() / frameSize;
2556 } else {
2557 size_t minFrameCount = 0;
2558 // For fast tracks we try to respect the application's request for notifications per buffer.
2559 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2560 if (notificationsPerBuffer > 0) {
2561 // Avoid possible arithmetic overflow during multiplication.
2562 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2563 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2564 notificationsPerBuffer, mFrameCount);
2565 } else {
2566 minFrameCount = mFrameCount * notificationsPerBuffer;
2567 }
2568 }
2569 } else {
2570 // For normal PCM streaming tracks, update minimum frame count.
2571 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2572 // cover audio hardware latency.
2573 // This is probably too conservative, but legacy application code may depend on it.
2574 // If you change this calculation, also review the start threshold which is related.
2575 uint32_t latencyMs = latency_l();
2576 if (latencyMs == 0) {
2577 ALOGE("Error when retrieving output stream latency");
2578 lStatus = UNKNOWN_ERROR;
2579 goto Exit;
2580 }
2581
2582 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2583 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2584
Eric Laurent81784c32012-11-19 14:55:58 -08002585 }
Eric Laurent21da6472017-11-09 16:29:26 -08002586 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002587 frameCount = minFrameCount;
2588 }
Eric Laurent81784c32012-11-19 14:55:58 -08002589 }
Eric Laurent21da6472017-11-09 16:29:26 -08002590
2591 // Make sure that application is notified with sufficient margin before underrun.
2592 // The client can divide the AudioTrack buffer into sub-buffers,
2593 // and expresses its desire to server as the notification frame count.
2594 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2595 size_t maxNotificationFrames;
2596 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2597 // notify every HAL buffer, regardless of the size of the track buffer
2598 maxNotificationFrames = mFrameCount;
2599 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002600 // Triple buffer the notification period for a triple buffered mixer period;
2601 // otherwise, double buffering for the notification period is fine.
2602 //
2603 // TODO: This should be moved to AudioTrack to modify the notification period
2604 // on AudioTrack::setBufferSizeInFrames() changes.
2605 const int nBuffering =
2606 (uint64_t{frameCount} * mSampleRate)
2607 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2608
Eric Laurent21da6472017-11-09 16:29:26 -08002609 maxNotificationFrames = frameCount / nBuffering;
2610 // If client requested a fast track but this was denied, then use the smaller maximum.
2611 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2612 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2613 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2614 maxNotificationFrames = maxNotificationFramesFastDenied;
2615 }
2616 }
2617 }
2618 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2619 if (notificationFrameCount == 0) {
2620 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2621 maxNotificationFrames, frameCount);
2622 } else {
2623 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2624 notificationFrameCount, maxNotificationFrames, frameCount);
2625 }
2626 notificationFrameCount = maxNotificationFrames;
2627 }
2628 }
2629
Glenn Kasten74935e42013-12-19 08:56:45 -08002630 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002631 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002632
Glenn Kastenc3df8382014-03-13 15:05:25 -07002633 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002634 case BIT_PERFECT:
2635 if (isBitPerfect) {
2636 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2637 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2638 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2639 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2640 mChannelMask);
2641 lStatus = BAD_VALUE;
2642 goto Exit;
2643 }
2644 }
2645 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002646
2647 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002648 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002649 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002650 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2651 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002652 sampleRate, format, channelMask, mOutput, mFormat);
2653 lStatus = BAD_VALUE;
2654 goto Exit;
2655 }
2656 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002657 break;
2658
2659 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002660 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002661 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2662 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002663 sampleRate, format, channelMask, mOutput, mFormat);
2664 lStatus = BAD_VALUE;
2665 goto Exit;
2666 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002667 break;
2668
2669 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002670 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002671 ALOGE("createTrack_l() Bad parameter: format %#x \""
2672 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 format, mOutput, mFormat);
2674 lStatus = BAD_VALUE;
2675 goto Exit;
2676 }
Andy Hungcd044842014-08-07 11:04:34 -07002677 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002678 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2679 lStatus = BAD_VALUE;
2680 goto Exit;
2681 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002682 break;
2683
Eric Laurent81784c32012-11-19 14:55:58 -08002684 }
2685
2686 lStatus = initCheck();
2687 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002688 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002689 goto Exit;
2690 }
2691
2692 { // scope for mLock
2693 Mutex::Autolock _l(mLock);
2694
2695 // all tracks in same audio session must share the same routing strategy otherwise
2696 // conflicts will happen when tracks are moved from one output to another by audio policy
2697 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002698 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002699 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002700 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002701 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002702 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002703 if (sessionId == t->sessionId() && strategy != actual) {
2704 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2705 strategy, actual);
2706 lStatus = BAD_VALUE;
2707 goto Exit;
2708 }
2709 }
2710 }
2711
yucliuc9c49cd2020-07-13 16:25:21 -07002712 // Set DIRECT flag if current thread is DirectOutputThread. This can
2713 // happen when the playback is rerouted to direct output thread by
2714 // dynamic audio policy.
2715 // Do NOT report the flag changes back to client, since the client
2716 // doesn't explicitly request a direct flag.
2717 audio_output_flags_t trackFlags = *flags;
2718 if (mType == DIRECT) {
2719 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2720 }
2721
Andy Hung3ff4b552023-06-26 19:20:57 -07002722 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002723 channelMask, frameCount,
2724 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002725 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung3ff4b552023-06-26 19:20:57 -07002726 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002727 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002728
Glenn Kasten03003332013-08-06 15:40:54 -07002729 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2730 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002731 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002732 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002733 goto Exit;
2734 }
2735 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002736 {
2737 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2738 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002739 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002740 }
2741 }
Eric Laurent81784c32012-11-19 14:55:58 -08002742
Andy Hungbd72c542023-06-20 18:56:17 -07002743 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002744 if (chain != 0) {
2745 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2746 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002747 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002748 chain->incTrackCnt();
2749 }
2750
Eric Laurent05067782016-06-01 18:27:28 -07002751 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002752 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2753 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2754 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002755 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002756 }
2757 }
2758
2759 lStatus = NO_ERROR;
2760
2761Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002762 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002763 return track;
2764}
2765
Andy Hung1bc088a2018-02-09 15:57:31 -08002766template<typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002767ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002768{
Andy Hungc0691382018-09-12 18:01:57 -07002769 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002770 const ssize_t index = mTracks.remove(track);
2771 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002772 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002773 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002774 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002775 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002776 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002777 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002778 }
2779 return index;
2780}
2781
Andy Hung71742ab2023-07-07 13:47:37 -07002782uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002783{
2784 return latency;
2785}
2786
Andy Hung71742ab2023-07-07 13:47:37 -07002787uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002788{
2789 Mutex::Autolock _l(mLock);
2790 return latency_l();
2791}
Andy Hung71742ab2023-07-07 13:47:37 -07002792uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002794 uint32_t latency;
2795 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2796 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002797 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002798 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002799}
2800
Andy Hung71742ab2023-07-07 13:47:37 -07002801void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002802{
2803 Mutex::Autolock _l(mLock);
2804 // Don't apply master volume in SW if our HAL can do it for us.
2805 if (mOutput && mOutput->audioHwDev &&
2806 mOutput->audioHwDev->canSetMasterVolume()) {
2807 mMasterVolume = 1.0;
2808 } else {
2809 mMasterVolume = value;
2810 }
2811}
2812
Andy Hung71742ab2023-07-07 13:47:37 -07002813void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002814{
2815 mMasterBalance.store(balance);
2816}
2817
Andy Hung71742ab2023-07-07 13:47:37 -07002818void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002819{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002820 if (isDuplicating()) {
2821 return;
2822 }
Eric Laurent81784c32012-11-19 14:55:58 -08002823 Mutex::Autolock _l(mLock);
2824 // Don't apply master mute in SW if our HAL can do it for us.
2825 if (mOutput && mOutput->audioHwDev &&
2826 mOutput->audioHwDev->canSetMasterMute()) {
2827 mMasterMute = false;
2828 } else {
2829 mMasterMute = muted;
2830 }
2831}
2832
Andy Hung71742ab2023-07-07 13:47:37 -07002833void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002834{
2835 Mutex::Autolock _l(mLock);
2836 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002837 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002838}
2839
Andy Hung71742ab2023-07-07 13:47:37 -07002840void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002841{
2842 Mutex::Autolock _l(mLock);
2843 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002844 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002845}
2846
Andy Hung71742ab2023-07-07 13:47:37 -07002847float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002848{
2849 Mutex::Autolock _l(mLock);
2850 return mStreamTypes[stream].volume;
2851}
2852
Andy Hung71742ab2023-07-07 13:47:37 -07002853void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002854{
2855 mOutput->stream->setVolume(left, right);
2856}
2857
Eric Laurent81784c32012-11-19 14:55:58 -08002858// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002859status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung71ba4b32022-10-06 12:09:49 -07002860NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002861{
2862 status_t status = ALREADY_EXISTS;
2863
Eric Laurent81784c32012-11-19 14:55:58 -08002864 if (mActiveTracks.indexOf(track) < 0) {
2865 // the track is newly added, make sure it fills up all its
2866 // buffers before playing. This is to ensure the client will
2867 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002868 if (track->isExternalTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002869 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002871 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872 mLock.lock();
2873 // abort track was stopped/paused while we released the lock
Andy Hung3ff4b552023-06-26 19:20:57 -07002874 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875 if (status == NO_ERROR) {
2876 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002877 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 mLock.lock();
2879 }
2880 return INVALID_OPERATION;
2881 }
2882 // abort if start is rejected by audio policy manager
2883 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002884 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2885 // current playback thread is reopened, which may happen when clients set preferred
2886 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2887 // immediately.
2888 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 }
2890#ifdef ADD_BATTERY_DATA
2891 // to track the speaker usage
2892 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2893#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002894 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895 }
2896
Eric Laurent51716182016-02-29 18:00:56 -08002897 // set retry count for buffer fill
2898 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002899 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002900 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002901 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002902 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002903 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002904 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002905 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002906 track->retryCount() = kMaxTrackStartupRetries;
2907 track->fillingStatus() =
2908 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002909 }
2910
Andy Hungbd72c542023-06-20 18:56:17 -07002911 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002912 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2913 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2914 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002915 // Unlock due to VibratorService will lock for this call and will
2916 // call Tracks.mute/unmute which also require thread's lock.
2917 mLock.unlock();
Andy Hung9554ec02023-07-20 21:23:42 -07002918 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002919 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002920 std::optional<media::AudioVibratorInfo> vibratorInfo;
2921 {
2922 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2923 // used to play this track.
Andy Hung2ac52f12023-08-28 18:36:53 -07002924 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung2cbc2722023-07-17 17:05:00 -07002925 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002926 }
jiabin57303cc2018-12-18 15:45:57 -08002927 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002928 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002929 if (vibratorInfo) {
2930 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2931 }
2932
jiabin57303cc2018-12-18 15:45:57 -08002933 // Haptic playback should be enabled by vibrator service.
2934 if (track->getHapticPlaybackEnabled()) {
2935 // Disable haptic playback of all active track to ensure only
2936 // one track playing haptic if current track should play haptic.
2937 for (const auto &t : mActiveTracks) {
2938 t->setHapticPlaybackEnabled(false);
2939 }
jiabin245cdd92018-12-07 17:55:15 -08002940 }
jiabine70bc7f2020-06-30 22:07:55 -07002941
2942 // Set haptic intensity for effect
2943 if (chain != nullptr) {
2944 chain->setHapticIntensity_l(track->id(), intensity);
2945 }
jiabin245cdd92018-12-07 17:55:15 -08002946 }
2947
Andy Hung3ff4b552023-06-26 19:20:57 -07002948 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002949 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002950 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002951 if (chain != 0) {
2952 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2953 track->sessionId());
2954 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002955 }
2956
Andy Hungc2b11cb2020-04-22 09:04:01 -07002957 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002958 status = NO_ERROR;
2959 }
2960
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002961 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002962 return status;
2963}
2964
Andy Hung71742ab2023-07-07 13:47:37 -07002965bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002966{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002967 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002968 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002969 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung3ff4b552023-06-26 19:20:57 -07002970 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002971 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002972 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002973 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002974 if (track->isPausePending()) {
2975 track->pauseAck();
2976 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002977 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002978 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979
2980 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002981}
2982
Andy Hung71742ab2023-07-07 13:47:37 -07002983void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002984{
2985 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002986
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002987 String8 result;
2988 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002989 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002990
Eric Laurent81784c32012-11-19 14:55:58 -08002991 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002992 {
2993 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2994 mAudioTrackCallbacks.erase(track);
2995 }
Eric Laurent81784c32012-11-19 14:55:58 -08002996 if (track->isFastTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002997 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002998 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002999 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3000 mFastTrackAvailMask |= 1 << index;
3001 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung3ff4b552023-06-26 19:20:57 -07003002 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003003 }
Andy Hungbd72c542023-06-20 18:56:17 -07003004 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003005 if (chain != 0) {
3006 chain->decTrackCnt();
3007 }
3008}
3009
Andy Hung71742ab2023-07-07 13:47:37 -07003010String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003011{
Eric Laurent81784c32012-11-19 14:55:58 -08003012 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003013 String8 out_s8;
3014 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3015 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003016 }
Andy Hung71ba4b32022-10-06 12:09:49 -07003017 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003018}
3019
Andy Hung71742ab2023-07-07 13:47:37 -07003020status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003021 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003022 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003023 return NO_INIT;
3024 }
3025 return mOutput->stream->selectPresentation(presentationId, programId);
3026}
3027
Andy Hung71742ab2023-07-07 13:47:37 -07003028void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003029 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003030 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003031 sp<AudioIoDescriptor> desc;
3032 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003033 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003034 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003035 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003036 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003037 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3038 mSampleRate, mFormat, mChannelMask,
3039 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3040 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003041 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003042 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003043 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003044 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003045 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003046 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003047 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003048 break;
3049 }
Andy Hung2cbc2722023-07-17 17:05:00 -07003050 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003051}
3052
Andy Hung71742ab2023-07-07 13:47:37 -07003053void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003055 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003056}
3057
Andy Hung71742ab2023-07-07 13:47:37 -07003058void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003059{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003060 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003061}
3062
Andy Hung71742ab2023-07-07 13:47:37 -07003063void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003064{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003065 mCallbackThread->setAsyncError();
3066}
3067
Andy Hung71742ab2023-07-07 13:47:37 -07003068void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003069 const std::basic_string<uint8_t>& metadataBs)
3070{
Andy Hung71742ab2023-07-07 13:47:37 -07003071 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003072 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung71742ab2023-07-07 13:47:37 -07003073 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003074 if (playbackThread == nullptr) {
3075 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3076 return;
3077 }
3078
jiabinf6eb4c32020-02-25 14:06:25 -08003079 audio_utils::metadata::Data metadata =
3080 audio_utils::metadata::dataFromByteString(metadataBs);
3081 if (metadata.empty()) {
3082 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3083 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3084 (int)metadataBs.size());
3085 return;
3086 }
3087
3088 audio_utils::metadata::ByteString metaDataStr =
3089 audio_utils::metadata::byteStringFromData(metadata);
3090 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3091 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003092 for (const auto& callbackPair : mAudioTrackCallbacks) {
3093 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003094 }
3095 }).detach();
3096}
3097
Andy Hung71742ab2023-07-07 13:47:37 -07003098void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099{
3100 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003101 // reject out of sequence requests
3102 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3103 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003104 mWaitWorkCV.signal();
3105 }
3106}
3107
Andy Hung71742ab2023-07-07 13:47:37 -07003108void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109{
3110 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003111 // reject out of sequence requests
3112 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003113 // Register discontinuity when HW drain is completed because that can cause
3114 // the timestamp frame position to reset to 0 for direct and offload threads.
3115 // (Out of sequence requests are ignored, since the discontinuity would be handled
3116 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003117 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003118 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119 mWaitWorkCV.signal();
3120 }
3121}
3122
Andy Hung71742ab2023-07-07 13:47:37 -07003123void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003124{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003125 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003126 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3127 mSampleRate = audioConfig.sample_rate;
3128 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003129 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003130 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003131 }
Andy Hungf8ab4692023-07-20 21:44:14 -07003132 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003133 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3134 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003135 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003136
3137 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3138 mMixerChannelMask = mChannelMask;
3139 }
3140
Andy Hunge5412692014-05-16 11:25:07 -07003141 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003142 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003143
Eric Laurentf1f22e72021-07-13 14:04:14 +02003144 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3145
Phil Burkca5e6142015-07-14 09:42:29 -07003146 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003147 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003148 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003149 // Get format from the shim, which will be different than the HAL format
3150 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003151 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003152 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003153 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003154 }
Andy Hungf8ab4692023-07-20 21:44:14 -07003155 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003156 LOG_FATAL("HAL format %#x not supported for mixed output",
3157 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003158 }
Phil Burk062e67a2015-02-11 13:40:50 -08003159 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003160 result = mOutput->stream->getBufferSize(&mBufferSize);
3161 LOG_ALWAYS_FATAL_IF(result != OK,
3162 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003163 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003164 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003165 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003166 mFrameCount);
3167 }
3168
Eric Laurentd1f69b02014-12-15 14:33:13 -08003169 mHwSupportsPause = false;
3170 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003171 bool supportsPause = false, supportsResume = false;
3172 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3173 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003174 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003175 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003176 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003177 } else if (supportsResume) {
3178 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003179 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003180 }
3181 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003182 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3183 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3184 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003185
Andy Hungfbfc3952015-01-15 13:33:51 -08003186 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3187 // For best precision, we use float instead of the associated output
3188 // device format (typically PCM 16 bit).
3189
3190 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3191 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3192 mBufferSize = mFrameSize * mFrameCount;
3193
3194 // TODO: We currently use the associated output device channel mask and sample rate.
3195 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3196 // (if a valid mask) to avoid premature downmix.
3197 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3198 // instead of the output device sample rate to avoid loss of high frequency information.
3199 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3200 }
3201
Andy Hung09a50072014-02-27 14:30:47 -08003202 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003203 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003204 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003205 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3206 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003207 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3208 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003209
Eric Laurent81784c32012-11-19 14:55:58 -08003210 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3211 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3212 maxNormalFrameCount = maxNormalFrameCount & ~15;
3213 if (maxNormalFrameCount < minNormalFrameCount) {
3214 maxNormalFrameCount = minNormalFrameCount;
3215 }
3216 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3217 if (multiplier <= 1.0) {
3218 multiplier = 1.0;
3219 } else if (multiplier <= 2.0) {
3220 if (2 * mFrameCount <= maxNormalFrameCount) {
3221 multiplier = 2.0;
3222 } else {
3223 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3224 }
3225 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003226 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003227 }
3228 }
3229 mNormalFrameCount = multiplier * mFrameCount;
3230 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003231 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003232 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3233 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003234 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003235 mNormalFrameCount);
3236
Andy Hung08fb1742015-05-31 23:22:10 -07003237 // Check if we want to throttle the processing to no more than 2x normal rate
3238 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003239 mThreadThrottleTimeMs = 0;
3240 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003241 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3242
Andy Hung010a1a12014-03-13 13:57:33 -07003243 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3244 // Originally this was int16_t[] array, need to remove legacy implications.
3245 free(mSinkBuffer);
3246 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003247
Andy Hung5b10a202014-03-13 13:59:29 -07003248 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3249 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3250 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003251 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003252
Andy Hung69aed5f2014-02-25 17:24:40 -08003253 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3254 // drives the output.
3255 free(mMixerBuffer);
3256 mMixerBuffer = NULL;
3257 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003258 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003259 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003260 * audio_bytes_per_sample(mMixerBufferFormat);
3261 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3262 }
Andy Hung98ef9782014-03-04 14:46:50 -08003263 free(mEffectBuffer);
3264 mEffectBuffer = NULL;
3265 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003266 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003267 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003268 * audio_bytes_per_sample(mEffectBufferFormat);
3269 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3270 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003271
Eric Laurentb62d0362021-10-26 17:40:18 +02003272 if (mType == SPATIALIZER) {
3273 free(mPostSpatializerBuffer);
3274 mPostSpatializerBuffer = nullptr;
3275 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3276 * audio_bytes_per_sample(mEffectBufferFormat);
3277 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3278 }
3279
Mikhail Naganov55773032020-10-01 15:08:13 -07003280 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3281 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003282 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3283 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003284 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003285
Eric Laurent81784c32012-11-19 14:55:58 -08003286 // force reconfiguration of effect chains and engines to take new buffer size and audio
3287 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003288 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003289 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3290 // matter.
3291 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hungbd72c542023-06-20 18:56:17 -07003292 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003293 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung2cbc2722023-07-17 17:05:00 -07003294 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003295 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003296 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003297
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003298 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003299 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003300 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung4d693a32023-07-19 12:47:35 -07003301 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003302 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3303 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3304 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3305 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3306 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3307 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3308 (int32_t)mHapticChannelMask)
3309 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3310 (int32_t)mHapticChannelCount)
3311 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung4d693a32023-07-19 12:47:35 -07003312 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003313 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3314 (int32_t)mFrameCount) // sic - added HAL
3315 ;
3316 uint32_t latencyMs;
3317 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3318 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3319 }
3320 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003321}
3322
Andy Hung71742ab2023-07-07 13:47:37 -07003323ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003324{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003325 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003326 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003327 }
3328 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003329 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07003330 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003331 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003332 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003333 }
Kevin Rocard12381092018-04-11 09:19:59 -07003334 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003335 MetadataUpdate change;
3336 change.playbackMetadataUpdate = metadata.tracks;
3337 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003338}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003339
Andy Hung71742ab2023-07-07 13:47:37 -07003340void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003341 const StreamOutHalInterface::SourceMetadata& metadata)
3342{
3343 mOutput->stream->updateSourceMetadata(metadata);
3344};
3345
Andy Hung71742ab2023-07-07 13:47:37 -07003346status_t PlaybackThread::getRenderPosition(
Andy Hung4989d312023-06-29 21:19:25 -07003347 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003348{
3349 if (halFrames == NULL || dspFrames == NULL) {
3350 return BAD_VALUE;
3351 }
3352 Mutex::Autolock _l(mLock);
3353 if (initCheck() != NO_ERROR) {
3354 return INVALID_OPERATION;
3355 }
Andy Hung818e7a32016-02-16 18:08:07 -08003356 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003357 *halFrames = framesWritten;
3358
3359 if (isSuspended()) {
3360 // return an estimation of rendered frames when the output is suspended
3361 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003362 *dspFrames = (uint32_t)
3363 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003364 return NO_ERROR;
3365 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003366 status_t status;
3367 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003368 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003369 *dspFrames = (size_t)frames;
3370 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003371 }
3372}
3373
Andy Hung71742ab2023-07-07 13:47:37 -07003374product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003375{
3376 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3377 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3378 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003379 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003380 }
3381 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003382 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003383 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003384 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003385 }
3386 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003387 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003388}
3389
3390
Andy Hung71742ab2023-07-07 13:47:37 -07003391AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003392{
3393 Mutex::Autolock _l(mLock);
3394 return mOutput;
3395}
3396
Andy Hung71742ab2023-07-07 13:47:37 -07003397AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003398{
3399 Mutex::Autolock _l(mLock);
3400 AudioStreamOut *output = mOutput;
3401 mOutput = NULL;
3402 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3403 // must push a NULL and wait for ack
3404 mOutputSink.clear();
3405 mPipeSink.clear();
3406 mNormalSink.clear();
3407 return output;
3408}
3409
3410// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07003411sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003412{
3413 if (mOutput == NULL) {
3414 return NULL;
3415 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003416 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003417}
3418
Andy Hung71742ab2023-07-07 13:47:37 -07003419uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003420{
3421 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3422}
3423
Andy Hung71742ab2023-07-07 13:47:37 -07003424status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003425{
3426 if (!isValidSyncEvent(event)) {
3427 return BAD_VALUE;
3428 }
3429
3430 Mutex::Autolock _l(mLock);
3431
3432 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003433 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003434 if (event->triggerSession() == track->sessionId()) {
3435 (void) track->setSyncEvent(event);
3436 return NO_ERROR;
3437 }
3438 }
3439
3440 return NAME_NOT_FOUND;
3441}
3442
Andy Hung71742ab2023-07-07 13:47:37 -07003443bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003444{
3445 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3446}
3447
Andy Hung71742ab2023-07-07 13:47:37 -07003448void PlaybackThread::threadLoop_removeTracks(
Andy Hung3ff4b552023-06-26 19:20:57 -07003449 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003450{
Andy Hungfe726a62018-09-27 15:17:25 -07003451 // Miscellaneous track cleanup when removed from the active list,
3452 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003453#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003454 for (const auto& track : tracksToRemove) {
3455 if (track->isExternalTrack()) {
3456 // to track the speaker usage
3457 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003458 }
3459 }
Andy Hungfe726a62018-09-27 15:17:25 -07003460#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003461}
3462
Andy Hung71742ab2023-07-07 13:47:37 -07003463void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003464{
3465 if (!mMasterMute) {
3466 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003467 if (mOutDeviceTypeAddrs.empty()) {
3468 ALOGD("ro.audio.silent is ignored since no output device is set");
3469 return;
3470 }
jiabinc52b1ff2019-10-31 17:20:42 -07003471 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003472 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3473 return;
3474 }
Eric Laurent81784c32012-11-19 14:55:58 -08003475 if (property_get("ro.audio.silent", value, "0") > 0) {
3476 char *endptr;
3477 unsigned long ul = strtoul(value, &endptr, 0);
3478 if (*endptr == '\0' && ul != 0) {
3479 ALOGD("Silence is golden");
3480 // The setprop command will not allow a property to be changed after
3481 // the first time it is set, so we don't have to worry about un-muting.
3482 setMasterMute_l(true);
3483 }
3484 }
3485 }
3486}
3487
3488// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07003489ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003490{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003491 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003492 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003493 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003494 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003495
3496 // If an NBAIO sink is present, use it to write the normal mixer's submix
3497 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003498
Andy Hung010a1a12014-03-13 13:57:33 -07003499 const size_t count = mBytesRemaining / mFrameSize;
3500
Simon Wilson2d590962012-11-29 15:18:50 -08003501 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003502 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung01b29482023-07-19 16:22:58 -07003503 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003504 if (screenState != mScreenState) {
3505 mScreenState = screenState;
3506 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3507 if (pipe != NULL) {
3508 pipe->setAvgFrames((mScreenState & 1) ?
3509 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3510 }
3511 }
Andy Hung010a1a12014-03-13 13:57:33 -07003512 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003513 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003514
Eric Laurent81784c32012-11-19 14:55:58 -08003515 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003516 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003517
Andy Hung8946a282018-04-19 20:04:56 -07003518#ifdef TEE_SINK
3519 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3520#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003521 } else {
3522 bytesWritten = framesWritten;
3523 }
3524 // otherwise use the HAL / AudioStreamOut directly
3525 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003527
Eric Laurentbfb1b832013-01-07 09:53:42 -08003528 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003529 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3530 mWriteAckSequence += 2;
3531 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003532 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003533 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003534 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003535 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003536 // FIXME We should have an implementation of timestamps for direct output threads.
3537 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003538 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003539 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003540
Eric Laurentbfb1b832013-01-07 09:53:42 -08003541 if (mUseAsyncWrite &&
3542 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3543 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003544 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003545 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003546 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003547 }
Eric Laurent81784c32012-11-19 14:55:58 -08003548 }
3549
Eric Laurent81784c32012-11-19 14:55:58 -08003550 mNumWrites++;
3551 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003552 if (mStandby) {
3553 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003554 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003555 mStandby = false;
3556 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003557 return bytesWritten;
3558}
3559
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003560// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003561void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003562 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003563{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003564 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003565 if (outputSink != nullptr) {
3566 outputSink->startMelComputation(processor);
3567 }
Vlad Popab042ee62022-10-20 18:05:00 +02003568}
3569
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003570// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003571void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003572{
3573 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003574 if (outputSink != nullptr) {
3575 outputSink->stopMelComputation();
3576 }
Vlad Popab042ee62022-10-20 18:05:00 +02003577}
3578
Andy Hung71742ab2023-07-07 13:47:37 -07003579void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003581 bool supportsDrain = false;
3582 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003583 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3584 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003585 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3586 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003588 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003589 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003590 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003591 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003592 }
3593}
3594
Andy Hung71742ab2023-07-07 13:47:37 -07003595void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003596{
Eric Laurent275e8e92014-11-30 15:14:47 -08003597 {
3598 Mutex::Autolock _l(mLock);
3599 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003600 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003601 track->invalidate();
3602 }
Andy Hungdae27702016-10-31 14:01:16 -07003603 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3604 // After we exit there are no more track changes sent to BatteryNotifier
3605 // because that requires an active threadLoop.
3606 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3607 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003608 }
Eric Laurent81784c32012-11-19 14:55:58 -08003609}
3610
3611/*
3612The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003613 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003614 - mActiveSleepTimeUs from activeSleepTimeUs()
3615 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003616 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3617 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003618 - maxPeriod from frame count and sample rate (MIXER only)
3619
3620The parameters that affect these derived values are:
3621 - frame count
3622 - frame size
3623 - sample rate
3624 - device type: A2DP or not
3625 - device latency
3626 - format: PCM or not
3627 - active sleep time
3628 - idle sleep time
3629*/
3630
Andy Hung71742ab2023-07-07 13:47:37 -07003631void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003632{
Andy Hung25c2dac2014-02-27 14:56:00 -08003633 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003634 mActiveSleepTimeUs = activeSleepTimeUs();
3635 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003636
Andy Hung18bef9b2023-07-20 21:31:38 -07003637 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003638
Eric Laurent42537be2016-01-08 17:16:42 -08003639 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3640 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003641 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003642 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3643 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3644 }
3645 }
Eric Laurent81784c32012-11-19 14:55:58 -08003646}
3647
Andy Hung71742ab2023-07-07 13:47:37 -07003648bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003649{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003650 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003651 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003652 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003653 size_t size = mTracks.size();
3654 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003655 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003656 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003657 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003658 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003659 }
3660 }
Eric Laurent13084622016-05-17 10:51:49 -07003661 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003662}
3663
Andy Hung71742ab2023-07-07 13:47:37 -07003664void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003665{
3666 Mutex::Autolock _l(mLock);
3667 invalidateTracks_l(streamType);
3668}
3669
Andy Hung71742ab2023-07-07 13:47:37 -07003670void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003671 Mutex::Autolock _l(mLock);
3672 invalidateTracks_l(portIds);
3673}
3674
Andy Hung71742ab2023-07-07 13:47:37 -07003675bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003676 bool trackMatch = false;
3677 const size_t size = mTracks.size();
3678 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003679 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003680 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3681 t->invalidate();
3682 portIds.erase(t->portId());
3683 trackMatch = true;
3684 }
3685 if (portIds.empty()) {
3686 break;
3687 }
3688 }
3689 return trackMatch;
3690}
3691
jiabinf042b9b2021-05-07 23:46:28 +00003692// getTrackById_l must be called with holding thread lock
Andy Hung71742ab2023-07-07 13:47:37 -07003693IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003694 audio_port_handle_t trackPortId) {
3695 for (size_t i = 0; i < mTracks.size(); i++) {
3696 if (mTracks[i]->portId() == trackPortId) {
3697 return mTracks[i].get();
3698 }
3699 }
3700 return nullptr;
3701}
3702
Andy Hung71742ab2023-07-07 13:47:37 -07003703status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003704{
Glenn Kastend848eb42016-03-08 13:42:11 -08003705 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003706 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003707 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003708
Andy Hungd3639922022-04-28 18:00:49 -07003709 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003710 if (!audio_is_global_session(session)) {
3711 // player sessions on a spatializer output will use a dedicated input buffer and
3712 // will either output multi channel to mEffectBuffer if the track is spatilaized
3713 // or stereo to mPostSpatializerBuffer if not spatialized.
3714 uint32_t channelMask;
3715 bool isSessionSpatialized =
3716 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3717 if (isSessionSpatialized) {
3718 channelMask = mMixerChannelMask;
3719 } else {
3720 channelMask = mChannelMask;
3721 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003722 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003723 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003724 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003725 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003726 &halInBuffer);
3727 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003728
Andy Hung2cbc2722023-07-17 17:05:00 -07003729 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003730 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3731 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3732 &halOutBuffer);
3733 if (result != OK) return result;
3734
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003735 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003736
Mikhail Naganov022b9952017-01-04 16:36:51 -08003737 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3738 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003739 } else {
3740 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3741 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3742 // mPostSpatializerBuffer as output buffer
3743 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung2cbc2722023-07-17 17:05:00 -07003744 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003745 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3746 if (result != OK) return result;
Andy Hung2cbc2722023-07-17 17:05:00 -07003747 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003748 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3749 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003750
Eric Laurentb62d0362021-10-26 17:40:18 +02003751 if (session == AUDIO_SESSION_DEVICE) {
3752 halInBuffer = halOutBuffer;
3753 }
3754 }
3755 } else {
Andy Hung2cbc2722023-07-17 17:05:00 -07003756 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003757 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3758 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3759 &halInBuffer);
3760 if (result != OK) return result;
3761 halOutBuffer = halInBuffer;
3762 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3763 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003764 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003765 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003766 // Only one effect chain can be present in direct output thread and it uses
3767 // the sink buffer as input
3768 if (mType != DIRECT) {
3769 size_t numSamples = mNormalFrameCount
3770 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3771 + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003772 const status_t allocateStatus =
3773 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003774 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003775 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003776 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003777
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003778 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003779 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3780 buffer, session);
3781 }
3782 }
3783 }
3784
3785 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003786 // Attach all tracks with same session ID to this chain.
3787 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003788 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003789 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003790 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3791 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003792 track->setMainBuffer(buffer);
3793 chain->incTrackCnt();
3794 }
3795 }
3796
3797 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003798 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003799 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003800 ALOGV("addEffectChain_l() activating track %p on session %d",
3801 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003802 chain->incActiveTrackCnt();
3803 }
3804 }
3805 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003806
Eric Laurentaaa44472014-09-12 17:41:50 -07003807 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003808 chain->setInBuffer(halInBuffer);
3809 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003810 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3811 // chains list in order to be processed last as it contains output device effects.
3812 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3813 // processing effects specific to an output stream before effects applied to all streams
3814 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003815 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3816 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003817 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003818 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003819 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003820 // Effect chain for other sessions are inserted at beginning of effect
3821 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003822 // sessions is not important.
3823 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003824 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3825 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003826 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003827 size_t size = mEffectChains.size();
3828 size_t i = 0;
3829 for (i = 0; i < size; i++) {
3830 if (mEffectChains[i]->sessionId() < session) {
3831 break;
3832 }
3833 }
3834 mEffectChains.insertAt(chain, i);
3835 checkSuspendOnAddEffectChain_l(chain);
3836
3837 return NO_ERROR;
3838}
3839
Andy Hung71742ab2023-07-07 13:47:37 -07003840size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003841{
Glenn Kastend848eb42016-03-08 13:42:11 -08003842 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003843
3844 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3845
3846 for (size_t i = 0; i < mEffectChains.size(); i++) {
3847 if (chain == mEffectChains[i]) {
3848 mEffectChains.removeAt(i);
3849 // detach all active tracks from the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003850 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003851 if (session == track->sessionId()) {
3852 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3853 chain.get(), session);
3854 chain->decActiveTrackCnt();
3855 }
3856 }
3857
3858 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003859 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003860 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003861 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003862 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003863 chain->decTrackCnt();
3864 }
3865 }
3866 break;
3867 }
3868 }
3869 return mEffectChains.size();
3870}
3871
Andy Hung71742ab2023-07-07 13:47:37 -07003872status_t PlaybackThread::attachAuxEffect(
Andy Hung3ff4b552023-06-26 19:20:57 -07003873 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003874{
3875 Mutex::Autolock _l(mLock);
3876 return attachAuxEffect_l(track, EffectId);
3877}
3878
Andy Hung71742ab2023-07-07 13:47:37 -07003879status_t PlaybackThread::attachAuxEffect_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07003880 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003881{
3882 status_t status = NO_ERROR;
3883
3884 if (EffectId == 0) {
3885 track->setAuxBuffer(0, NULL);
3886 } else {
3887 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hungbd72c542023-06-20 18:56:17 -07003888 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003889 if (effect != 0) {
3890 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3891 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3892 } else {
3893 status = INVALID_OPERATION;
3894 }
3895 } else {
3896 status = BAD_VALUE;
3897 }
3898 }
3899 return status;
3900}
3901
Andy Hung71742ab2023-07-07 13:47:37 -07003902void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003903{
3904 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003905 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003906 if (track->auxEffectId() == effectId) {
3907 attachAuxEffect_l(track, 0);
3908 }
3909 }
3910}
3911
Andy Hung71742ab2023-07-07 13:47:37 -07003912bool PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003913NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003914{
Andy Hung4bf583b2023-05-30 18:10:23 -07003915 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003916
Andy Hung3ff4b552023-06-26 19:20:57 -07003917 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003918
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003919 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003920 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003921
3922 // MIXER
3923 nsecs_t lastWarning = 0;
3924
3925 // DUPLICATING
3926 // FIXME could this be made local to while loop?
3927 writeFrames = 0;
3928
3929 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003930 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003931
Andy Hungd3639922022-04-28 18:00:49 -07003932 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003933 sleepTimeShift = 0;
3934 }
3935
3936 CpuStats cpuStats;
3937 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3938
3939 acquireWakeLock();
3940
Glenn Kasteneef598c2017-04-03 14:41:13 -07003941 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3942 // thread associated with this PlaybackThread.
3943 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3944 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003945 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3946 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003947 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003948 const char *logString = NULL;
3949
rago1bb90822017-05-02 18:31:48 -07003950 // Estimated time for next buffer to be written to hal. This is used only on
3951 // suspended mode (for now) to help schedule the wait time until next iteration.
3952 nsecs_t timeLoopNextNs = 0;
3953
Eric Laurent664539d2013-09-23 18:24:31 -07003954 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003955
Andy Hung2dbffc22018-08-08 18:50:41 -07003956 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003957
Eric Laurentb3f315a2021-07-13 15:09:05 +02003958 sendCheckOutputStageEffectsEvent();
3959
Andy Hung446f4df2019-02-21 12:26:41 -08003960 // loopCount is used for statistics and diagnostics.
3961 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003962 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003963 // Log merge requests are performed during AudioFlinger binder transactions, but
3964 // that does not cover audio playback. It's requested here for that reason.
Andy Hung2cbc2722023-07-17 17:05:00 -07003965 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003966
Eric Laurent81784c32012-11-19 14:55:58 -08003967 cpuStats.sample(myName);
3968
Andy Hungbd72c542023-06-20 18:56:17 -07003969 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003970 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003971 bool isHapticSessionSpatialized = false;
Andy Hung3ff4b552023-06-26 19:20:57 -07003972 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003973
Andy Hung2dbffc22018-08-08 18:50:41 -07003974 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3975 //
jiabinc52b1ff2019-10-31 17:20:42 -07003976 // Note: we access outDeviceTypes() outside of mLock.
3977 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003978 // Here, we try for the AF lock, but do not block on it as the latency
3979 // is more informational.
Andy Hung2ac52f12023-08-28 18:36:53 -07003980 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd63e79d2023-07-13 16:52:46 -07003981 std::vector<SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003982 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003983 status_t status = INVALID_OPERATION;
3984 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung2cbc2722023-07-17 17:05:00 -07003985 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd63e79d2023-07-13 16:52:46 -07003986 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003987 && swPatches.size() > 0) {
3988 status = swPatches[0].getLatencyMs_l(&latencyMs);
3989 downstreamPatchHandle = swPatches[0].getPatchHandle();
3990 }
3991 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003992 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003993 lastDownstreamPatchHandle = downstreamPatchHandle;
3994 }
3995 if (status == OK) {
3996 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003997 // latency of 5 seconds).
3998 const double minLatency = 0., maxLatency = 5000.;
3999 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004000 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004001 } else {
4002 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07004003 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004004 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004005 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004006 }
Andy Hung2cbc2722023-07-17 17:05:00 -07004007 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004008 }
4009 } else {
4010 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4011 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004012 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004013 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4014 }
4015 }
4016
Eric Laurentb3f315a2021-07-13 15:09:05 +02004017 if (mCheckOutputStageEffects.exchange(false)) {
4018 checkOutputStageEffects();
4019 }
4020
Vlad Popa7e81cea2023-01-19 16:34:16 +01004021 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08004022 { // scope for mLock
4023
4024 Mutex::Autolock _l(mLock);
4025
Eric Laurent021cf962014-05-13 10:18:14 -07004026 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004027 if (mCheckOutputStageEffects.load()) {
4028 continue;
4029 }
Eric Laurent10351942014-05-08 18:49:52 -07004030
Glenn Kasteneef598c2017-04-03 14:41:13 -07004031 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08004032 if (logString != NULL) {
4033 mNBLogWriter->logTimestamp();
4034 mNBLogWriter->log(logString);
4035 logString = NULL;
4036 }
4037
Dean Wheatley12473e92021-03-18 23:00:55 +11004038 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004039
Eric Laurent81784c32012-11-19 14:55:58 -08004040 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004041 if (mSignalPending) {
4042 // A signal was raised while we were unlocked
4043 mSignalPending = false;
4044 } else if (waitingAsyncCallback_l()) {
4045 if (exitPending()) {
4046 break;
4047 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004048 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004049 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004050 releaseWakeLock_l();
4051 released = true;
4052 }
Andy Hung10cbff12017-02-21 17:30:14 -08004053
4054 const int64_t waitNs = computeWaitTimeNs_l();
4055 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
4056 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
4057 if (status == TIMED_OUT) {
4058 mSignalPending = true; // if timeout recheck everything
4059 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004060 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004061 if (released) {
4062 acquireWakeLock_l();
4063 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004064 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4065 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004066
4067 continue;
4068 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004069 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004070 isSuspended()) {
4071 // put audio hardware into standby after short delay
4072 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004073
4074 threadLoop_standby();
4075
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004076 // This is where we go into standby
4077 if (!mStandby) {
4078 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004079 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004080 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004081 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004082 }
Andy Hungd0979812019-02-21 15:51:44 -08004083 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004084 }
4085
Eric Tan39ec8d62018-07-24 09:49:29 -07004086 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004087 // we're about to wait, flush the binder command buffer
4088 IPCThreadState::self()->flushCommands();
4089
4090 clearOutputTracks();
4091
4092 if (exitPending()) {
4093 break;
4094 }
4095
4096 releaseWakeLock_l();
4097 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004098 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004099 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004100 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004101 acquireWakeLock_l();
4102
4103 mMixerStatus = MIXER_IDLE;
4104 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4105 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004106 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004107 checkSilentMode_l();
4108
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004109 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4110 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004111 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004112 sleepTimeShift = 0;
4113 }
4114
4115 continue;
4116 }
4117 }
Eric Laurent81784c32012-11-19 14:55:58 -08004118 // mMixerStatusIgnoringFastTracks is also updated internally
4119 mMixerStatus = prepareTracks_l(&tracksToRemove);
4120
Andy Hungdae27702016-10-31 14:01:16 -07004121 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004122
Vlad Popa7e81cea2023-01-19 16:34:16 +01004123 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004124
Eric Laurent81784c32012-11-19 14:55:58 -08004125 // prevent any changes in effect chain list and in each effect chain
4126 // during mixing and effect process as the audio buffers could be deleted
4127 // or modified if an effect is created or deleted
4128 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004129
4130 // Determine which session to pick up haptic data.
4131 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004132 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004133 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004134 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004135 for (const auto& track : mActiveTracks) {
Andy Hungbd72c542023-06-20 18:56:17 -07004136 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004137 if (effectChain != nullptr
4138 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004139 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004140 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004141 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004142 break;
4143 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004144 if (activeHapticSessionId == AUDIO_SESSION_NONE
4145 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004146 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004147 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004148 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004149 }
4150 }
4151 }
4152
Andy Hungc1646382019-04-30 16:12:10 -07004153 // Acquire a local copy of active tracks with lock (release w/o lock).
4154 //
4155 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4156 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4157 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4158 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02004159
4160 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004161
Jiabin Huangfb476842022-12-06 03:18:10 +00004162 for (const auto &track : mActiveTracks ) {
4163 track->updateTeePatches();
4164 }
4165
Eric Laurent19952e12023-04-20 10:08:29 +02004166 // signal actual start of output stream when the render position reported by the kernel
4167 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004168 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4169 && (mKernelPositionOnStandby
4170 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004171 mHalStarted = true;
4172 mWaitHalStartCV.broadcast();
4173 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004174 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004175
Eric Laurentbfb1b832013-01-07 09:53:42 -08004176 if (mBytesRemaining == 0) {
4177 mCurrentWriteLength = 0;
4178 if (mMixerStatus == MIXER_TRACKS_READY) {
4179 // threadLoop_mix() sets mCurrentWriteLength
4180 threadLoop_mix();
4181 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4182 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004183 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184 // must be written to HAL
4185 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004186 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004187 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004188
4189 // Tally underrun frames as we are inserting 0s here.
4190 for (const auto& track : activeTracks) {
Andy Hung3ff4b552023-06-26 19:20:57 -07004191 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004192 && !track->isStopped()
4193 && !track->isPaused()
4194 && !track->isTerminated()) {
4195 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4196 __func__, track->id(), track->getTrackStateAsString(),
4197 mNormalFrameCount);
Andy Hung3ff4b552023-06-26 19:20:57 -07004198 track->audioTrackServerProxy()->tallyUnderrunFrames(
4199 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004200 }
4201 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004202 }
4203 }
Andy Hung98ef9782014-03-04 14:46:50 -08004204 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004205 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004206 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004207 // or mSinkBuffer (if there are no effects and there is no data already copied to
4208 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004209 //
4210 // This is done pre-effects computation; if effects change to
4211 // support higher precision, this needs to move.
4212 //
4213 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004214 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004215 uint32_t mixerChannelCount = mEffectBufferValid ?
4216 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004217 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004218 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4219 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4220
David Li88ee0902022-06-22 10:01:21 +08004221 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4222 // do these processes after effects are applied.
4223 if (!mEffectBufferValid) {
4224 // mono blend occurs for mixer threads only (not direct or offloaded)
4225 // and is handled here if we're going directly to the sink.
4226 if (requireMonoBlend()) {
4227 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4228 mNormalFrameCount, true /*limit*/);
4229 }
Andy Hung2ddee192015-12-18 17:34:44 -08004230
David Li88ee0902022-06-22 10:01:21 +08004231 if (!hasFastMixer()) {
4232 // Balance must take effect after mono conversion.
4233 // We do it here if there is no FastMixer.
4234 // mBalance detects zero balance within the class for speed
4235 // (not needed here).
4236 mBalance.setBalance(mMasterBalance.load());
4237 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4238 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004239 }
4240
Andy Hung98ef9782014-03-04 14:46:50 -08004241 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004242 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004243
4244 // If we're going directly to the sink and there are haptic channels,
4245 // we should adjust channels as the sample data is partially interleaved
4246 // in this case.
4247 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4248 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4249 mChannelCount + mHapticChannelCount,
4250 audio_bytes_per_sample(format),
4251 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4252 }
Andy Hung98ef9782014-03-04 14:46:50 -08004253 }
4254
Eric Laurentbfb1b832013-01-07 09:53:42 -08004255 mBytesRemaining = mCurrentWriteLength;
4256 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004257 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4258 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4259 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4260 mBytesWritten += mBytesRemaining;
4261 mFramesWritten += framesRemaining;
4262 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004263 mBytesRemaining = 0;
4264 }
Eric Laurent81784c32012-11-19 14:55:58 -08004265
Eric Laurentbfb1b832013-01-07 09:53:42 -08004266 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004267 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004268 for (size_t i = 0; i < effectChains.size(); i ++) {
4269 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004270 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004271 if (activeHapticSessionId != AUDIO_SESSION_NONE
4272 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004273 // Haptic data is active in this case, copy it directly from
4274 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004275 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4276 audio_channel_count_from_out_mask(mMixerChannelMask) :
4277 mChannelCount;
4278 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4279 hapticSessionChannelCount = mChannelCount;
4280 }
4281
jiabin47affe52019-04-04 18:02:07 -07004282 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004283 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004284 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004285 memcpy_by_audio_format(
4286 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004287 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004288 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004289 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004290 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004291 }
Eric Laurent81784c32012-11-19 14:55:58 -08004292 }
4293 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004294 // Process effect chains for offloaded thread even if no audio
4295 // was read from audio track: process only updates effect state
4296 // and thus does have to be synchronized with audio writes but may have
4297 // to be called while waiting for async write callback
4298 if (mType == OFFLOAD) {
4299 for (size_t i = 0; i < effectChains.size(); i ++) {
4300 effectChains[i]->process_l();
4301 }
4302 }
Eric Laurent81784c32012-11-19 14:55:58 -08004303
Andy Hung98ef9782014-03-04 14:46:50 -08004304 // Only if the Effects buffer is enabled and there is data in the
4305 // Effects buffer (buffer valid), we need to
4306 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004307 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004308 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004309 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004310 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004311 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004312 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004313 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004314 }
4315
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004316 if (!hasFastMixer()) {
4317 // Balance must take effect after mono conversion.
4318 // We do it here if there is no FastMixer.
4319 // mBalance detects zero balance within the class for speed (not needed here).
4320 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004321 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004322 }
4323
Eric Laurentb62d0362021-10-26 17:40:18 +02004324 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4325 // mPostSpatializerBuffer if the haptics track is spatialized.
4326 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4327 // For other thread types, the haptics channels are already in mEffectBuffer.
4328 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4329 const size_t srcBufferSize = mNormalFrameCount *
4330 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4331 mEffectBufferFormat);
4332 const size_t dstBufferSize = mNormalFrameCount
4333 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4334
4335 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4336 mEffectBufferFormat,
4337 (uint8_t*)mEffectBuffer + srcBufferSize,
4338 mEffectBufferFormat,
4339 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004340 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004341 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4342 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4343 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4344 // Clamp PCM float values more than this distance from 0 to insulate
4345 // a HAL which doesn't handle NaN correctly.
4346 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4347 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4348 static_cast<const float*>(effectBuffer),
4349 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4350 } else {
4351 memcpy_by_audio_format(mSinkBuffer, mFormat,
4352 effectBuffer, mEffectBufferFormat, framesToCopy);
4353 }
jiabin245cdd92018-12-07 17:55:15 -08004354 // The sample data is partially interleaved when haptic channels exist,
4355 // we need to adjust channels here.
4356 if (mHapticChannelCount > 0) {
4357 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4358 mChannelCount + mHapticChannelCount,
4359 audio_bytes_per_sample(mFormat),
4360 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4361 }
Andy Hung98ef9782014-03-04 14:46:50 -08004362 }
4363
Eric Laurent81784c32012-11-19 14:55:58 -08004364 // enable changes in effect chain
4365 unlockEffectChains(effectChains);
4366
Vlad Popafce10862023-02-03 10:37:07 +01004367 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004368 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004369 metadataUpdate.playbackMetadataUpdate);
4370 }
4371
Eric Laurentbfb1b832013-01-07 09:53:42 -08004372 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004373 // mSleepTimeUs == 0 means we must write to audio hardware
4374 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004375 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004376 // writePeriodNs is updated >= 0 when ret > 0.
4377 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004378 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004379 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004380 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004381 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004382 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004383 if (ret < 0) {
4384 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004385 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004386 mBytesWritten += ret;
4387 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004388 const int64_t frames = ret / mFrameSize;
4389 mFramesWritten += frames;
4390
4391 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4392 // process information relating to write time.
4393 if (audio_has_proportional_frames(mFormat)) {
4394 // we are in a continuous mixing cycle
4395 if (mMixerStatus == MIXER_TRACKS_READY &&
4396 loopCount == lastLoopCountWritten + 1) {
4397
4398 const double jitterMs =
4399 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4400 {frames, writePeriodNs},
4401 {0, 0} /* lastTimestamp */, mSampleRate);
4402 const double processMs =
4403 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4404
4405 Mutex::Autolock _l(mLock);
4406 mIoJitterMs.add(jitterMs);
4407 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004408
4409 if (mPipeSink.get() != nullptr) {
4410 // Using the Monopipe availableToWrite, we estimate the current
4411 // buffer size.
4412 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4413 const ssize_t
4414 availableToWrite = mPipeSink->availableToWrite();
4415 const size_t pipeFrames = monoPipe->maxFrames();
4416 const size_t
4417 remainingFrames = pipeFrames - max(availableToWrite, 0);
4418 mMonopipePipeDepthStats.add(remainingFrames);
4419 }
Andy Hung446f4df2019-02-21 12:26:41 -08004420 }
4421
4422 // write blocked detection
4423 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004424 if ((mType == MIXER || mType == SPATIALIZER)
4425 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004426 mNumDelayedWrites++;
4427 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4428 ATRACE_NAME("underrun");
4429 ALOGW("write blocked for %lld msecs, "
4430 "%d delayed writes, thread %d",
4431 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4432 mNumDelayedWrites, mId);
4433 lastWarning = lastIoEndNs;
4434 }
4435 }
4436 }
4437 // update timing info.
4438 mLastIoBeginNs = lastIoBeginNs;
4439 mLastIoEndNs = lastIoEndNs;
4440 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004441 }
4442 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4443 (mMixerStatus == MIXER_DRAIN_ALL)) {
4444 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004445 }
Andy Hungd3639922022-04-28 18:00:49 -07004446 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004447
4448 if (mThreadThrottle
4449 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004450 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004451 // Limit MixerThread data processing to no more than twice the
4452 // expected processing rate.
4453 //
4454 // This helps prevent underruns with NuPlayer and other applications
4455 // which may set up buffers that are close to the minimum size, or use
4456 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4457 //
4458 // The throttle smooths out sudden large data drains from the device,
4459 // e.g. when it comes out of standby, which often causes problems with
4460 // (1) mixer threads without a fast mixer (which has its own warm-up)
4461 // (2) minimum buffer sized tracks (even if the track is full,
4462 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004463 //
4464 // Total time spent in last processing cycle equals time spent in
4465 // 1. threadLoop_write, as well as time spent in
4466 // 2. threadLoop_mix (significant for heavy mixing, especially
4467 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004468
Andy Hung446f4df2019-02-21 12:26:41 -08004469 // it's OK if deltaMs is an overestimate.
4470
4471 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004472
Ivan Lozanoea04d392017-11-07 14:37:07 -08004473 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004474 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004475 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004476
Andy Hung08fb1742015-05-31 23:22:10 -07004477 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004478 // notify of throttle start on verbose log
4479 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4480 "mixer(%p) throttle begin:"
4481 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004482 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004483 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004484 // Throttle must be attributed to the previous mixer loop's write time
4485 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004486 // This also ensures proper timing statistics.
4487 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004488 } else {
4489 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4490 if (diff > 0) {
4491 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004492 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004493 ALOGD_IF(!isSingleDeviceType(
4494 outDeviceTypes(), audio_is_a2dp_out_device) &&
4495 !isSingleDeviceType(
4496 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004497 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004498 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4499 }
Andy Hung08fb1742015-05-31 23:22:10 -07004500 }
4501 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004502 }
Eric Laurent81784c32012-11-19 14:55:58 -08004503
Eric Laurentbfb1b832013-01-07 09:53:42 -08004504 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004505 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004506 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004507 // suspended requires accurate metering of sleep time.
4508 if (isSuspended()) {
4509 // advance by expected sleepTime
4510 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4511 const nsecs_t nowNs = systemTime();
4512
4513 // compute expected next time vs current time.
4514 // (negative deltas are treated as delays).
4515 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4516 if (deltaNs < -kMaxNextBufferDelayNs) {
4517 // Delays longer than the max allowed trigger a reset.
4518 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4519 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4520 timeLoopNextNs = nowNs + deltaNs;
4521 } else if (deltaNs < 0) {
4522 // Delays within the max delay allowed: zero the delta/sleepTime
4523 // to help the system catch up in the next iteration(s)
4524 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4525 deltaNs = 0;
4526 }
4527 // update sleep time (which is >= 0)
4528 mSleepTimeUs = deltaNs / 1000;
4529 }
Eric Laurente93cc032016-05-05 10:15:10 -07004530 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4531 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004532 }
Glenn Kastene7754022014-10-31 12:11:26 -07004533 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004534 }
Eric Laurent81784c32012-11-19 14:55:58 -08004535 }
4536
4537 // Finally let go of removed track(s), without the lock held
4538 // since we can't guarantee the destructors won't acquire that
4539 // same lock. This will also mutate and push a new fast mixer state.
4540 threadLoop_removeTracks(tracksToRemove);
4541 tracksToRemove.clear();
4542
4543 // FIXME I don't understand the need for this here;
4544 // it was in the original code but maybe the
4545 // assignment in saveOutputTracks() makes this unnecessary?
4546 clearOutputTracks();
4547
4548 // Effect chains will be actually deleted here if they were removed from
4549 // mEffectChains list during mixing or effects processing
4550 effectChains.clear();
4551
4552 // FIXME Note that the above .clear() is no longer necessary since effectChains
4553 // is now local to this block, but will keep it for now (at least until merge done).
4554 }
4555
Eric Laurentbfb1b832013-01-07 09:53:42 -08004556 threadLoop_exit();
4557
Eric Laurentcf817a22014-08-04 20:36:31 -07004558 if (!mStandby) {
4559 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004560 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004561 }
4562
4563 releaseWakeLock();
4564
4565 ALOGV("Thread %p type %d exiting", this, mType);
4566 return false;
4567}
4568
Andy Hung71742ab2023-07-07 13:47:37 -07004569void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004570{
Dean Wheatley12473e92021-03-18 23:00:55 +11004571 if (mStandby) {
4572 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4573 return;
4574 } else if (mHwPaused) {
4575 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4576 return;
4577 }
4578
4579 // Gather the framesReleased counters for all active tracks,
4580 // and associate with the sink frames written out. We need
4581 // this to convert the sink timestamp to the track timestamp.
4582 bool kernelLocationUpdate = false;
4583 ExtendedTimestamp timestamp; // use private copy to fetch
4584
4585 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4586 // HAL may be draining some small duration buffered data for fade out.
4587 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4588 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4589 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4590 mSampleRate);
4591
4592 if (isTimestampCorrectionEnabled()) {
4593 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4594 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4595 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4596 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4597 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4598 = correctedTimestamp.mFrames;
4599 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4600 = correctedTimestamp.mTimeNs;
4601 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4602 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4603 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4604
4605 // Note: Downstream latency only added if timestamp correction enabled.
4606 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4607 const int64_t newPosition =
4608 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4609 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4610 // prevent retrograde
4611 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4612 newPosition,
4613 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4614 - mSuspendedFrames));
4615 }
4616 }
4617
4618 // We always fetch the timestamp here because often the downstream
4619 // sink will block while writing.
4620
4621 // We keep track of the last valid kernel position in case we are in underrun
4622 // and the normal mixer period is the same as the fast mixer period, or there
4623 // is some error from the HAL.
4624 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4625 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4626 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4627 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4628 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4629
4630 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4631 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4632 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4633 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4634 }
4635
4636 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4637 kernelLocationUpdate = true;
4638 } else {
4639 ALOGVV("getTimestamp error - no valid kernel position");
4640 }
4641
4642 // copy over kernel info
4643 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4644 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4645 + mSuspendedFrames; // add frames discarded when suspended
4646 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4647 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4648 } else {
4649 mTimestampVerifier.error();
4650 }
4651
4652 // mFramesWritten for non-offloaded tracks are contiguous
4653 // even after standby() is called. This is useful for the track frame
4654 // to sink frame mapping.
4655 bool serverLocationUpdate = false;
4656 if (mFramesWritten != mLastFramesWritten) {
4657 serverLocationUpdate = true;
4658 mLastFramesWritten = mFramesWritten;
4659 }
4660 // Only update timestamps if there is a meaningful change.
4661 // Either the kernel timestamp must be valid or we have written something.
4662 if (kernelLocationUpdate || serverLocationUpdate) {
4663 if (serverLocationUpdate) {
4664 // use the time before we called the HAL write - it is a bit more accurate
4665 // to when the server last read data than the current time here.
4666 //
4667 // If we haven't written anything, mLastIoBeginNs will be -1
4668 // and we use systemTime().
4669 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4670 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4671 ? systemTime() : mLastIoBeginNs;
4672 }
4673
Andy Hung3ff4b552023-06-26 19:20:57 -07004674 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004675 if (!t->isFastTrack()) {
4676 t->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07004677 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004678 mFramesWritten,
4679 mSampleRate,
4680 mTimestamp);
4681 }
4682 }
4683 }
4684
4685 if (audio_has_proportional_frames(mFormat)) {
4686 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4687 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4688 mLatencyMs.add(latencyMs);
4689 }
4690 }
4691#if 0
4692 // logFormat example
4693 if (z % 100 == 0) {
4694 timespec ts;
4695 clock_gettime(CLOCK_MONOTONIC, &ts);
4696 LOGT("This is an integer %d, this is a float %f, this is my "
4697 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4698 LOGT("A deceptive null-terminated string %\0");
4699 }
4700 ++z;
4701#endif
4702}
4703
Eric Laurentbfb1b832013-01-07 09:53:42 -08004704// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07004705void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung71ba4b32022-10-06 12:09:49 -07004706NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004707{
Andy Hungfe726a62018-09-27 15:17:25 -07004708 for (const auto& track : tracksToRemove) {
4709 mActiveTracks.remove(track);
4710 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hungbd72c542023-06-20 18:56:17 -07004711 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004712 if (chain != 0) {
4713 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4714 __func__, track->id(), chain.get(), track->sessionId());
4715 chain->decActiveTrackCnt();
4716 }
4717 // If an external client track, inform APM we're no longer active, and remove if needed.
4718 // We do this under lock so that the state is consistent if the Track is destroyed.
4719 if (track->isExternalTrack()) {
4720 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004721 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004722 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004723 }
4724 }
Andy Hungfe726a62018-09-27 15:17:25 -07004725 if (track->isTerminated()) {
4726 // remove from our tracks vector
4727 removeTrack_l(track);
4728 }
jiabineb3bda02020-06-30 14:07:03 -07004729 if (mHapticChannelCount > 0 &&
4730 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4731 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004732 mLock.unlock();
4733 // Unlock due to VibratorService will lock for this call and will
4734 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung9554ec02023-07-20 21:23:42 -07004735 afutils::onExternalVibrationStop(track->getExternalVibration());
jiabin57303cc2018-12-18 15:45:57 -08004736 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004737
4738 // When the track is stop, set the haptic intensity as MUTE
4739 // for the HapticGenerator effect.
4740 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004741 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004742 }
jiabin245cdd92018-12-07 17:55:15 -08004743 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004744 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004745}
Eric Laurent81784c32012-11-19 14:55:58 -08004746
Andy Hung71742ab2023-07-07 13:47:37 -07004747status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004748{
4749 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004750 ExtendedTimestamp ets;
4751 status_t status = mNormalSink->getTimestamp(ets);
4752 if (status == NO_ERROR) {
4753 status = ets.getBestTimestamp(&timestamp);
4754 }
4755 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004756 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004757 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004758 collectTimestamps_l();
4759 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4760 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004761 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004762 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4763 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4764 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4765 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4766 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004767 }
4768 return INVALID_OPERATION;
4769}
Eric Laurent1c333e22014-05-20 10:48:17 -07004770
Eric Laurenteab90452019-06-24 15:17:46 -07004771// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4772// still applied by the mixer.
4773// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4774// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4775// if more than one track are active
Andy Hung71742ab2023-07-07 13:47:37 -07004776status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004777{
4778 status_t result = NO_ERROR;
4779 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4780 if (*volume != mLeftVolFloat) {
4781 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004782 // HAL can return INVALID_OPERATION if operation is not supported.
4783 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004784 "Error when setting output stream volume: %d", result);
4785 if (result == NO_ERROR) {
4786 mLeftVolFloat = *volume;
4787 }
4788 }
4789 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4790 // remove stream volume contribution from software volume.
4791 if (mLeftVolFloat == *volume) {
4792 *volume = 1.0f;
4793 }
4794 }
4795 return result;
4796}
4797
Andy Hung71742ab2023-07-07 13:47:37 -07004798status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004799 audio_patch_handle_t *handle)
4800{
Andy Hungf60abce2016-08-26 11:37:54 -07004801 status_t status;
4802 if (property_get_bool("af.patch_park", false /* default_value */)) {
4803 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4804 // or if HAL does not properly lock against access.
4805 AutoPark<FastMixer> park(mFastMixer);
4806 status = PlaybackThread::createAudioPatch_l(patch, handle);
4807 } else {
4808 status = PlaybackThread::createAudioPatch_l(patch, handle);
4809 }
Eric Laurentb0463942022-12-20 16:31:10 +01004810
4811 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004812 return status;
4813}
4814
Andy Hung71742ab2023-07-07 13:47:37 -07004815status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004816 audio_patch_handle_t *handle)
4817{
4818 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004819
4820 // store new device and send to effects
4821 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004822 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004823 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004824 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4825 && !mOutput->audioHwDev->supportsAudioPatches(),
4826 "Enumerated device type(%#x) must not be used "
4827 "as it does not support audio patches",
4828 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004829 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004830 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4831 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004832 }
4833
François Gaffie0c280aa2018-07-25 10:02:15 +02004834 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004835#ifdef ADD_BATTERY_DATA
4836 // when changing the audio output device, call addBatteryData to notify
4837 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004838 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004839 uint32_t params = 0;
4840 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004841 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004842 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004843 }
4844
Eric Laurent054d9d32015-04-24 08:48:48 -07004845 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004846 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004847 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4848 }
4849
4850 if (params != 0) {
4851 addBatteryData(params);
4852 }
4853 }
4854#endif
4855
4856 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004857 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004858 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004859
jiabinc52b1ff2019-10-31 17:20:42 -07004860 // mPatch.num_sinks is not set when the thread is created so that
4861 // the first patch creation triggers an ioConfigChanged callback
4862 bool configChanged = (mPatch.num_sinks == 0) ||
4863 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004864 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004865 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004866 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004867
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004868 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004869 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4870 status = hwDevice->createAudioPatch(patch->num_sources,
4871 patch->sources,
4872 patch->num_sinks,
4873 patch->sinks,
4874 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004875 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004876 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004877 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004878 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004879 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004880
4881 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004882 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004883 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004884 // also dispatch to active AudioTracks for MediaMetrics
4885 for (const auto &track : mActiveTracks) {
4886 track->logEndInterval();
4887 track->logBeginInterval(patchSinksAsString);
4888 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004889
Eric Laurente8726fe2015-06-26 09:39:24 -07004890 if (configChanged) {
4891 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4892 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004893 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004894 mActiveTracks.setHasChanged();
4895
Eric Laurent1c333e22014-05-20 10:48:17 -07004896 return status;
4897}
4898
Andy Hung71742ab2023-07-07 13:47:37 -07004899status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004900{
Andy Hungf60abce2016-08-26 11:37:54 -07004901 status_t status;
4902 if (property_get_bool("af.patch_park", false /* default_value */)) {
4903 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4904 // or if HAL does not properly lock against access.
4905 AutoPark<FastMixer> park(mFastMixer);
4906 status = PlaybackThread::releaseAudioPatch_l(handle);
4907 } else {
4908 status = PlaybackThread::releaseAudioPatch_l(handle);
4909 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004910 return status;
4911}
4912
Andy Hung71742ab2023-07-07 13:47:37 -07004913status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004914{
4915 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004916
jiabinc52b1ff2019-10-31 17:20:42 -07004917 mPatch = audio_patch{};
4918 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004919
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004920 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004921 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4922 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004923 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004924 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004925 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004926 // Force meteadata update after a route change
4927 mActiveTracks.setHasChanged();
4928
Eric Laurent1c333e22014-05-20 10:48:17 -07004929 return status;
4930}
4931
Andy Hung71742ab2023-07-07 13:47:37 -07004932void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004933{
4934 Mutex::Autolock _l(mLock);
4935 mTracks.add(track);
4936}
4937
Andy Hung71742ab2023-07-07 13:47:37 -07004938void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004939{
4940 Mutex::Autolock _l(mLock);
4941 destroyTrack_l(track);
4942}
4943
Andy Hung71742ab2023-07-07 13:47:37 -07004944void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004945{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004946 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004947 config->role = AUDIO_PORT_ROLE_SOURCE;
4948 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4949 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004950 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4951 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4952 config->flags.output = mOutput->flags;
4953 }
Eric Laurent83b88082014-06-20 18:31:16 -07004954}
4955
Eric Laurent81784c32012-11-19 14:55:58 -08004956// ----------------------------------------------------------------------------
4957
Andy Hung71742ab2023-07-07 13:47:37 -07004958/* static */
4959sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07004960 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung71742ab2023-07-07 13:47:37 -07004961 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004962 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07004963}
4964
Andy Hung2cbc2722023-07-17 17:05:00 -07004965MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004966 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07004967 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004968 // mAudioMixer below
4969 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004970 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004971 mFastMixerFutex(0),
4972 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004973 // mOutputSink below
4974 // mPipeSink below
4975 // mNormalSink below
4976{
Andy Hung2cbc2722023-07-17 17:05:00 -07004977 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004978 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004979 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004980 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004981 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4982 mNormalFrameCount);
4983 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4984
Andy Hungfbfc3952015-01-15 13:33:51 -08004985 if (type == DUPLICATING) {
4986 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4987 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4988 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4989 return;
4990 }
Eric Laurent81784c32012-11-19 14:55:58 -08004991 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004992 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004993 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004994 const NBAIO_Format offers[1] = {Format_from_SR_C(
4995 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004996#if !LOG_NDEBUG
4997 ssize_t index =
4998#else
4999 (void)
5000#endif
5001 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005002 ALOG_ASSERT(index == 0);
5003
5004 // initialize fast mixer depending on configuration
5005 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005006 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005007 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005008 } else {
5009 switch (kUseFastMixer) {
5010 case FastMixer_Never:
5011 initFastMixer = false;
5012 break;
5013 case FastMixer_Always:
5014 initFastMixer = true;
5015 break;
5016 case FastMixer_Static:
5017 case FastMixer_Dynamic:
5018 initFastMixer = mFrameCount < mNormalFrameCount;
5019 break;
5020 }
5021 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5022 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5023 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005024 }
5025 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005026 audio_format_t fastMixerFormat;
5027 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5028 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5029 } else {
5030 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5031 }
5032 if (mFormat != fastMixerFormat) {
5033 // change our Sink format to accept our intermediate precision
5034 mFormat = fastMixerFormat;
5035 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005036 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005037 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5038 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5039 }
Eric Laurent81784c32012-11-19 14:55:58 -08005040
5041 // create a MonoPipe to connect our submix to FastMixer
5042 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005043
Andy Hung1258c1a2014-05-23 21:22:17 -07005044 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005045 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005046 format.mFormat = fastMixerFormat;
5047 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5048
Eric Laurent81784c32012-11-19 14:55:58 -08005049 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5050 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5051 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5052 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07005053 const NBAIO_Format offersFast[1] = {format};
5054 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005055#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005056 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005057#else
5058 (void)
5059#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07005060 monoPipe->negotiate(offersFast, std::size(offersFast),
5061 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005062 ALOG_ASSERT(index == 0);
5063 monoPipe->setAvgFrames((mScreenState & 1) ?
5064 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5065 mPipeSink = monoPipe;
5066
Eric Laurent81784c32012-11-19 14:55:58 -08005067 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005068 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005069 FastMixerStateQueue *sq = mFastMixer->sq();
5070#ifdef STATE_QUEUE_DUMP
5071 sq->setObserverDump(&mStateQueueObserverDump);
5072 sq->setMutatorDump(&mStateQueueMutatorDump);
5073#endif
5074 FastMixerState *state = sq->begin();
5075 FastTrack *fastTrack = &state->mFastTracks[0];
5076 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5077 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5078 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005079 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5080 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5081 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005082 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005083 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005084 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005085 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005086 fastTrack->mGeneration++;
5087 state->mFastTracksGen++;
5088 state->mTrackMask = 1;
5089 // fast mixer will use the HAL output sink
5090 state->mOutputSink = mOutputSink.get();
5091 state->mOutputSinkGen++;
5092 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005093 // specify sink channel mask when haptic channel mask present as it can not
5094 // be calculated directly from channel count
5095 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005096 ? AUDIO_CHANNEL_NONE
5097 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005098 state->mCommand = FastMixerState::COLD_IDLE;
5099 // already done in constructor initialization list
5100 //mFastMixerFutex = 0;
5101 state->mColdFutexAddr = &mFastMixerFutex;
5102 state->mColdGen++;
5103 state->mDumpState = &mFastMixerDumpState;
Andy Hung2cbc2722023-07-17 17:05:00 -07005104 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005105 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005106 sq->end();
5107 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5108
Eric Tan0513b5d2018-09-17 10:32:48 -07005109 NBLog::thread_info_t info;
5110 info.id = mId;
5111 info.type = NBLog::FASTMIXER;
5112 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5113
Eric Laurent81784c32012-11-19 14:55:58 -08005114 // start the fast mixer
5115 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5116 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005117 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005118 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005119
5120#ifdef AUDIO_WATCHDOG
5121 // create and start the watchdog
5122 mAudioWatchdog = new AudioWatchdog();
5123 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5124 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5125 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005126 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005127#endif
Andy Hung8946a282018-04-19 20:04:56 -07005128 } else {
5129#ifdef TEE_SINK
5130 // Only use the MixerThread tee if there is no FastMixer.
5131 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5132 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5133#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005134 }
5135
5136 switch (kUseFastMixer) {
5137 case FastMixer_Never:
5138 case FastMixer_Dynamic:
5139 mNormalSink = mOutputSink;
5140 break;
5141 case FastMixer_Always:
5142 mNormalSink = mPipeSink;
5143 break;
5144 case FastMixer_Static:
5145 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5146 break;
5147 }
5148}
5149
Andy Hung71742ab2023-07-07 13:47:37 -07005150MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005151{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005152 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005153 FastMixerStateQueue *sq = mFastMixer->sq();
5154 FastMixerState *state = sq->begin();
5155 if (state->mCommand == FastMixerState::COLD_IDLE) {
5156 int32_t old = android_atomic_inc(&mFastMixerFutex);
5157 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005158 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005159 }
5160 }
5161 state->mCommand = FastMixerState::EXIT;
5162 sq->end();
5163 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5164 mFastMixer->join();
5165 // Though the fast mixer thread has exited, it's state queue is still valid.
5166 // We'll use that extract the final state which contains one remaining fast track
5167 // corresponding to our sub-mix.
5168 state = sq->begin();
5169 ALOG_ASSERT(state->mTrackMask == 1);
5170 FastTrack *fastTrack = &state->mFastTracks[0];
5171 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5172 delete fastTrack->mBufferProvider;
5173 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005174 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005175#ifdef AUDIO_WATCHDOG
5176 if (mAudioWatchdog != 0) {
5177 mAudioWatchdog->requestExit();
5178 mAudioWatchdog->requestExitAndWait();
5179 mAudioWatchdog.clear();
5180 }
5181#endif
5182 }
Andy Hung2cbc2722023-07-17 17:05:00 -07005183 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005184 delete mAudioMixer;
5185}
5186
Andy Hung71742ab2023-07-07 13:47:37 -07005187void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005188 PlaybackThread::onFirstRef();
5189
5190 Mutex::Autolock _l(mLock);
5191 if (mOutput != nullptr && mOutput->stream != nullptr) {
5192 status_t status = mOutput->stream->setLatencyModeCallback(this);
5193 if (status != INVALID_OPERATION) {
5194 updateHalSupportedLatencyModes_l();
5195 }
5196 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5197 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5198 mBluetoothLatencyModesEnabled.store(
5199 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5200 }
5201}
Eric Laurent81784c32012-11-19 14:55:58 -08005202
Andy Hung71742ab2023-07-07 13:47:37 -07005203uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005204{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005205 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005206 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5207 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5208 }
5209 return latency;
5210}
5211
Andy Hung71742ab2023-07-07 13:47:37 -07005212ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005213{
5214 // FIXME we should only do one push per cycle; confirm this is true
5215 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005216 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005217 FastMixerStateQueue *sq = mFastMixer->sq();
5218 FastMixerState *state = sq->begin();
5219 if (state->mCommand != FastMixerState::MIX_WRITE &&
5220 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5221 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005222
5223 // FIXME workaround for first HAL write being CPU bound on some devices
5224 ATRACE_BEGIN("write");
5225 mOutput->write((char *)mSinkBuffer, 0);
5226 ATRACE_END();
5227
Eric Laurent81784c32012-11-19 14:55:58 -08005228 int32_t old = android_atomic_inc(&mFastMixerFutex);
5229 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005230 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005231 }
5232#ifdef AUDIO_WATCHDOG
5233 if (mAudioWatchdog != 0) {
5234 mAudioWatchdog->resume();
5235 }
5236#endif
5237 }
5238 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005239#ifdef FAST_THREAD_STATISTICS
Andy Hung2cbc2722023-07-17 17:05:00 -07005240 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005241 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005242#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005243 sq->end();
5244 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5245 if (kUseFastMixer == FastMixer_Dynamic) {
5246 mNormalSink = mPipeSink;
5247 }
5248 } else {
5249 sq->end(false /*didModify*/);
5250 }
5251 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005252 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005253}
5254
Andy Hung71742ab2023-07-07 13:47:37 -07005255void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005256{
5257 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005258 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005259 FastMixerStateQueue *sq = mFastMixer->sq();
5260 FastMixerState *state = sq->begin();
5261 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005262 // Report any frames trapped in the Monopipe
5263 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5264 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5265 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5266 "monoPipeWritten:%lld monoPipeLeft:%lld",
5267 (long long)mFramesWritten, (long long)mSuspendedFrames,
5268 (long long)mPipeSink->framesWritten(), pipeFrames);
5269 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5270
Eric Laurent81784c32012-11-19 14:55:58 -08005271 state->mCommand = FastMixerState::COLD_IDLE;
5272 state->mColdFutexAddr = &mFastMixerFutex;
5273 state->mColdGen++;
5274 mFastMixerFutex = 0;
5275 sq->end();
5276 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5277 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5278 if (kUseFastMixer == FastMixer_Dynamic) {
5279 mNormalSink = mOutputSink;
5280 }
5281#ifdef AUDIO_WATCHDOG
5282 if (mAudioWatchdog != 0) {
5283 mAudioWatchdog->pause();
5284 }
5285#endif
5286 } else {
5287 sq->end(false /*didModify*/);
5288 }
5289 }
5290 PlaybackThread::threadLoop_standby();
5291}
5292
Andy Hung71742ab2023-07-07 13:47:37 -07005293bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005294{
5295 return false;
5296}
5297
Andy Hung71742ab2023-07-07 13:47:37 -07005298bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299{
5300 return !mStandby;
5301}
5302
Andy Hung71742ab2023-07-07 13:47:37 -07005303bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304{
5305 Mutex::Autolock _l(mLock);
5306 return waitingAsyncCallback_l();
5307}
5308
Eric Laurent81784c32012-11-19 14:55:58 -08005309// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07005310void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005311{
5312 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005313 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005314 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005315 // discard any pending drain or write ack by incrementing sequence
5316 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5317 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005318 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005319 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5320 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005321 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005322 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005323 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005324}
5325
Andy Hung71742ab2023-07-07 13:47:37 -07005326void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005327{
5328 ALOGV("signal playback thread");
5329 broadcast_l();
5330}
5331
Andy Hung71742ab2023-07-07 13:47:37 -07005332void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005333{
5334 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5335 invalidateTracks((audio_stream_type_t)i);
5336 }
5337}
5338
Andy Hung71742ab2023-07-07 13:47:37 -07005339void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005340{
Eric Laurent81784c32012-11-19 14:55:58 -08005341 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005342 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005343 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005344 // increase sleep time progressively when application underrun condition clears.
5345 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5346 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5347 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005348 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005349 sleepTimeShift--;
5350 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005351 mSleepTimeUs = 0;
5352 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005353 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005354
Eric Laurent81784c32012-11-19 14:55:58 -08005355}
5356
Andy Hung71742ab2023-07-07 13:47:37 -07005357void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005358{
5359 // If no tracks are ready, sleep once for the duration of an output
5360 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005361 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005362 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005363 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5364 // Using the Monopipe availableToWrite, we estimate the
5365 // sleep time to retry for more data (before we underrun).
5366 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5367 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5368 const size_t pipeFrames = monoPipe->maxFrames();
5369 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5370 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5371 const size_t framesDelay = std::min(
5372 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5373 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5374 pipeFrames, framesLeft, framesDelay);
5375 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5376 } else {
5377 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5378 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5379 mSleepTimeUs = kMinThreadSleepTimeUs;
5380 }
5381 // reduce sleep time in case of consecutive application underruns to avoid
5382 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5383 // duration we would end up writing less data than needed by the audio HAL if
5384 // the condition persists.
5385 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5386 sleepTimeShift++;
5387 }
Eric Laurent81784c32012-11-19 14:55:58 -08005388 }
5389 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005390 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005391 }
5392 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005393 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5394 // before effects processing or output.
5395 if (mMixerBufferValid) {
5396 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005397 if (mType == SPATIALIZER) {
5398 memset(mSinkBuffer, 0, mSinkBufferSize);
5399 }
Andy Hung98ef9782014-03-04 14:46:50 -08005400 } else {
5401 memset(mSinkBuffer, 0, mSinkBufferSize);
5402 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005403 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005404 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5405 "anticipated start");
5406 }
5407 // TODO add standby time extension fct of effect tail
5408}
5409
5410// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07005411PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07005412 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005413{
Andy Hungc0691382018-09-12 18:01:57 -07005414 // clean up deleted track ids in AudioMixer before allocating new tracks
5415 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5416 // for each trackId, destroy it in the AudioMixer
5417 if (mAudioMixer->exists(trackId)) {
5418 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005419 }
5420 });
Andy Hungc0691382018-09-12 18:01:57 -07005421 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005422
5423 mixer_state mixerStatus = MIXER_IDLE;
5424 // find out which tracks need to be processed
5425 size_t count = mActiveTracks.size();
5426 size_t mixedTracks = 0;
5427 size_t tracksWithEffect = 0;
5428 // counts only _active_ fast tracks
5429 size_t fastTracks = 0;
5430 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5431
5432 float masterVolume = mMasterVolume;
5433 bool masterMute = mMasterMute;
5434
5435 if (masterMute) {
5436 masterVolume = 0;
5437 }
5438 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hungbd72c542023-06-20 18:56:17 -07005439 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005440 if (chain != 0) {
5441 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5442 chain->setVolume_l(&v, &v);
5443 masterVolume = (float)((v + (1 << 23)) >> 24);
5444 chain.clear();
5445 }
5446
5447 // prepare a new state to push
5448 FastMixerStateQueue *sq = NULL;
5449 FastMixerState *state = NULL;
5450 bool didModify = false;
5451 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005452 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005453 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005454 sq = mFastMixer->sq();
5455 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005456 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005457 }
5458
Andy Hung69aed5f2014-02-25 17:24:40 -08005459 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005460 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005461
Andy Hungbd3b2b02018-05-21 10:53:11 -07005462 // DeferredOperations handles statistics after setting mixerStatus.
5463 class DeferredOperations {
5464 public:
Andy Hungea840382020-05-05 21:50:17 -07005465 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5466 : mMixerStatus(mixerStatus)
5467 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005468
5469 // when leaving scope, tally frames properly.
5470 ~DeferredOperations() {
5471 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5472 // because that is when the underrun occurs.
5473 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005474 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005475 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005476 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005477 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005478 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005479 }
5480 }
Andy Hungea840382020-05-05 21:50:17 -07005481 // send the max underrun frames for this mixer period
5482 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005483 }
5484
5485 // tallyUnderrunFrames() is called to update the track counters
5486 // with the number of underrun frames for a particular mixer period.
5487 // We defer tallying until we know the final mixer status.
Andy Hung3ff4b552023-06-26 19:20:57 -07005488 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005489 mUnderrunFrames.emplace_back(track, underrunFrames);
5490 }
5491
5492 private:
5493 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005494 ThreadMetrics * const mThreadMetrics;
Andy Hung3ff4b552023-06-26 19:20:57 -07005495 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005496 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005497 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005498
jiabin245cdd92018-12-07 17:55:15 -08005499 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005500 for (size_t i=0 ; i<count ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005501 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005502
5503 // this const just means the local variable doesn't change
Andy Hung3ff4b552023-06-26 19:20:57 -07005504 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005505
5506 // process fast tracks
5507 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005508 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5509 "%s(%d): FastTrack(%d) present without FastMixer",
5510 __func__, id(), track->id());
5511
jiabin245cdd92018-12-07 17:55:15 -08005512 if (track->getHapticPlaybackEnabled()) {
5513 noFastHapticTrack = false;
5514 }
Eric Laurent81784c32012-11-19 14:55:58 -08005515
5516 // It's theoretically possible (though unlikely) for a fast track to be created
5517 // and then removed within the same normal mix cycle. This is not a problem, as
5518 // the track never becomes active so it's fast mixer slot is never touched.
5519 // The converse, of removing an (active) track and then creating a new track
5520 // at the identical fast mixer slot within the same normal mix cycle,
5521 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung3ff4b552023-06-26 19:20:57 -07005522 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005523 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005524 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5525 FastTrack *fastTrack = &state->mFastTracks[j];
5526
5527 // Determine whether the track is currently in underrun condition,
5528 // and whether it had a recent underrun.
5529 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5530 FastTrackUnderruns underruns = ftDump->mUnderruns;
5531 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung3ff4b552023-06-26 19:20:57 -07005532 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005533 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung3ff4b552023-06-26 19:20:57 -07005534 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005535 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung3ff4b552023-06-26 19:20:57 -07005536 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005537 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung3ff4b552023-06-26 19:20:57 -07005538 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005539 // don't count underruns that occur while stopping or pausing
5540 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005541 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005542 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5543 recentUnderruns > 0) {
5544 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005545 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005546 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005547 // Immediately account for FastTrack underruns.
Andy Hung3ff4b552023-06-26 19:20:57 -07005548 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005549
5550 // This is similar to the state machine for normal tracks,
5551 // with a few modifications for fast tracks.
5552 bool isActive = true;
Andy Hung3ff4b552023-06-26 19:20:57 -07005553 switch (track->state()) {
5554 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005555 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005556 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005557 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005558 }
5559 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005560 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005561 // ramp down is not yet implemented
5562 track->setPaused();
5563 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005564 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005565 // ramp up is not yet implemented
Andy Hung3ff4b552023-06-26 19:20:57 -07005566 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005567 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005568 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005569 if (recentFull > 0 || recentPartial > 0) {
5570 // track has provided at least some frames recently: reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005571 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005572 }
5573 if (recentUnderruns == 0) {
5574 // no recent underruns: stay active
5575 break;
5576 }
5577 // there has recently been an underrun of some kind
5578 if (track->sharedBuffer() == 0) {
5579 // were any of the recent underruns "empty" (no frames available)?
5580 if (recentEmpty == 0) {
5581 // no, then ignore the partial underruns as they are allowed indefinitely
5582 break;
5583 }
5584 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung3ff4b552023-06-26 19:20:57 -07005585 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005586 break;
5587 }
5588 // indicate to client process that the track was disabled because of underrun;
5589 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005590 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005591 // remove from active list, but state remains ACTIVE [confusing but true]
5592 isActive = false;
5593 break;
5594 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005595 FALLTHROUGH_INTENDED;
Andy Hung3ff4b552023-06-26 19:20:57 -07005596 case IAfTrackBase::STOPPING_2:
5597 case IAfTrackBase::PAUSED:
5598 case IAfTrackBase::STOPPED:
5599 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005600 // Check for presentation complete if track is inactive
5601 // We have consumed all the buffers of this track.
5602 // This would be incomplete if we auto-paused on underrun
5603 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005604 uint32_t latency = 0;
5605 status_t result = mOutput->stream->getLatency(&latency);
5606 ALOGE_IF(result != OK,
5607 "Error when retrieving output stream latency: %d", result);
5608 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005609 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005610 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5611 // track stays in active list until presentation is complete
5612 break;
5613 }
5614 }
5615 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005616 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005617 }
5618 if (track->isStopped()) {
5619 // Can't reset directly, as fast mixer is still polling this track
5620 // track->reset();
5621 // So instead mark this track as needing to be reset after push with ack
5622 resetMask |= 1 << i;
5623 }
5624 isActive = false;
5625 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005626 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005627 default:
Andy Hung3ff4b552023-06-26 19:20:57 -07005628 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005629 }
5630
5631 if (isActive) {
5632 // was it previously inactive?
5633 if (!(state->mTrackMask & (1 << j))) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005634 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5635 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005636 fastTrack->mBufferProvider = eabp;
5637 fastTrack->mVolumeProvider = vp;
Andy Hung3ff4b552023-06-26 19:20:57 -07005638 fastTrack->mChannelMask = track->channelMask();
5639 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005640 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005641 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005642 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005643 fastTrack->mGeneration++;
5644 state->mTrackMask |= 1 << j;
5645 didModify = true;
5646 // no acknowledgement required for newly active tracks
5647 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005648 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005649 float volume;
5650 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5651 volume = 0.f;
5652 } else {
5653 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5654 }
5655
5656 handleVoipVolume_l(&volume);
5657
Eric Laurent81784c32012-11-19 14:55:58 -08005658 // cache the combined master volume and stream type volume for fast mixer; this
5659 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005660 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005661 proxy->framesReleased()).first;
5662 volume *= vh;
Andy Hung3ff4b552023-06-26 19:20:57 -07005663 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005664 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005665 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5666 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005667
Andy Hung2cbc2722023-07-17 17:05:00 -07005668 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005669 /*muteState=*/{masterVolume == 0.f,
5670 mStreamTypes[track->streamType()].volume == 0.f,
5671 mStreamTypes[track->streamType()].mute,
5672 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005673 vlf == 0.f && vrf == 0.f,
5674 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005675
5676 vlf *= volume;
5677 vrf *= volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005678
jiabin76d94692022-12-15 21:51:21 +00005679 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005680 ++fastTracks;
5681 } else {
5682 // was it previously active?
5683 if (state->mTrackMask & (1 << j)) {
5684 fastTrack->mBufferProvider = NULL;
5685 fastTrack->mGeneration++;
5686 state->mTrackMask &= ~(1 << j);
5687 didModify = true;
5688 // If any fast tracks were removed, we must wait for acknowledgement
5689 // because we're about to decrement the last sp<> on those tracks.
5690 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5691 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005692 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5693 // AudioTrack may start (which may not be with a start() but with a write()
5694 // after underrun) and immediately paused or released. In that case the
5695 // FastTrack state hasn't had time to update.
5696 // TODO Remove the ALOGW when this theory is confirmed.
5697 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005698 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung3ff4b552023-06-26 19:20:57 -07005699 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005700 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005701 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005702 }
5703 tracksToRemove->add(track);
5704 // Avoids a misleading display in dumpsys
Andy Hung3ff4b552023-06-26 19:20:57 -07005705 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005706 }
jiabin245cdd92018-12-07 17:55:15 -08005707 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5708 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5709 didModify = true;
5710 }
Eric Laurent81784c32012-11-19 14:55:58 -08005711 continue;
5712 }
5713
5714 { // local variable scope to avoid goto warning
5715
5716 audio_track_cblk_t* cblk = track->cblk();
5717
5718 // The first time a track is added we wait
5719 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005720 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005721
5722 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005723 // use the trackId as the AudioMixer name.
5724 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005725 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005726 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005727 track->channelMask(),
5728 track->format(),
5729 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005730 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005731 ALOGW("%s(): AudioMixer cannot create track(%d)"
5732 " mask %#x, format %#x, sessionId %d",
5733 __func__, trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005734 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005735 tracksToRemove->add(track);
5736 track->invalidate(); // consider it dead.
5737 continue;
5738 }
5739 }
5740
Eric Laurent81784c32012-11-19 14:55:58 -08005741 // make sure that we have enough frames to mix one full buffer.
5742 // enforce this condition only once to enable draining the buffer in case the client
5743 // app does not call stop() and relies on underrun to stop:
5744 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5745 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005746 size_t desiredFrames;
Andy Hung3ff4b552023-06-26 19:20:57 -07005747 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5748 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005749
5750 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005751 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005752 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5753 // add frames already consumed but not yet released by the resampler
5754 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005755 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005756
Eric Laurent81784c32012-11-19 14:55:58 -08005757 uint32_t minFrames = 1;
5758 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5759 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005760 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005761 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005762
5763 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005764 if (ATRACE_ENABLED()) {
5765 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005766 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005767 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005768 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005769 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005770 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005771 !track->isPaused() && !track->isTerminated())
5772 {
Andy Hungc0691382018-09-12 18:01:57 -07005773 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005774
5775 mixedTracks++;
5776
Andy Hung69aed5f2014-02-25 17:24:40 -08005777 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5778 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005779 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005780 if (track->mainBuffer() != mSinkBuffer &&
5781 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005782 if (mEffectBufferEnabled) {
5783 mEffectBufferValid = true; // Later can set directly.
5784 }
Eric Laurent81784c32012-11-19 14:55:58 -08005785 chain = getEffectChain_l(track->sessionId());
5786 // Delegate volume control to effect in track effect chain if needed
5787 if (chain != 0) {
5788 tracksWithEffect++;
5789 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005790 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005791 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005792 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005793 }
5794 }
5795
5796
5797 int param = AudioMixer::VOLUME;
Andy Hung3ff4b552023-06-26 19:20:57 -07005798 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005799 // no ramp for the first volume setting
Andy Hung3ff4b552023-06-26 19:20:57 -07005800 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5801 if (track->state() == IAfTrackBase::RESUMING) {
5802 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005803 // If a new track is paused immediately after start, do not ramp on resume.
5804 if (cblk->mServer != 0) {
5805 param = AudioMixer::RAMP_VOLUME;
5806 }
Eric Laurent81784c32012-11-19 14:55:58 -08005807 }
Andy Hungc0691382018-09-12 18:01:57 -07005808 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005809 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005810 // FIXME should not make a decision based on mServer
5811 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005812 // If the track is stopped before the first frame was mixed,
5813 // do not apply ramp
5814 param = AudioMixer::RAMP_VOLUME;
5815 }
5816
5817 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005818 uint32_t vl, vr; // in U8.24 integer format
5819 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005820 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005821 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005822 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung3ff4b552023-06-26 19:20:57 -07005823 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005824 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung3ff4b552023-06-26 19:20:57 -07005825 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005826
Eric Laurenteab90452019-06-24 15:17:46 -07005827 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5828 v = 0;
5829 }
5830
5831 handleVoipVolume_l(&v);
5832
5833 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005834 vl = vr = 0;
5835 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005836 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005837 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005838 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005839 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5840 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005841 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005842 if (vlf > GAIN_FLOAT_UNITY) {
5843 ALOGV("Track left volume out of range: %.3g", vlf);
5844 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005845 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005846 if (vrf > GAIN_FLOAT_UNITY) {
5847 ALOGV("Track right volume out of range: %.3g", vrf);
5848 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005849 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005850
Andy Hung2cbc2722023-07-17 17:05:00 -07005851 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005852 /*muteState=*/{masterVolume == 0.f,
5853 mStreamTypes[track->streamType()].volume == 0.f,
5854 mStreamTypes[track->streamType()].mute,
5855 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005856 vlf == 0.f && vrf == 0.f,
5857 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005858
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005859 // now apply the master volume and stream type volume and shaper volume
5860 vlf *= v * vh;
5861 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005862 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005863 // then derive vl and vr as U8.24 versions for the effect chain
5864 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5865 vl = (uint32_t) (scaleto8_24 * vlf);
5866 vr = (uint32_t) (scaleto8_24 * vrf);
5867 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005868 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005869 // send level comes from shared memory and so may be corrupt
5870 if (sendLevel > MAX_GAIN_INT) {
5871 ALOGV("Track send level out of range: %04X", sendLevel);
5872 sendLevel = MAX_GAIN_INT;
5873 }
Andy Hung6be49402014-05-30 10:42:03 -07005874 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5875 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005876 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005877
jiabin76d94692022-12-15 21:51:21 +00005878 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005879
Eric Laurent81784c32012-11-19 14:55:58 -08005880 // Delegate volume control to effect in track effect chain if needed
5881 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5882 // Do not ramp volume if volume is controlled by effect
5883 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005884 // Update remaining floating point volume levels
5885 vlf = (float)vl / (1 << 24);
5886 vrf = (float)vr / (1 << 24);
Andy Hung3ff4b552023-06-26 19:20:57 -07005887 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005888 } else {
5889 // force no volume ramp when volume controller was just disabled or removed
5890 // from effect chain to avoid volume spike
Andy Hung3ff4b552023-06-26 19:20:57 -07005891 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005892 param = AudioMixer::VOLUME;
5893 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005894 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005895 }
5896
Eric Laurent81784c32012-11-19 14:55:58 -08005897 // XXX: these things DON'T need to be done each time
Andy Hung3ff4b552023-06-26 19:20:57 -07005898 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005899 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005900
Andy Hungc0691382018-09-12 18:01:57 -07005901 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5902 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5903 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005904 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005905 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005906 AudioMixer::TRACK,
5907 AudioMixer::FORMAT, (void *)track->format());
5908 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005909 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005910 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005911 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005912
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005913 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005914 mAudioMixer->setParameter(
5915 trackId,
5916 AudioMixer::TRACK,
5917 AudioMixer::MIXER_CHANNEL_MASK,
5918 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5919 } else {
5920 mAudioMixer->setParameter(
5921 trackId,
5922 AudioMixer::TRACK,
5923 AudioMixer::MIXER_CHANNEL_MASK,
5924 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5925 }
5926
Glenn Kastene3aa6592012-12-04 12:22:46 -08005927 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005928 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005929 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005930 if (reqSampleRate == 0) {
5931 reqSampleRate = mSampleRate;
5932 } else if (reqSampleRate > maxSampleRate) {
5933 reqSampleRate = maxSampleRate;
5934 }
Eric Laurent81784c32012-11-19 14:55:58 -08005935 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005936 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005937 AudioMixer::RESAMPLE,
5938 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005939 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005940
Andy Hung8edb8dc2015-03-26 19:13:55 -07005941 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005942 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005943 AudioMixer::TIMESTRETCH,
5944 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005945 // cast away constness for this generic API.
5946 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005947
Andy Hung69aed5f2014-02-25 17:24:40 -08005948 /*
5949 * Select the appropriate output buffer for the track.
5950 *
Andy Hung98ef9782014-03-04 14:46:50 -08005951 * Tracks with effects go into their own effects chain buffer
5952 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005953 *
5954 * Other tracks can use mMixerBuffer for higher precision
5955 * channel accumulation. If this buffer is enabled
5956 * (mMixerBufferEnabled true), then selected tracks will accumulate
5957 * into it.
5958 *
5959 */
5960 if (mMixerBufferEnabled
5961 && (track->mainBuffer() == mSinkBuffer
5962 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005963 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005964 mAudioMixer->setParameter(
5965 trackId,
5966 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005967 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005968 mAudioMixer->setParameter(
5969 trackId,
5970 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005971 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005972 } else {
5973 mAudioMixer->setParameter(
5974 trackId,
5975 AudioMixer::TRACK,
5976 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5977 mAudioMixer->setParameter(
5978 trackId,
5979 AudioMixer::TRACK,
5980 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5981 // TODO: override track->mainBuffer()?
5982 mMixerBufferValid = true;
5983 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005984 } else {
5985 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005986 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005987 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005988 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005989 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005990 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005991 AudioMixer::TRACK,
5992 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5993 }
Eric Laurent81784c32012-11-19 14:55:58 -08005994 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005995 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005996 AudioMixer::TRACK,
5997 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005998 mAudioMixer->setParameter(
5999 trackId,
6000 AudioMixer::TRACK,
6001 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006002 mAudioMixer->setParameter(
6003 trackId,
6004 AudioMixer::TRACK,
6005 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung3ff4b552023-06-26 19:20:57 -07006006 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006007 mAudioMixer->setParameter(
6008 trackId,
6009 AudioMixer::TRACK,
Andy Hung3ff4b552023-06-26 19:20:57 -07006010 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006011
6012 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006013 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006014
6015 // If one track is ready, set the mixer ready if:
6016 // - the mixer was not ready during previous round OR
6017 // - no other track is not ready
6018 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6019 mixerStatus != MIXER_TRACKS_ENABLED) {
6020 mixerStatus = MIXER_TRACKS_READY;
6021 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006022
6023 // Enable the next few lines to instrument a test for underrun log handling.
6024 // TODO: Remove when we have a better way of testing the underrun log.
6025#if 0
6026 static int i;
6027 if ((++i & 0xf) == 0) {
6028 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6029 }
6030#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006031 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006032 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006033 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006034 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6035 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006036 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006037 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006038 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006039
Eric Laurent81784c32012-11-19 14:55:58 -08006040 // clear effect chain input buffer if an active track underruns to avoid sending
6041 // previous audio buffer again to effects
6042 chain = getEffectChain_l(track->sessionId());
6043 if (chain != 0) {
6044 chain->clearInputBuffer();
6045 }
6046
Andy Hungc0691382018-09-12 18:01:57 -07006047 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006048 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6049 track->isStopped() || track->isPaused()) {
6050 // We have consumed all the buffers of this track.
6051 // Remove it from the list of active tracks.
6052 // TODO: use actual buffer filling status instead of latency when available from
6053 // audio HAL
6054 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006055 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006056 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6057 if (track->isStopped()) {
6058 track->reset();
6059 }
6060 tracksToRemove->add(track);
6061 }
6062 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006063 // No buffers for this track. Give it a few chances to
6064 // fill a buffer, then remove it from active list.
Andy Hung3ff4b552023-06-26 19:20:57 -07006065 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006066 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6067 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006068 tracksToRemove->add(track);
6069 // indicate to client process that the track was disabled because of underrun;
6070 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006071 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006072 // If one track is not ready, mark the mixer also not ready if:
6073 // - the mixer was ready during previous round OR
6074 // - no other track is ready
6075 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6076 mixerStatus != MIXER_TRACKS_READY) {
6077 mixerStatus = MIXER_TRACKS_ENABLED;
6078 }
6079 }
Andy Hungc0691382018-09-12 18:01:57 -07006080 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006081 }
6082
6083 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006084
6085 }
6086
jiabin245cdd92018-12-07 17:55:15 -08006087 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6088 // When there is no fast track playing haptic and FastMixer exists,
6089 // enabling the first FastTrack, which provides mixed data from normal
6090 // tracks, to play haptic data.
6091 FastTrack *fastTrack = &state->mFastTracks[0];
6092 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6093 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6094 didModify = true;
6095 }
6096 }
6097
Eric Laurent81784c32012-11-19 14:55:58 -08006098 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006099 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006100 if (didModify) {
6101 state->mFastTracksGen++;
6102 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6103 if (kUseFastMixer == FastMixer_Dynamic &&
6104 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6105 state->mCommand = FastMixerState::COLD_IDLE;
6106 state->mColdFutexAddr = &mFastMixerFutex;
6107 state->mColdGen++;
6108 mFastMixerFutex = 0;
6109 if (kUseFastMixer == FastMixer_Dynamic) {
6110 mNormalSink = mOutputSink;
6111 }
6112 // If we go into cold idle, need to wait for acknowledgement
6113 // so that fast mixer stops doing I/O.
6114 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6115 pauseAudioWatchdog = true;
6116 }
Eric Laurent81784c32012-11-19 14:55:58 -08006117 }
6118 if (sq != NULL) {
6119 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006120 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6121 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6122 // when bringing the output sink into standby.)
6123 //
6124 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6125 //
6126 // This occurs with BT suspend when we idle the FastMixer with
6127 // active tracks, which may be added or removed.
6128 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006129 }
6130#ifdef AUDIO_WATCHDOG
6131 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6132 mAudioWatchdog->pause();
6133 }
6134#endif
6135
6136 // Now perform the deferred reset on fast tracks that have stopped
6137 while (resetMask != 0) {
6138 size_t i = __builtin_ctz(resetMask);
6139 ALOG_ASSERT(i < count);
6140 resetMask &= ~(1 << i);
Andy Hung3ff4b552023-06-26 19:20:57 -07006141 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006142 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6143 track->reset();
6144 }
6145
Andy Hung80d03d22018-04-10 10:32:11 -07006146 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6147 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6148 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6149 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6150 // See also the implementation of destroyTrack_l().
6151 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006152 const int trackId = track->id();
6153 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6154 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006155 }
6156 }
6157
Eric Laurent81784c32012-11-19 14:55:58 -08006158 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006159 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006160
Eric Laurentb3f315a2021-07-13 15:09:05 +02006161 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6162 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006163 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006164 }
6165
6166 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006167 // as long as there are effects we should clear the effects buffer, to avoid
6168 // passing a non-clean buffer to the effect chain
6169 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006170 if (mType == SPATIALIZER) {
6171 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6172 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006173 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006174 // sink or mix buffer must be cleared if all tracks are connected to an
6175 // effect chain as in this case the mixer will not write to the sink or mix buffer
6176 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006177 // always clear sink buffer for spatializer output as the output of the spatializer
6178 // effect will be accumulated into it
6179 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6180 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006181 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006182 if (mMixerBufferValid) {
6183 memset(mMixerBuffer, 0, mMixerBufferSize);
6184 // TODO: In testing, mSinkBuffer below need not be cleared because
6185 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6186 // after mixing.
6187 //
6188 // To enforce this guarantee:
6189 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6190 // (mixedTracks == 0 && fastTracks > 0))
6191 // must imply MIXER_TRACKS_READY.
6192 // Later, we may clear buffers regardless, and skip much of this logic.
6193 }
Andy Hung98ef9782014-03-04 14:46:50 -08006194 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006195 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006196 }
6197
6198 // if any fast tracks, then status is ready
6199 mMixerStatusIgnoringFastTracks = mixerStatus;
6200 if (fastTracks > 0) {
6201 mixerStatus = MIXER_TRACKS_READY;
6202 }
6203 return mixerStatus;
6204}
6205
Eric Laurentad7dd962016-09-22 12:38:37 -07006206// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006207uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006208{
6209 uint32_t trackCount = 0;
6210 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006211 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006212 trackCount++;
6213 }
6214 }
6215 return trackCount;
6216}
6217
Andy Hung71742ab2023-07-07 13:47:37 -07006218bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006219{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006220 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6221 // could falsely detect that the frame position has stalled due to underrun because we haven't
6222 // given the Audio HAL enough time to update.
6223 const nsecs_t nowNs = systemTime();
6224 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6225 return mLatchedValue;
6226 }
6227 mPreviousNs = nowNs;
6228 mLatchedValue = false;
6229 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006230 uint64_t position = 0;
6231 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006232 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006233 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006234 if (position != mPreviousPosition) {
6235 mPreviousPosition = position;
6236 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006237 }
6238 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006239 return mLatchedValue;
6240}
6241
Andy Hung71742ab2023-07-07 13:47:37 -07006242void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006243{
6244 mLatchedValue = true;
6245 mPreviousPosition = 0;
6246 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006247}
6248
Andy Hung1bc088a2018-02-09 15:57:31 -08006249// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006250bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006251 audio_channel_mask_t channelMask, audio_format_t format,
6252 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006253{
Andy Hung1bc088a2018-02-09 15:57:31 -08006254 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6255 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006256 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006257 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006258 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006259 ALOGW("%s: invalid format: %#x", __func__, format);
6260 return false;
6261 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006262 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006263 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6264 return false;
6265 }
6266 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006267}
6268
Eric Laurent10351942014-05-08 18:49:52 -07006269// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006270bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006271 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006272{
Eric Laurent81784c32012-11-19 14:55:58 -08006273 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006274 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006275
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006276 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006277
Eric Laurent10351942014-05-08 18:49:52 -07006278 AudioParameter param = AudioParameter(keyValuePair);
6279 int value;
6280 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6281 reconfig = true;
6282 }
6283 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungf8ab4692023-07-20 21:44:14 -07006284 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006285 status = BAD_VALUE;
6286 } else {
6287 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006288 reconfig = true;
6289 }
Eric Laurent10351942014-05-08 18:49:52 -07006290 }
6291 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungf8ab4692023-07-20 21:44:14 -07006292 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006293 status = BAD_VALUE;
6294 } else {
6295 // no need to save value, since it's constant
6296 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006297 }
Eric Laurent10351942014-05-08 18:49:52 -07006298 }
6299 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6300 // do not accept frame count changes if tracks are open as the track buffer
6301 // size depends on frame count and correct behavior would not be guaranteed
6302 // if frame count is changed after track creation
6303 if (!mTracks.isEmpty()) {
6304 status = INVALID_OPERATION;
6305 } else {
6306 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006307 }
Eric Laurent10351942014-05-08 18:49:52 -07006308 }
6309 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006310 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006311 }
Eric Laurent81784c32012-11-19 14:55:58 -08006312
Eric Laurent10351942014-05-08 18:49:52 -07006313 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006314 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006315 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006316 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6317 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006318 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006319 mThreadMetrics.logEndInterval();
6320 mThreadSnapshot.onEnd();
Andy Hungdda7aed2023-03-27 15:53:06 -07006321 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006322 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006323 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006324 }
Eric Laurent10351942014-05-08 18:49:52 -07006325 if (status == NO_ERROR && reconfig) {
6326 readOutputParameters_l();
6327 delete mAudioMixer;
6328 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006329 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006330 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006331 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006332 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07006333 track->channelMask(),
6334 track->format(),
6335 track->sessionId());
Andy Hung71ba4b32022-10-06 12:09:49 -07006336 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006337 "%s(): AudioMixer cannot create track(%d)"
6338 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006339 __func__,
Andy Hung3ff4b552023-06-26 19:20:57 -07006340 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006341 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006342 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006343 }
Eric Laurent81784c32012-11-19 14:55:58 -08006344 }
6345
Dean Wheatley68918102021-03-19 22:09:19 +11006346 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006347}
6348
6349
Andy Hung71742ab2023-07-07 13:47:37 -07006350void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006351{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006352 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006353 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006354 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006355 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006356 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6357 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6358 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006359 if (hasFastMixer()) {
6360 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6361
6362 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6363 // while we are dumping it. It may be inconsistent, but it won't mutate!
6364 // This is a large object so we place it on the heap.
6365 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006366 const std::unique_ptr<FastMixerDumpState> copy =
6367 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006368 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006369
6370#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006371 // Similar for state queue
6372 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6373 observerCopy.dump(fd);
6374 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6375 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006376#endif
6377
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006378#ifdef AUDIO_WATCHDOG
6379 if (mAudioWatchdog != 0) {
6380 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6381 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6382 wdCopy.dump(fd);
6383 }
6384#endif
6385
6386 } else {
6387 dprintf(fd, " No FastMixer\n");
6388 }
Eric Laurent90cea102023-05-15 15:08:27 +02006389
6390 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6391 mBluetoothLatencyModesEnabled ? "" : "not ");
6392 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6393 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6394 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006395}
6396
Andy Hung71742ab2023-07-07 13:47:37 -07006397uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006398{
6399 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6400}
6401
Andy Hung71742ab2023-07-07 13:47:37 -07006402uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006403{
6404 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6405}
6406
Andy Hung71742ab2023-07-07 13:47:37 -07006407void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006408{
6409 PlaybackThread::cacheParameters_l();
6410
6411 // FIXME: Relaxed timing because of a certain device that can't meet latency
6412 // Should be reduced to 2x after the vendor fixes the driver issue
6413 // increase threshold again due to low power audio mode. The way this warning
6414 // threshold is calculated and its usefulness should be reconsidered anyway.
6415 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6416}
6417
Andy Hung71742ab2023-07-07 13:47:37 -07006418void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung2cbc2722023-07-17 17:05:00 -07006419 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006420}
6421
Andy Hung71742ab2023-07-07 13:47:37 -07006422void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006423 // Only handle latency mode if:
6424 // - mBluetoothLatencyModesEnabled is true
6425 // - the HAL supports latency modes
6426 // - the selected device is Bluetooth LE or A2DP
6427 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6428 return;
6429 }
6430 if (mOutDeviceTypeAddrs.size() != 1
6431 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6432 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6433 return;
6434 }
6435
6436 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6437 if (mSupportedLatencyModes.size() == 1) {
6438 // If the HAL only support one latency mode currently, confirm the choice
6439 latencyMode = mSupportedLatencyModes[0];
6440 } else if (mSupportedLatencyModes.size() > 1) {
6441 // Request low latency if:
6442 // - At least one active track is either:
6443 // - a fast track with gaming usage or
6444 // - a track with acessibility usage
6445 for (const auto& track : mActiveTracks) {
6446 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6447 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6448 latencyMode = AUDIO_LATENCY_MODE_LOW;
6449 break;
6450 }
6451 }
6452 }
6453
6454 if (latencyMode != mSetLatencyMode) {
6455 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6456 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6457 __func__, mId, toString(latencyMode).c_str(), status);
6458 if (status == NO_ERROR) {
6459 mSetLatencyMode = latencyMode;
6460 }
6461 }
6462}
6463
Andy Hung71742ab2023-07-07 13:47:37 -07006464void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006465
6466 if (mOutput == nullptr || mOutput->stream == nullptr) {
6467 return;
6468 }
6469 std::vector<audio_latency_mode_t> latencyModes;
6470 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6471 if (status != NO_ERROR) {
6472 latencyModes.clear();
6473 }
6474 if (latencyModes != mSupportedLatencyModes) {
6475 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6476 __func__, mId, status, toString(latencyModes).c_str());
6477 mSupportedLatencyModes.swap(latencyModes);
6478 sendHalLatencyModesChangedEvent_l();
6479 }
6480}
6481
Andy Hung71742ab2023-07-07 13:47:37 -07006482status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006483 std::vector<audio_latency_mode_t>* modes) {
6484 if (modes == nullptr) {
6485 return BAD_VALUE;
6486 }
6487 Mutex::Autolock _l(mLock);
6488 *modes = mSupportedLatencyModes;
6489 return NO_ERROR;
6490}
6491
Andy Hung71742ab2023-07-07 13:47:37 -07006492void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006493 std::vector<audio_latency_mode_t> modes) {
6494 Mutex::Autolock _l(mLock);
6495 if (modes != mSupportedLatencyModes) {
6496 ALOGD("%s: thread(%d) supported latency modes: %s",
6497 __func__, mId, toString(modes).c_str());
6498 mSupportedLatencyModes.swap(modes);
6499 sendHalLatencyModesChangedEvent_l();
6500 }
6501}
6502
Andy Hung71742ab2023-07-07 13:47:37 -07006503status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006504 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6505 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6506 return INVALID_OPERATION;
6507 }
6508 mBluetoothLatencyModesEnabled.store(enabled);
6509 return NO_ERROR;
6510}
6511
Eric Laurent81784c32012-11-19 14:55:58 -08006512// ----------------------------------------------------------------------------
6513
Andy Hung71742ab2023-07-07 13:47:37 -07006514/* static */
6515sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07006516 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07006517 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6518 const audio_offload_info_t& offloadInfo) {
6519 return sp<DirectOutputThread>::make(
Andy Hung2cbc2722023-07-17 17:05:00 -07006520 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07006521}
6522
Andy Hung2cbc2722023-07-17 17:05:00 -07006523DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07006524 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6525 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07006526 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006527 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006528{
Andy Hung2cbc2722023-07-17 17:05:00 -07006529 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006530}
6531
Andy Hung71742ab2023-07-07 13:47:37 -07006532DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006533{
6534}
6535
Andy Hung71742ab2023-07-07 13:47:37 -07006536void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006537{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006538 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006539 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6540 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6541}
6542
Andy Hung71742ab2023-07-07 13:47:37 -07006543void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006544{
6545 Mutex::Autolock _l(mLock);
6546 if (mMasterBalance != balance) {
6547 mMasterBalance.store(balance);
6548 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6549 broadcast_l();
6550 }
6551}
6552
Andy Hung71742ab2023-07-07 13:47:37 -07006553void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006554{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006555 float left, right;
6556
Andy Hung333ab962019-05-28 20:23:35 -07006557 // Ensure volumeshaper state always advances even when muted.
Andy Hung3ff4b552023-06-26 19:20:57 -07006558 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hungee86cee2022-12-13 19:19:53 -08006559
Andy Hungee86cee2022-12-13 19:19:53 -08006560 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6561 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6562
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006563 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6564 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hungee86cee2022-12-13 19:19:53 -08006565
6566 const int64_t volumeShaperFrames =
6567 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6568 const auto [shaperVolume, shaperActive] =
6569 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006570 mVolumeShaperActive = shaperActive;
6571
Vlad Popae2f5aef2022-07-25 16:00:20 +02006572 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6573 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6574 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6575
6576 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6577
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006578 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006579 left = right = 0;
6580 } else {
6581 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006582 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006583
Glenn Kastenc56f3422014-03-21 17:53:17 -07006584 if (left > GAIN_FLOAT_UNITY) {
6585 left = GAIN_FLOAT_UNITY;
6586 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006587 if (right > GAIN_FLOAT_UNITY) {
6588 right = GAIN_FLOAT_UNITY;
6589 }
zhangjincheng73e73872023-01-16 17:17:38 +08006590 left *= v;
6591 right *= v;
Andy Hung2cbc2722023-07-17 17:05:00 -07006592 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng73e73872023-01-16 17:17:38 +08006593 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6594 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6595 right *= mMasterBalanceRight;
6596 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006597 }
6598
Andy Hung2cbc2722023-07-17 17:05:00 -07006599 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006600 /*muteState=*/{mMasterMute,
6601 mStreamTypes[track->streamType()].volume == 0.f,
6602 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006603 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006604 clientVolumeMute,
6605 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006606
Eric Laurentbfb1b832013-01-07 09:53:42 -08006607 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006608 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006609 if (left != mLeftVolFloat || right != mRightVolFloat) {
6610 mLeftVolFloat = left;
6611 mRightVolFloat = right;
6612
Eric Laurentbfb1b832013-01-07 09:53:42 -08006613 // Delegate volume control to effect in track effect chain if needed
6614 // only one effect chain can be present on DirectOutputThread, so if
6615 // there is one, the track is connected to it
6616 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006617 // if effect chain exists, volume is handled by it.
6618 // Convert volumes from float to 8.24
6619 uint32_t vl = (uint32_t)(left * (1 << 24));
6620 uint32_t vr = (uint32_t)(right * (1 << 24));
6621 // Direct/Offload effect chains set output volume in setVolume_l().
6622 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6623 } else {
6624 // otherwise we directly set the volume.
6625 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006626 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006627 }
6628 }
6629}
6630
Andy Hung71742ab2023-07-07 13:47:37 -07006631void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006632{
Andy Hung3ff4b552023-06-26 19:20:57 -07006633 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6634 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006635
Eric Laurent0f0631e2015-07-06 18:01:25 -07006636 if (previousTrack != 0 && latestTrack != 0) {
6637 if (mType == DIRECT) {
6638 if (previousTrack.get() != latestTrack.get()) {
6639 mFlushPending = true;
6640 }
6641 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006642 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6643 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006644 mFlushPending = true;
6645 }
6646 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006647 } else if (previousTrack == 0) {
6648 // there could be an old track added back during track transition for direct
6649 // output, so always issues flush to flush data of the previous track if it
6650 // was already destroyed with HAL paused, then flush can resume the playback
6651 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006652 }
6653 PlaybackThread::onAddNewTrack_l();
6654}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006655
Andy Hung71742ab2023-07-07 13:47:37 -07006656PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07006657 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006658)
6659{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006660 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006661 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006662 bool doHwPause = false;
6663 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006664
6665 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07006666 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006667 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006668 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006669 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006670 continue;
6671 }
6672
Andy Hung3ff4b552023-06-26 19:20:57 -07006673 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006674#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006675 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006676#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006677 // Only consider last track started for volume and mixer state control.
6678 // In theory an older track could underrun and restart after the new one starts
6679 // but as we only care about the transition phase between two tracks on a
6680 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07006681 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006682 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006683
Kuowei Li23666472021-01-20 10:23:25 +08006684 if (track->isPausePending()) {
6685 track->pauseAck();
6686 // It is possible a track might have been flushed or stopped.
6687 // Other operations such as flush pending might occur on the next prepare.
6688 if (track->isPausing()) {
6689 track->setPaused();
6690 }
6691 // Always perform pause, as an immediate flush will change
6692 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006693 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006694 doHwPause = true;
6695 mHwPaused = true;
6696 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006697 } else if (track->isFlushPending()) {
6698 track->flushAck();
6699 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006700 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006701 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006702 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006703 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006704 if (last) {
6705 mLeftVolFloat = mRightVolFloat = -1.0;
6706 if (mHwPaused) {
6707 doHwResume = true;
6708 mHwPaused = false;
6709 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006710 }
6711 }
6712
Eric Laurent81784c32012-11-19 14:55:58 -08006713 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006714 // for all its buffers to be filled before processing it.
6715 // Allow draining the buffer in case the client
6716 // app does not call stop() and relies on underrun to stop:
Andy Hung3ff4b552023-06-26 19:20:57 -07006717 // hence the test on (track->retryCount() > 1).
6718 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006719 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6720 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006721 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006722
6723 // target retry count that we will use is based on the time we wait for retries.
6724 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6725 // the retry threshold is when we accept any size for PCM data. This is slightly
6726 // smaller than the retry count so we can push small bits of data without a glitch.
6727 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006728 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006729 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung3ff4b552023-06-26 19:20:57 -07006730 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006731 minFrames = mNormalFrameCount;
6732 } else {
6733 minFrames = 1;
6734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006735
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006736 const size_t framesReady = track->framesReady();
6737 const int trackId = track->id();
6738 if (ATRACE_ENABLED()) {
6739 std::string traceName("nRdy");
6740 traceName += std::to_string(trackId);
6741 ATRACE_INT(traceName.c_str(), framesReady);
6742 }
6743 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006744 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006745 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006746 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006747
Andy Hung3ff4b552023-06-26 19:20:57 -07006748 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6749 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006750 if (last) {
6751 // make sure processVolume_l() will apply new volume even if 0
6752 mLeftVolFloat = mRightVolFloat = -1.0;
6753 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006754 if (!mHwSupportsPause) {
6755 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006756 }
6757 }
6758
6759 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006760 processVolume_l(track, last);
6761 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006762 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006763 if (previousTrack != 0) {
6764 if (track != previousTrack.get()) {
6765 // Flush any data still being written from last track
6766 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006767 // Invalidate previous track to force a seek when resuming.
6768 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006769 }
6770 }
6771 mPreviousTrack = track;
6772
Eric Laurentd595b7c2013-04-03 17:27:56 -07006773 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006774 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006775 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006776 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006777 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006778 doHwResume = true;
6779 mHwPaused = false;
6780 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006781 }
Eric Laurent81784c32012-11-19 14:55:58 -08006782 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006783 // clear effect chain input buffer if the last active track started underruns
6784 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006785 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006786 mEffectChains[0]->clearInputBuffer();
6787 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006788 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006789 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006790 if (last && mHwPaused) {
6791 doHwResume = true;
6792 mHwPaused = false;
6793 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006794 }
6795 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6796 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006797 // We have consumed all the buffers of this track.
6798 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006799 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006800 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006801 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006802 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006803 if (presComplete) {
6804 mOutput->presentationComplete();
6805 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006806 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006807 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006808 }
Eric Laurent81784c32012-11-19 14:55:58 -08006809 if (track->isStopped()) {
6810 track->reset();
6811 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006812 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006813 }
6814 } else {
6815 // No buffers for this track. Give it a few chances to
6816 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006817 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006818 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006819 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07006820 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006821 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07006822 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006823 } else {
6824 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6825 tracksToRemove->add(track);
6826 // indicate to client process that the track was disabled because of
6827 // underrun; it will then automatically call start() when data is available
6828 track->disable();
6829 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6830 // unlike mixerthread, HAL can be paused for direct output
6831 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6832 "minFrames = %u, mFormat = %#x",
6833 framesReady, minFrames, mFormat);
6834 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6835 doHwPause = true;
6836 mHwPaused = true;
6837 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006838 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006839 } else if (last) {
6840 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006841 }
6842 }
6843 }
6844 }
6845
Eric Laurentd1f69b02014-12-15 14:33:13 -08006846 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006847 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006848 for (size_t i = 0; i < mTracks.size(); i++) {
6849 if (mTracks[i]->isFlushPending()) {
6850 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006851 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006852 }
6853 }
6854 }
6855
6856 // make sure the pause/flush/resume sequence is executed in the right order.
6857 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6858 // before flush and then resume HW. This can happen in case of pause/flush/resume
6859 // if resume is received before pause is executed.
6860 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006861 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006862 status_t result = mOutput->stream->pause();
6863 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006864 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006865 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006866 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006867 flushHw_l();
6868 }
6869 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006870 status_t result = mOutput->stream->resume();
6871 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006872 }
Eric Laurent81784c32012-11-19 14:55:58 -08006873 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006874 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006875
6876 return mixerStatus;
6877}
6878
Andy Hung71742ab2023-07-07 13:47:37 -07006879void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006880{
Eric Laurent81784c32012-11-19 14:55:58 -08006881 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006882 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006883 // output audio to hardware
6884 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006885 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006886 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006887 status_t status = mActiveTrack->getNextBuffer(&buffer);
6888 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006889 // no need to pad with 0 for compressed audio
6890 if (audio_has_proportional_frames(mFormat)) {
6891 memset(curBuf, 0, frameCount * mFrameSize);
6892 }
Eric Laurent81784c32012-11-19 14:55:58 -08006893 break;
6894 }
6895 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6896 frameCount -= buffer.frameCount;
6897 curBuf += buffer.frameCount * mFrameSize;
6898 mActiveTrack->releaseBuffer(&buffer);
6899 }
Andy Hung2098f272014-02-27 14:00:06 -08006900 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006901 mSleepTimeUs = 0;
6902 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006903 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006904}
6905
Andy Hung71742ab2023-07-07 13:47:37 -07006906void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006907{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006908 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006909 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006910 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006911 return;
6912 }
Andy Hung85ba3332021-04-27 17:40:26 -07006913 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6914 mSleepTimeUs = mActiveSleepTimeUs;
6915 } else {
6916 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006917 }
Andy Hung85ba3332021-04-27 17:40:26 -07006918 // Note: In S or later, we do not write zeroes for
6919 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006920}
6921
Andy Hung71742ab2023-07-07 13:47:37 -07006922void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006923{
6924 {
6925 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006926 for (size_t i = 0; i < mTracks.size(); i++) {
6927 if (mTracks[i]->isFlushPending()) {
6928 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006929 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006930 }
6931 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006932 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006933 flushHw_l();
6934 }
6935 }
6936 PlaybackThread::threadLoop_exit();
6937}
6938
6939// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07006940bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006941{
6942 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006943 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006944
6945 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6946 // after a timeout and we will enter standby then.
6947 if (mTracks.size() > 0) {
6948 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006949 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung3ff4b552023-06-26 19:20:57 -07006950 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006951 }
6952
Eric Laurent5cff4032015-05-26 13:49:58 -07006953 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006954}
6955
Eric Laurent10351942014-05-08 18:49:52 -07006956// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006957bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006958 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006959{
6960 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006961 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006962
Eric Laurent10351942014-05-08 18:49:52 -07006963 AudioParameter param = AudioParameter(keyValuePair);
6964 int value;
6965 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006966 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006967 }
Eric Laurent10351942014-05-08 18:49:52 -07006968 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6969 // do not accept frame count changes if tracks are open as the track buffer
6970 // size depends on frame count and correct behavior would not be garantied
6971 // if frame count is changed after track creation
6972 if (!mTracks.isEmpty()) {
6973 status = INVALID_OPERATION;
6974 } else {
6975 reconfig = true;
6976 }
6977 }
6978 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006979 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006980 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006981 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006982 if (!mStandby) {
6983 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006984 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006985 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006986 }
Eric Laurent10351942014-05-08 18:49:52 -07006987 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006988 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006989 }
6990 if (status == NO_ERROR && reconfig) {
6991 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006992 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006993 }
6994 }
6995
Dean Wheatley68918102021-03-19 22:09:19 +11006996 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006997}
6998
Andy Hung71742ab2023-07-07 13:47:37 -07006999uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007000{
7001 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007002 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007003 time = PlaybackThread::activeSleepTimeUs();
7004 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007005 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007006 }
7007 return time;
7008}
7009
Andy Hung71742ab2023-07-07 13:47:37 -07007010uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007011{
7012 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007013 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007014 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7015 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007016 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007017 }
7018 return time;
7019}
7020
Andy Hung71742ab2023-07-07 13:47:37 -07007021uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007022{
7023 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007024 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007025 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7026 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007027 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007028 }
7029 return time;
7030}
7031
Andy Hung71742ab2023-07-07 13:47:37 -07007032void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007033{
7034 PlaybackThread::cacheParameters_l();
7035
7036 // use shorter standby delay as on normal output to release
7037 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007038 // no delay on outputs with HW A/V sync
7039 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007040 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007041 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007042 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007043 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007044 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007045 }
Eric Laurent81784c32012-11-19 14:55:58 -08007046}
7047
Andy Hung71742ab2023-07-07 13:47:37 -07007048void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007049{
ziyangch8f194f12021-12-01 13:48:04 -08007050 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007051 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007052 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007053 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007054 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007055 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08007056 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007057}
7058
Andy Hung71742ab2023-07-07 13:47:37 -07007059int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007060 // If a VolumeShaper is active, we must wake up periodically to update volume.
7061 const int64_t NS_PER_MS = 1000000;
7062 return mVolumeShaperActive ?
7063 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7064}
7065
Eric Laurent81784c32012-11-19 14:55:58 -08007066// ----------------------------------------------------------------------------
7067
Andy Hung71742ab2023-07-07 13:47:37 -07007068AsyncCallbackThread::AsyncCallbackThread(
7069 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007070 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007071 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007072 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007073 mDrainSequence(0),
7074 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007075{
7076}
7077
Andy Hung71742ab2023-07-07 13:47:37 -07007078void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079{
7080 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7081}
7082
Andy Hung71742ab2023-07-07 13:47:37 -07007083bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007084{
7085 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007086 uint32_t writeAckSequence;
7087 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007088 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007089
7090 {
7091 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007092 while (!((mWriteAckSequence & 1) ||
7093 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007094 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007095 exitPending())) {
7096 mWaitWorkCV.wait(mLock);
7097 }
7098
Eric Laurentbfb1b832013-01-07 09:53:42 -08007099 if (exitPending()) {
7100 break;
7101 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007102 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7103 mWriteAckSequence, mDrainSequence);
7104 writeAckSequence = mWriteAckSequence;
7105 mWriteAckSequence &= ~1;
7106 drainSequence = mDrainSequence;
7107 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007108 asyncError = mAsyncError;
7109 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007110 }
7111 {
Andy Hung71742ab2023-07-07 13:47:37 -07007112 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007113 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007114 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007115 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007116 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007117 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007118 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007119 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007120 if (asyncError) {
7121 playbackThread->onAsyncError();
7122 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007123 }
7124 }
7125 }
7126 return false;
7127}
7128
Andy Hung71742ab2023-07-07 13:47:37 -07007129void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007130{
7131 ALOGV("AsyncCallbackThread::exit");
7132 Mutex::Autolock _l(mLock);
7133 requestExit();
7134 mWaitWorkCV.broadcast();
7135}
7136
Andy Hung71742ab2023-07-07 13:47:37 -07007137void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007138{
7139 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007140 // bit 0 is cleared
7141 mWriteAckSequence = sequence << 1;
7142}
7143
Andy Hung71742ab2023-07-07 13:47:37 -07007144void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007145{
7146 Mutex::Autolock _l(mLock);
7147 // ignore unexpected callbacks
7148 if (mWriteAckSequence & 2) {
7149 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007150 mWaitWorkCV.signal();
7151 }
7152}
7153
Andy Hung71742ab2023-07-07 13:47:37 -07007154void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007155{
7156 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007157 // bit 0 is cleared
7158 mDrainSequence = sequence << 1;
7159}
7160
Andy Hung71742ab2023-07-07 13:47:37 -07007161void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007162{
7163 Mutex::Autolock _l(mLock);
7164 // ignore unexpected callbacks
7165 if (mDrainSequence & 2) {
7166 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007167 mWaitWorkCV.signal();
7168 }
7169}
7170
Andy Hung71742ab2023-07-07 13:47:37 -07007171void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007172{
7173 Mutex::Autolock _l(mLock);
7174 mAsyncError = true;
7175 mWaitWorkCV.signal();
7176}
7177
Eric Laurentbfb1b832013-01-07 09:53:42 -08007178
7179// ----------------------------------------------------------------------------
Andy Hung71742ab2023-07-07 13:47:37 -07007180
7181/* static */
7182sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007183 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007184 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7185 const audio_offload_info_t& offloadInfo) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007186 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07007187}
7188
Andy Hung2cbc2722023-07-17 17:05:00 -07007189OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07007190 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7191 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07007192 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007193 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007194{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007195 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007196 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007197 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007198}
7199
Andy Hung71742ab2023-07-07 13:47:37 -07007200void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007201{
7202 if (mFlushPending || mHwPaused) {
7203 // If a flush is pending or track was paused, just discard buffered data
7204 flushHw_l();
7205 } else {
7206 mMixerStatus = MIXER_DRAIN_ALL;
7207 threadLoop_drain();
7208 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007209 if (mUseAsyncWrite) {
7210 ALOG_ASSERT(mCallbackThread != 0);
7211 mCallbackThread->exit();
7212 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007213 PlaybackThread::threadLoop_exit();
7214}
7215
Andy Hung71742ab2023-07-07 13:47:37 -07007216PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07007217 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007218)
7219{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007220 size_t count = mActiveTracks.size();
7221
7222 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007223 bool doHwPause = false;
7224 bool doHwResume = false;
7225
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007226 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007227
Eric Laurentbfb1b832013-01-07 09:53:42 -08007228 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07007229 for (const sp<IAfTrack>& t : mActiveTracks) {
7230 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007231#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007232 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007233#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007234 // Only consider last track started for volume and mixer state control.
7235 // In theory an older track could underrun and restart after the new one starts
7236 // but as we only care about the transition phase between two tracks on a
7237 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07007238 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007239 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007240
Haynes Mathew George7844f672014-01-15 12:32:55 -08007241 if (track->isInvalid()) {
7242 ALOGW("An invalidated track shouldn't be in active list");
7243 tracksToRemove->add(track);
7244 continue;
7245 }
7246
Andy Hung3ff4b552023-06-26 19:20:57 -07007247 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007248 ALOGW("An idle track shouldn't be in active list");
7249 continue;
7250 }
7251
Kuowei Li23666472021-01-20 10:23:25 +08007252 if (track->isPausePending()) {
7253 track->pauseAck();
7254 // It is possible a track might have been flushed or stopped.
7255 // Other operations such as flush pending might occur on the next prepare.
7256 if (track->isPausing()) {
7257 track->setPaused();
7258 }
7259 // Always perform pause if last, as an immediate flush will change
7260 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007261 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007262 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007263 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007264 mHwPaused = true;
7265 }
7266 // If we were part way through writing the mixbuffer to
7267 // the HAL we must save this until we resume
7268 // BUG - this will be wrong if a different track is made active,
7269 // in that case we want to discard the pending data in the
7270 // mixbuffer and tell the client to present it again when the
7271 // track is resumed
7272 mPausedWriteLength = mCurrentWriteLength;
7273 mPausedBytesRemaining = mBytesRemaining;
7274 mBytesRemaining = 0; // stop writing
7275 }
7276 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007277 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007278 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007279 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007280 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007281 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007282 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007283 track->flushAck();
7284 if (last) {
7285 mFlushPending = true;
7286 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007287 } else if (track->isResumePending()){
7288 track->resumeAck();
7289 if (last) {
7290 if (mPausedBytesRemaining) {
7291 // Need to continue write that was interrupted
7292 mCurrentWriteLength = mPausedWriteLength;
7293 mBytesRemaining = mPausedBytesRemaining;
7294 mPausedBytesRemaining = 0;
7295 }
7296 if (mHwPaused) {
7297 doHwResume = true;
7298 mHwPaused = false;
7299 // threadLoop_mix() will handle the case that we need to
7300 // resume an interrupted write
7301 }
7302 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007303 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007304
Eric Laurent3df841a2016-07-15 15:15:40 -07007305 mLeftVolFloat = mRightVolFloat = -1.0;
7306
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007307 // Do not handle new data in this iteration even if track->framesReady()
7308 mixerStatus = MIXER_TRACKS_ENABLED;
7309 }
7310 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007311 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007312 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung3ff4b552023-06-26 19:20:57 -07007313 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7314 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007315 if (last) {
7316 // make sure processVolume_l() will apply new volume even if 0
7317 mLeftVolFloat = mRightVolFloat = -1.0;
7318 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007319 }
7320
7321 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007322 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007323 if (previousTrack != 0) {
7324 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007325 // Flush any data still being written from last track
7326 mBytesRemaining = 0;
7327 if (mPausedBytesRemaining) {
7328 // Last track was paused so we also need to flush saved
7329 // mixbuffer state and invalidate track so that it will
7330 // re-submit that unwritten data when it is next resumed
7331 mPausedBytesRemaining = 0;
7332 // Invalidate is a bit drastic - would be more efficient
7333 // to have a flag to tell client that some of the
7334 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007335 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007336 }
7337 // flush data already sent to the DSP if changing audio session as audio
7338 // comes from a different source. Also invalidate previous track to force a
7339 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007340 if (previousTrack->sessionId() != track->sessionId()) {
7341 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007342 }
7343 }
7344 }
7345 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007346 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007347 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007348 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007349 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007350 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007351 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007352 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007353 mixerStatus = MIXER_TRACKS_READY;
7354 }
7355 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007356 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007357 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007358 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007359 // Hardware buffer can hold a large amount of audio so we must
7360 // wait for all current track's data to drain before we say
7361 // that the track is stopped.
7362 if (mBytesRemaining == 0) {
7363 // Only start draining when all data in mixbuffer
7364 // has been written
7365 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung3ff4b552023-06-26 19:20:57 -07007366 track->setState(IAfTrackBase::STOPPING_2);
7367 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007368 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7369 if (last && !mStandby) {
7370 // do not modify drain sequence if we are already draining. This happens
7371 // when resuming from pause after drain.
7372 if ((mDrainSequence & 1) == 0) {
7373 mSleepTimeUs = 0;
7374 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7375 mixerStatus = MIXER_DRAIN_TRACK;
7376 mDrainSequence += 2;
7377 }
7378 if (mHwPaused) {
7379 // It is possible to move from PAUSED to STOPPING_1 without
7380 // a resume so we must ensure hardware is running
7381 doHwResume = true;
7382 mHwPaused = false;
7383 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007384 }
7385 }
Eric Laurente93cc032016-05-05 10:15:10 -07007386 } else if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007387 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007388 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007389 }
7390 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007391 // Drain has completed or we are in standby, signal presentation complete
7392 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007393 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007394 mOutput->presentationComplete();
7395 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007396 track->reset();
7397 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007398 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007399 if (!mUseAsyncWrite) {
7400 // If we don't get explicit drain notification we must
7401 // register discontinuity regardless of whether this is
7402 // the previous (!last) or the upcoming (last) track
7403 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007404 mTimestampVerifier.discontinuity(
7405 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007406 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007407 }
7408 } else {
7409 // No buffers for this track. Give it a few chances to
7410 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007411 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007412 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07007413 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007414 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07007415 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007416 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007417 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7418 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007419 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007420 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007421 // it will then automatically call start() when data is available
7422 track->disable();
7423 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007424 } else if (last){
7425 mixerStatus = MIXER_TRACKS_ENABLED;
7426 }
7427 }
7428 }
7429 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007430 if (track->isReady()) { // check ready to prevent premature start.
7431 processVolume_l(track, last);
7432 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007433 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007434
Eric Laurentea0fade2013-10-04 16:23:48 -07007435 // make sure the pause/flush/resume sequence is executed in the right order.
7436 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7437 // before flush and then resume HW. This can happen in case of pause/flush/resume
7438 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007439 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007440 status_t result = mOutput->stream->pause();
7441 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007442 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007443 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007444 if (mFlushPending) {
7445 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007446 }
Eric Laurentfd477972013-10-25 18:10:40 -07007447 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007448 status_t result = mOutput->stream->resume();
7449 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007450 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007451
Eric Laurentbfb1b832013-01-07 09:53:42 -08007452 // remove all the tracks that need to be...
7453 removeTracks_l(*tracksToRemove);
7454
7455 return mixerStatus;
7456}
7457
Eric Laurentbfb1b832013-01-07 09:53:42 -08007458// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07007459bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007460{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007461 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7462 mWriteAckSequence, mDrainSequence);
7463 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007464 return true;
7465 }
7466 return false;
7467}
7468
Andy Hung71742ab2023-07-07 13:47:37 -07007469bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007470{
7471 Mutex::Autolock _l(mLock);
7472 return waitingAsyncCallback_l();
7473}
7474
Andy Hung71742ab2023-07-07 13:47:37 -07007475void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007476{
Eric Laurente659ef42014-09-29 13:06:46 -07007477 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007478 // Flush anything still waiting in the mixbuffer
7479 mCurrentWriteLength = 0;
7480 mBytesRemaining = 0;
7481 mPausedWriteLength = 0;
7482 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007483 // reset bytes written count to reflect that DSP buffers are empty after flush.
7484 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007485
Eric Laurentbfb1b832013-01-07 09:53:42 -08007486 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007487 // discard any pending drain or write ack by incrementing sequence
7488 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7489 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007490 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007491 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7492 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007493 }
7494}
7495
Andy Hung71742ab2023-07-07 13:47:37 -07007496void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007497{
7498 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007499 if (PlaybackThread::invalidateTracks_l(streamType)) {
7500 mFlushPending = true;
7501 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007502}
7503
Andy Hung71742ab2023-07-07 13:47:37 -07007504void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007505 Mutex::Autolock _l(mLock);
7506 if (PlaybackThread::invalidateTracks_l(portIds)) {
7507 mFlushPending = true;
7508 }
7509}
7510
Eric Laurentbfb1b832013-01-07 09:53:42 -08007511// ----------------------------------------------------------------------------
7512
Andy Hung71742ab2023-07-07 13:47:37 -07007513/* static */
7514sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -07007515 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007516 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007517 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -07007518}
7519
Andy Hung2cbc2722023-07-17 17:05:00 -07007520DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007521 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -07007522 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007523 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007524 mWaitTimeMs(UINT_MAX)
7525{
7526 addOutputTrack(mainThread);
7527}
7528
Andy Hung71742ab2023-07-07 13:47:37 -07007529DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007530{
7531 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7532 mOutputTracks[i]->destroy();
7533 }
7534}
7535
Andy Hung71742ab2023-07-07 13:47:37 -07007536void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007537{
7538 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007539 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007540 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007541 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007542 if (mMixerBufferValid) {
7543 memset(mMixerBuffer, 0, mMixerBufferSize);
7544 } else {
7545 memset(mSinkBuffer, 0, mSinkBufferSize);
7546 }
Eric Laurent81784c32012-11-19 14:55:58 -08007547 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007548 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007549 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007550 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007551 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007552}
7553
Andy Hung71742ab2023-07-07 13:47:37 -07007554void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007555{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007556 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007557 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007558 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007559 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007560 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007561 }
7562 } else if (mBytesWritten != 0) {
7563 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7564 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007565 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007566 } else {
7567 // flush remaining overflow buffers in output tracks
7568 writeFrames = 0;
7569 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007570 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007571 }
7572}
7573
Andy Hung71742ab2023-07-07 13:47:37 -07007574ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007575{
7576 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007577 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7578
7579 // Consider the first OutputTrack for timestamp and frame counting.
7580
7581 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7582 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7583 // we always claim success.
7584 if (i == 0) {
7585 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7586 ALOGD_IF(correction != 0 && writeFrames != 0,
7587 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7588 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7589 mFramesWritten -= correction;
7590 }
7591
7592 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007593 }
Andy Hungcf10d742020-04-28 15:38:24 -07007594 if (mStandby) {
7595 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007596 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007597 mStandby = false;
7598 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007599 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007600}
7601
Andy Hung71742ab2023-07-07 13:47:37 -07007602void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007603{
7604 // DuplicatingThread implements standby by stopping all tracks
7605 for (size_t i = 0; i < outputTracks.size(); i++) {
7606 outputTracks[i]->stop();
7607 }
7608}
7609
Andy Hung71742ab2023-07-07 13:47:37 -07007610void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007611{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007612 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007613
7614 std::stringstream ss;
7615 const size_t numTracks = mOutputTracks.size();
7616 ss << " " << numTracks << " OutputTracks";
7617 if (numTracks > 0) {
7618 ss << ":";
7619 for (const auto &track : mOutputTracks) {
Andy Hung44f27182023-07-06 20:56:16 -07007620 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007621 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007622 if (thread.get() != nullptr) {
7623 ss << thread.get() << ", " << thread->id();
7624 } else {
7625 ss << "null";
7626 }
7627 ss << ")";
7628 }
7629 }
7630 ss << "\n";
7631 std::string result = ss.str();
7632 write(fd, result.c_str(), result.size());
7633}
7634
Andy Hung71742ab2023-07-07 13:47:37 -07007635void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007636{
7637 outputTracks = mOutputTracks;
7638}
7639
Andy Hung71742ab2023-07-07 13:47:37 -07007640void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007641{
7642 outputTracks.clear();
7643}
7644
Andy Hung71742ab2023-07-07 13:47:37 -07007645void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007646{
7647 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007648 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7649 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7650 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7651 const size_t frameCount =
7652 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7653 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7654 // from different OutputTracks and their associated MixerThreads (e.g. one may
7655 // nearly empty and the other may be dropping data).
7656
Svet Ganov33761132021-05-13 22:51:08 +00007657 // TODO b/182392769: use attribution source util, move to server edge
7658 AttributionSourceState attributionSource = AttributionSourceState();
7659 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007660 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007661 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007662 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007663 attributionSource.token = sp<BBinder>::make();
Andy Hung3ff4b552023-06-26 19:20:57 -07007664 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007665 this,
7666 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007667 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007668 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007669 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007670 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007671 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7672 if (status != NO_ERROR) {
7673 ALOGE("addOutputTrack() initCheck failed %d", status);
7674 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007675 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007676 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7677 mOutputTracks.add(outputTrack);
7678 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7679 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007680}
7681
Andy Hung71742ab2023-07-07 13:47:37 -07007682void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007683{
7684 Mutex::Autolock _l(mLock);
7685 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7686 if (mOutputTracks[i]->thread() == thread) {
7687 mOutputTracks[i]->destroy();
7688 mOutputTracks.removeAt(i);
7689 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007690 if (thread->getOutput() == mOutput) {
7691 mOutput = NULL;
7692 }
Eric Laurent81784c32012-11-19 14:55:58 -08007693 return;
7694 }
7695 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007696 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007697}
7698
7699// caller must hold mLock
Andy Hung71742ab2023-07-07 13:47:37 -07007700void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007701{
7702 mWaitTimeMs = UINT_MAX;
7703 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007704 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007705 if (strong != 0) {
7706 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7707 if (waitTimeMs < mWaitTimeMs) {
7708 mWaitTimeMs = waitTimeMs;
7709 }
7710 }
7711 }
7712}
7713
Andy Hung71742ab2023-07-07 13:47:37 -07007714bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007715{
7716 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007717 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007718 if (thread == 0) {
7719 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7720 outputTracks[i].get());
7721 return false;
7722 }
Andy Hung44f27182023-07-06 20:56:16 -07007723 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007724 // see note at standby() declaration
Andy Hung4989d312023-06-29 21:19:25 -07007725 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007726 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7727 thread.get());
7728 return false;
7729 }
7730 }
7731 return true;
7732}
7733
Andy Hung71742ab2023-07-07 13:47:37 -07007734void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007735 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007736{
Kevin Rocard12381092018-04-11 09:19:59 -07007737 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7738 outputTrack->setMetadatas(metadata.tracks);
7739 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007740}
7741
Andy Hung71742ab2023-07-07 13:47:37 -07007742uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007743{
7744 return (mWaitTimeMs * 1000) / 2;
7745}
7746
Andy Hung71742ab2023-07-07 13:47:37 -07007747void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007748{
7749 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7750 updateWaitTime_l();
7751
7752 MixerThread::cacheParameters_l();
7753}
7754
Eric Laurentb3f315a2021-07-13 15:09:05 +02007755// ----------------------------------------------------------------------------
7756
Andy Hung71742ab2023-07-07 13:47:37 -07007757/* static */
7758sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007759 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007760 AudioStreamOut* output,
7761 audio_io_handle_t id,
7762 bool systemReady,
7763 audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007764 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07007765}
7766
Andy Hung2cbc2722023-07-17 17:05:00 -07007767SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007768 AudioStreamOut* output,
7769 audio_io_handle_t id,
7770 bool systemReady,
7771 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07007772 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007773{
7774}
7775
Andy Hung71742ab2023-07-07 13:47:37 -07007776void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007777 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007778
Andy Hung41ccf7f2022-12-14 14:25:49 -08007779 const pid_t tid = getTid();
7780 if (tid == -1) {
7781 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7782 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7783 } else {
7784 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7785 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007786 stream()->setHalThreadPriority(priorityBoost);
7787 }
7788 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007789}
7790
Andy Hung71742ab2023-07-07 13:47:37 -07007791void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007792 // if mSupportedLatencyModes is empty, the HAL stream does not support
7793 // latency mode control and we can exit.
7794 if (mSupportedLatencyModes.empty()) {
7795 return;
7796 }
7797 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7798 if (mSupportedLatencyModes.size() == 1) {
7799 // If the HAL only support one latency mode currently, confirm the choice
7800 latencyMode = mSupportedLatencyModes[0];
7801 } else if (mSupportedLatencyModes.size() > 1) {
7802 // Request low latency if:
7803 // - The low latency mode is requested by the spatializer controller
7804 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7805 // AND
7806 // - At least one active track is spatialized
7807 bool hasSpatializedActiveTrack = false;
7808 for (const auto& track : mActiveTracks) {
7809 if (track->isSpatialized()) {
7810 hasSpatializedActiveTrack = true;
7811 break;
7812 }
7813 }
7814 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7815 latencyMode = AUDIO_LATENCY_MODE_LOW;
7816 }
7817 }
7818
7819 if (latencyMode != mSetLatencyMode) {
7820 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007821 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7822 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007823 if (status == NO_ERROR) {
7824 mSetLatencyMode = latencyMode;
7825 }
7826 }
7827}
7828
Andy Hung71742ab2023-07-07 13:47:37 -07007829status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007830 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7831 return BAD_VALUE;
7832 }
7833 Mutex::Autolock _l(mLock);
7834 mRequestedLatencyMode = mode;
7835 return NO_ERROR;
7836}
7837
Andy Hung71742ab2023-07-07 13:47:37 -07007838void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007839{
7840 bool hasVirtualizer = false;
7841 bool hasDownMixer = false;
Andy Hungbd72c542023-06-20 18:56:17 -07007842 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007843 {
7844 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07007845 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007846 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007847 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007848 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7849 }
7850
7851 finalDownMixer = mFinalDownMixer;
7852 mFinalDownMixer.clear();
7853 }
7854
7855 if (hasVirtualizer) {
7856 if (finalDownMixer != nullptr) {
7857 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007858 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007859 }
7860 finalDownMixer.clear();
7861 } else if (!hasDownMixer) {
7862 std::vector<effect_descriptor_t> descriptors;
Andy Hung2cbc2722023-07-17 17:05:00 -07007863 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007864 EFFECT_UIID_DOWNMIX, &descriptors);
7865 if (status != NO_ERROR) {
7866 return;
7867 }
7868 ALOG_ASSERT(!descriptors.empty(),
7869 "%s getDescriptors() returned no error but empty list", __func__);
7870
7871 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7872 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007873 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007874
7875 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7876 ALOGW("%s error creating downmixer %d", __func__, status);
7877 finalDownMixer.clear();
7878 } else {
7879 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007880 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007881 }
7882 }
7883
7884 {
7885 Mutex::Autolock _l(mLock);
7886 mFinalDownMixer = finalDownMixer;
7887 }
7888}
7889
Eric Laurent81784c32012-11-19 14:55:58 -08007890// ----------------------------------------------------------------------------
7891// Record
7892// ----------------------------------------------------------------------------
7893
Andy Hung2cbc2722023-07-17 17:05:00 -07007894sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007895 AudioStreamIn* input,
7896 audio_io_handle_t id,
7897 bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007898 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung44f27182023-07-06 20:56:16 -07007899}
7900
Andy Hung2cbc2722023-07-17 17:05:00 -07007901RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007902 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007903 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007904 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007905 ) :
Andy Hung2cbc2722023-07-17 17:05:00 -07007906 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007907 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007908 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007909 mActiveTracks(&this->mLocalLog),
7910 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007911 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007912 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007913 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7914 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007915 // mFastCapture below
7916 , mFastCaptureFutex(0)
7917 // mInputSource
7918 // mPipeSink
7919 // mPipeSource
7920 , mPipeFramesP2(0)
7921 // mPipeMemory
7922 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007923 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007924 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007925{
Glenn Kastend7dca052015-03-05 16:05:54 -08007926 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07007927 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007928
George Burgess IVa8f90c12020-05-14 11:27:19 -07007929 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007930 mIsMsdDevice = strcmp(
7931 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7932 }
7933
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007934 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007935
Andy Hungc8fddf32018-08-08 18:32:37 -07007936 // TODO: We may also match on address as well as device type for
7937 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007938 // TODO: This property should be ensure that only contains one single device type.
7939 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7940 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007941 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7942 : AUDIO_DEVICE_NONE));
7943
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007944 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007945 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007946 size_t numCounterOffers = 0;
7947 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007948#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007949 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007950#else
7951 (void)
7952#endif
7953 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007954 ALOG_ASSERT(index == 0);
7955
7956 // initialize fast capture depending on configuration
7957 bool initFastCapture;
7958 switch (kUseFastCapture) {
7959 case FastCapture_Never:
7960 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007961 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007962 break;
7963 case FastCapture_Always:
7964 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007965 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007966 break;
7967 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007968 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7969 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7970 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7971 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7972 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007973 break;
7974 // case FastCapture_Dynamic:
7975 }
7976
7977 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007978 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007979 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007980 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7981 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007982 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007983 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007984 const sp<MemoryDealer> roHeap(readOnlyHeap());
7985 sp<IMemory> pipeMemory;
7986 if ((roHeap == 0) ||
7987 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007988 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007989 ALOGE("not enough memory for pipe buffer size=%zu; "
7990 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7991 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7992 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007993 goto failed;
7994 }
7995 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7996 memset(pipeBuffer, 0, pipeSize);
7997 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07007998 const NBAIO_Format offersFast[1] = {format};
7999 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008000 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07008001 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008002 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008003 mPipeSink = pipe;
8004 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07008005 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008006 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07008007 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008008 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008009 mPipeSource = pipeReader;
8010 mPipeFramesP2 = pipeFramesP2;
8011 mPipeMemory = pipeMemory;
8012
8013 // create fast capture
8014 mFastCapture = new FastCapture();
8015 FastCaptureStateQueue *sq = mFastCapture->sq();
8016#ifdef STATE_QUEUE_DUMP
8017 // FIXME
8018#endif
8019 FastCaptureState *state = sq->begin();
8020 state->mCblk = NULL;
8021 state->mInputSource = mInputSource.get();
8022 state->mInputSourceGen++;
8023 state->mPipeSink = pipe;
8024 state->mPipeSinkGen++;
8025 state->mFrameCount = mFrameCount;
8026 state->mCommand = FastCaptureState::COLD_IDLE;
8027 // already done in constructor initialization list
8028 //mFastCaptureFutex = 0;
8029 state->mColdFutexAddr = &mFastCaptureFutex;
8030 state->mColdGen++;
8031 state->mDumpState = &mFastCaptureDumpState;
8032#ifdef TEE_SINK
8033 // FIXME
8034#endif
Andy Hung2cbc2722023-07-17 17:05:00 -07008035 mFastCaptureNBLogWriter =
8036 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008037 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8038 sq->end();
8039 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8040
8041 // start the fast capture
8042 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8043 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008044 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008045 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008046#ifdef AUDIO_WATCHDOG
8047 // FIXME
8048#endif
8049
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008050 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008051 }
Andy Hung8946a282018-04-19 20:04:56 -07008052#ifdef TEE_SINK
8053 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8054 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8055#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008056failed: ;
8057
8058 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008059}
8060
Andy Hung71742ab2023-07-07 13:47:37 -07008061RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008062{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008063 if (mFastCapture != 0) {
8064 FastCaptureStateQueue *sq = mFastCapture->sq();
8065 FastCaptureState *state = sq->begin();
8066 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8067 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8068 if (old == -1) {
8069 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8070 }
8071 }
8072 state->mCommand = FastCaptureState::EXIT;
8073 sq->end();
8074 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8075 mFastCapture->join();
8076 mFastCapture.clear();
8077 }
Andy Hung2cbc2722023-07-17 17:05:00 -07008078 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8079 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008080 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008081}
8082
Andy Hung71742ab2023-07-07 13:47:37 -07008083void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008084{
Glenn Kastend7dca052015-03-05 16:05:54 -08008085 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008086}
8087
Andy Hung71742ab2023-07-07 13:47:37 -07008088void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008089{
8090 ALOGV(" preExit()");
8091 Mutex::Autolock _l(mLock);
8092 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008093 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008094 track->invalidate();
8095 }
8096 mActiveTracks.clear();
8097 mStartStopCond.broadcast();
8098}
8099
Andy Hung71742ab2023-07-07 13:47:37 -07008100bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008101{
Eric Laurent81784c32012-11-19 14:55:58 -08008102 nsecs_t lastWarning = 0;
8103
8104 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008105
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008106reacquire_wakelock:
Andy Hung3ff4b552023-06-26 19:20:57 -07008107 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008108 {
8109 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008110 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008111 }
8112
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008113 // used to request a deferred sleep, to be executed later while mutex is unlocked
8114 uint32_t sleepUs = 0;
8115
Andy Hung446f4df2019-02-21 12:26:41 -08008116 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8117
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008118 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008119 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungbd72c542023-06-20 18:56:17 -07008120 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008121
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008122 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung3ff4b552023-06-26 19:20:57 -07008123 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008124
Glenn Kasten735f45f2014-08-18 15:51:59 -07008125 // reference to the (first and only) active fast track
Andy Hung3ff4b552023-06-26 19:20:57 -07008126 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008127
Glenn Kasten735f45f2014-08-18 15:51:59 -07008128 // reference to a fast track which is about to be removed
Andy Hung3ff4b552023-06-26 19:20:57 -07008129 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008130
Eric Laurent33403f02020-05-29 18:35:06 -07008131 bool silenceFastCapture = false;
8132
Eric Laurent81784c32012-11-19 14:55:58 -08008133 { // scope for mLock
8134 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008135
Eric Laurent021cf962014-05-13 10:18:14 -07008136 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008137
Eric Laurent000a4192014-01-29 15:17:32 -08008138 // check exitPending here because checkForNewParameters_l() and
8139 // checkForNewParameters_l() can temporarily release mLock
8140 if (exitPending()) {
8141 break;
8142 }
8143
Eric Laurent5c25d562016-07-13 17:17:45 -07008144 // sleep with mutex unlocked
8145 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008146 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008147 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8148 ATRACE_END();
8149 sleepUs = 0;
8150 continue;
8151 }
8152
Glenn Kasten2b806402013-11-20 16:37:38 -08008153 // if no active track(s), then standby and release wakelock
8154 size_t size = mActiveTracks.size();
8155 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008156 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008157 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008158 releaseWakeLock_l();
8159 ALOGV("RecordThread: loop stopping");
8160 // go to sleep
8161 mWaitWorkCV.wait(mLock);
8162 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008163 goto reacquire_wakelock;
8164 }
8165
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008166 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008167 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008168 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008169
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008170 activeTrack = mActiveTracks[i];
8171 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008172 if (activeTrack->isFastTrack()) {
8173 ALOG_ASSERT(fastTrackToRemove == 0);
8174 fastTrackToRemove = activeTrack;
8175 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008176 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008177 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008178 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008179 continue;
8180 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008181
Andy Hung3ff4b552023-06-26 19:20:57 -07008182 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008183 switch (activeTrackState) {
8184
Andy Hung3ff4b552023-06-26 19:20:57 -07008185 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008186 mActiveTracks.remove(activeTrack);
Andy Hung3ff4b552023-06-26 19:20:57 -07008187 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008188 doBroadcast = true;
8189 size--;
8190 continue;
8191
Andy Hung3ff4b552023-06-26 19:20:57 -07008192 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008193 sleepUs = 10000;
8194 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008195 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008196 continue;
8197
Andy Hung3ff4b552023-06-26 19:20:57 -07008198 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008199 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008200 if (mStandby) {
8201 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008202 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008203 mStandby = false;
8204 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008205 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008206 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008207 break;
8208
Andy Hung3ff4b552023-06-26 19:20:57 -07008209 case 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::IDLE: // cannot be on ActiveTracks if idle
8214 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8215 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008216 default:
Andy Hungce685402018-10-05 17:23:27 -07008217 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8218 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008219 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008220
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008221 if (activeTrack->isFastTrack()) {
8222 ALOG_ASSERT(!mFastTrackAvail);
8223 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008224 // if the active fast track is silenced either:
8225 // 1) silence the whole capture from fast capture buffer if this is
8226 // the only active track
8227 // 2) invalidate this track: this will cause the client to reconnect and possibly
8228 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008229 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008230 if (activeTrack->isSilenced()) {
8231 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008232 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008233 } else {
8234 silenceFastCapture = true;
8235 }
8236 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008237 // Invalidate fast tracks if access to audio history is required as this is not
8238 // possible with fast tracks. Once the fast track has been invalidated, no new
8239 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8240 if (mMaxSharedAudioHistoryMs != 0) {
8241 invalidate = true;
8242 }
8243 if (invalidate) {
8244 activeTrack->invalidate();
8245 ALOG_ASSERT(fastTrackToRemove == 0);
8246 fastTrackToRemove = activeTrack;
8247 removeTrack_l(activeTrack);
8248 mActiveTracks.remove(activeTrack);
8249 size--;
8250 continue;
8251 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008252 fastTrack = activeTrack;
8253 }
Eric Laurent33403f02020-05-29 18:35:06 -07008254
8255 activeTracks.add(activeTrack);
8256 i++;
8257
Glenn Kasten9e982352013-08-14 14:39:50 -07008258 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008259
Andy Hungdae27702016-10-31 14:01:16 -07008260 mActiveTracks.updatePowerState(this);
8261
Kevin Rocard069c2712018-03-29 19:09:14 -07008262 updateMetadata_l();
8263
Eric Laurent5c25d562016-07-13 17:17:45 -07008264 if (allStopped) {
8265 standbyIfNotAlreadyInStandby();
8266 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008267 if (doBroadcast) {
8268 mStartStopCond.broadcast();
8269 }
8270
8271 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008272 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008273 if (sleepUs == 0) {
8274 sleepUs = kRecordThreadSleepUs;
8275 }
8276 continue;
8277 }
8278 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008279
Eric Laurent81784c32012-11-19 14:55:58 -08008280 lockEffectChains_l(effectChains);
8281 }
8282
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008283 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008284
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008285 size_t size = effectChains.size();
8286 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008287 // thread mutex is not locked, but effect chain is locked
8288 effectChains[i]->process_l();
8289 }
8290
Glenn Kasten735f45f2014-08-18 15:51:59 -07008291 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008292 if (mFastCapture != 0) {
8293 FastCaptureStateQueue *sq = mFastCapture->sq();
8294 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008295 bool didModify = false;
8296 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008297 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8298 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8299 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8300 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8301 if (old == -1) {
8302 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8303 }
8304 }
8305 state->mCommand = FastCaptureState::READ_WRITE;
8306#if 0 // FIXME
Andy Hung2cbc2722023-07-17 17:05:00 -07008307 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008308 FastThreadDumpState::kSamplingNforLowRamDevice :
8309 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008310#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008311 didModify = true;
8312 }
8313 audio_track_cblk_t *cblkOld = state->mCblk;
8314 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8315 if (cblkNew != cblkOld) {
8316 state->mCblk = cblkNew;
8317 // block until acked if removing a fast track
8318 if (cblkOld != NULL) {
8319 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8320 }
8321 didModify = true;
8322 }
jiabin01c8f562018-07-19 17:47:28 -07008323 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8324 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8325 if (state->mFastPatchRecordBufferProvider != abp) {
8326 state->mFastPatchRecordBufferProvider = abp;
8327 state->mFastPatchRecordFormat = fastTrack == 0 ?
8328 AUDIO_FORMAT_INVALID : fastTrack->format();
8329 didModify = true;
8330 }
Eric Laurent33403f02020-05-29 18:35:06 -07008331 if (state->mSilenceCapture != silenceFastCapture) {
8332 state->mSilenceCapture = silenceFastCapture;
8333 didModify = true;
8334 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008335 sq->end(didModify);
8336 if (didModify) {
8337 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008338#if 0
8339 if (kUseFastCapture == FastCapture_Dynamic) {
8340 mNormalSource = mPipeSource;
8341 }
8342#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008343 }
8344 }
8345
Glenn Kasten735f45f2014-08-18 15:51:59 -07008346 // now run the fast track destructor with thread mutex unlocked
8347 fastTrackToRemove.clear();
8348
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008349 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8350 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8351 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8352 // If destination is non-contiguous, first read past the nominal end of buffer, then
8353 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008354
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008355 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07008356 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008357 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008358
8359 // If an NBAIO source is present, use it to read the normal capture's data
8360 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008361 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008362
8363 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8364 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8365 // we immediately retry the read() to get data and prevent another overflow.
8366 for (int retries = 0; retries <= 2; ++retries) {
8367 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8368 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8369 framesToRead);
8370 if (framesRead != OVERRUN) break;
8371 }
8372
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008373 const ssize_t availableToRead = mPipeSource->availableToRead();
8374 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008375 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008376 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008377 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8378 "more frames to read than fifo size, %zd > %zu",
8379 availableToRead, mPipeFramesP2);
8380 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8381 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8382 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8383 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008384 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8385 }
8386 if (framesRead < 0) {
8387 status_t status = (status_t) framesRead;
8388 switch (status) {
8389 case OVERRUN:
8390 ALOGW("overrun on read from pipe");
8391 framesRead = 0;
8392 break;
8393 case NEGOTIATE:
8394 ALOGE("re-negotiation is needed");
8395 framesRead = -1; // Will cause an attempt to recover.
8396 break;
8397 default:
8398 ALOGE("unknown error %d on read from pipe", status);
8399 break;
8400 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008401 }
8402 // otherwise use the HAL / AudioStreamIn directly
8403 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008404 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008405 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008406 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008407 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008408 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008409 if (result < 0) {
8410 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008411 } else {
8412 framesRead = bytesRead / mFrameSize;
8413 }
8414 }
8415
Andy Hung446f4df2019-02-21 12:26:41 -08008416 const int64_t lastIoEndNs = systemTime(); // end IO timing
8417
Andy Hung3f0c9022016-01-15 17:49:46 -08008418 // Update server timestamp with server stats
8419 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008420 if (framesRead >= 0) {
8421 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8422 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8423 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008424
8425 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008426 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008427 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008428 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008429 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8430 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8431 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008432 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008433 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8434
8435 mTimestampVerifier.add(position, time, mSampleRate);
8436
8437 // Correct timestamps
8438 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008439 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008440 id(), (long long)time, (long long)position);
8441 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8442 position = correctedTimestamp.mFrames;
8443 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008444 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008445 id(), (long long)time, (long long)position);
8446 }
8447
Andy Hung3f0c9022016-01-15 17:49:46 -08008448 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8449 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8450 // Note: In general record buffers should tend to be empty in
8451 // a properly running pipeline.
8452 //
8453 // Also, it is not advantageous to call get_presentation_position during the read
8454 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008455 } else {
8456 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008457 }
8458 }
Andy Hunge6c37112019-02-26 17:38:10 -08008459
8460 // From the timestamp, input read latency is negative output write latency.
8461 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung3ff4b552023-06-26 19:20:57 -07008462 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008463 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8464 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8465 mLatencyMs.add(latencyMs);
8466 }
8467
Andy Hung3f0c9022016-01-15 17:49:46 -08008468 // Use this to track timestamp information
8469 // ALOGD("%s", mTimestamp.toString().c_str());
8470
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008471 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008472 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008473 // Force input into standby so that it tries to recover at next read attempt
8474 inputStandBy();
8475 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008476 }
8477 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008478 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008479 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008480 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008481 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008482
Andy Hung8946a282018-04-19 20:04:56 -07008483#ifdef TEE_SINK
8484 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8485#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008486 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008487 {
8488 size_t part1 = mRsmpInFramesP2 - rear;
8489 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008490 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008491 (framesRead - part1) * mFrameSize);
8492 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008493 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008494 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495
8496 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008497
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008498 // loop over each active track
8499 for (size_t i = 0; i < size; i++) {
8500 activeTrack = activeTracks[i];
8501
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008502 // skip fast tracks, as those are handled directly by FastCapture
8503 if (activeTrack->isFastTrack()) {
8504 continue;
8505 }
8506
Andy Hung73c02e42015-03-29 01:13:58 -07008507 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008508 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8509
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008510 enum {
8511 OVERRUN_UNKNOWN,
8512 OVERRUN_TRUE,
8513 OVERRUN_FALSE
8514 } overrun = OVERRUN_UNKNOWN;
8515
8516 // loop over getNextBuffer to handle circular sink
8517 for (;;) {
8518
Andy Hung3ff4b552023-06-26 19:20:57 -07008519 activeTrack->sinkBuffer().frameCount = ~0;
8520 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8521 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008522 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8523
Andy Hung73c02e42015-03-29 01:13:58 -07008524 // check available frames and handle overrun conditions
8525 // if the record track isn't draining fast enough.
8526 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008527 size_t framesIn;
Andy Hung3ff4b552023-06-26 19:20:57 -07008528 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008529 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008530 overrun = OVERRUN_TRUE;
8531 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008532 if (framesOut == 0 || framesIn == 0) {
8533 break;
8534 }
8535
Andy Hung6770c6f2015-04-07 13:43:36 -07008536 // Don't allow framesOut to be larger than what is possible with resampling
8537 // from framesIn.
8538 // This isn't strictly necessary but helps limit buffer resizing in
8539 // RecordBufferConverter. TODO: remove when no longer needed.
8540 framesOut = min(framesOut,
8541 destinationFramesPossible(
Andy Hung3ff4b552023-06-26 19:20:57 -07008542 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008543
8544 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008545 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008546 // straight from RecordThread buffer to RecordTrack buffer.
8547 AudioBufferProvider::Buffer buffer;
8548 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008549 const status_t getNextBufferStatus =
Andy Hung3ff4b552023-06-26 19:20:57 -07008550 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07008551 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008552 ALOGV_IF(buffer.frameCount != framesOut,
8553 "%s() read less than expected (%zu vs %zu)",
8554 __func__, buffer.frameCount, framesOut);
8555 framesOut = buffer.frameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008556 memcpy(activeTrack->sinkBuffer().raw,
8557 buffer.raw, buffer.frameCount * mFrameSize);
8558 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008559 } else {
8560 framesOut = 0;
8561 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008562 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008563 }
8564 } else {
8565 // process frames from the RecordThread buffer provider to the RecordTrack
8566 // buffer
Andy Hung3ff4b552023-06-26 19:20:57 -07008567 framesOut = activeTrack->recordBufferConverter()->convert(
8568 activeTrack->sinkBuffer().raw,
8569 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008570 framesOut);
8571 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008572
8573 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8574 overrun = OVERRUN_FALSE;
8575 }
8576
Andy Hung93bb5732023-05-04 21:16:34 -07008577 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8578 const ssize_t framesToDrop =
Andy Hung3ff4b552023-06-26 19:20:57 -07008579 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008580 if (framesToDrop == 0) {
8581 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008582 if (framesOut > 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008583 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008584 // Sanitize before releasing if the track has no access to the source data
8585 // An idle UID receives silence from non virtual devices until active
8586 if (activeTrack->isSilenced()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008587 memset(activeTrack->sinkBuffer().raw,
8588 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008589 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008590 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008591 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008592 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008593 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008594 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008595 }
8596 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008597
8598 switch (overrun) {
8599 case OVERRUN_TRUE:
8600 // client isn't retrieving buffers fast enough
8601 if (!activeTrack->setOverflow()) {
8602 nsecs_t now = systemTime();
8603 // FIXME should lastWarning per track?
8604 if ((now - lastWarning) > kWarningThrottleNs) {
8605 ALOGW("RecordThread: buffer overflow");
8606 lastWarning = now;
8607 }
8608 }
8609 break;
8610 case OVERRUN_FALSE:
8611 activeTrack->clearOverflow();
8612 break;
8613 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008614 break;
8615 }
8616
Andy Hung3f0c9022016-01-15 17:49:46 -08008617 // update frame information and push timestamp out
8618 activeTrack->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07008619 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008620 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8621 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008622 }
8623
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008624unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008625 // enable changes in effect chain
8626 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008627 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008628 if (audio_has_proportional_frames(mFormat)
8629 && loopCount == lastLoopCountRead + 1) {
8630 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8631 const double jitterMs =
8632 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8633 {framesRead, readPeriodNs},
8634 {0, 0} /* lastTimestamp */, mSampleRate);
8635 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8636
8637 Mutex::Autolock _l(mLock);
8638 mIoJitterMs.add(jitterMs);
8639 mProcessTimeMs.add(processMs);
8640 }
8641 // update timing info.
8642 mLastIoBeginNs = lastIoBeginNs;
8643 mLastIoEndNs = lastIoEndNs;
8644 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008645 }
8646
Glenn Kasten93e471f2013-08-19 08:40:07 -07008647 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008648
8649 {
8650 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008651 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008652 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008653 track->invalidate();
8654 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008655 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008656 mStartStopCond.broadcast();
8657 }
8658
8659 releaseWakeLock();
8660
8661 ALOGV("RecordThread %p exiting", this);
8662 return false;
8663}
8664
Andy Hung71742ab2023-07-07 13:47:37 -07008665void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008666{
8667 if (!mStandby) {
8668 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008669 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008670 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008671 mStandby = true;
8672 }
8673}
8674
Andy Hung71742ab2023-07-07 13:47:37 -07008675void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008676{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008677 // Idle the fast capture if it's currently running
8678 if (mFastCapture != 0) {
8679 FastCaptureStateQueue *sq = mFastCapture->sq();
8680 FastCaptureState *state = sq->begin();
8681 if (!(state->mCommand & FastCaptureState::IDLE)) {
8682 state->mCommand = FastCaptureState::COLD_IDLE;
8683 state->mColdFutexAddr = &mFastCaptureFutex;
8684 state->mColdGen++;
8685 mFastCaptureFutex = 0;
8686 sq->end();
8687 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8688 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8689#if 0
8690 if (kUseFastCapture == FastCapture_Dynamic) {
8691 // FIXME
8692 }
8693#endif
8694#ifdef AUDIO_WATCHDOG
8695 // FIXME
8696#endif
8697 } else {
8698 sq->end(false /*didModify*/);
8699 }
8700 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008701 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008702 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008703
8704 // If going into standby, flush the pipe source.
8705 if (mPipeSource.get() != nullptr) {
8706 const ssize_t flushed = mPipeSource->flush();
8707 if (flushed > 0) {
8708 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8709 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8710 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8711 }
8712 }
Eric Laurent81784c32012-11-19 14:55:58 -08008713}
8714
Glenn Kasten05997e22014-03-13 15:08:33 -07008715// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07008716sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07008717 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008718 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008719 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008720 audio_format_t format,
8721 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008722 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008723 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008724 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008725 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008726 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008727 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008728 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008729 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008730 audio_port_handle_t portId,
8731 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008732{
Glenn Kasten74935e42013-12-19 08:56:45 -08008733 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008734 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008735 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008736 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008737 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008738 audio_input_flags_t requestedFlags = *flags;
8739 uint32_t sampleRate;
8740
8741 lStatus = initCheck();
8742 if (lStatus != NO_ERROR) {
8743 ALOGE("createRecordTrack_l() audio driver not initialized");
8744 goto Exit;
8745 }
8746
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008747 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8748 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8749 lStatus = BAD_VALUE;
8750 goto Exit;
8751 }
8752
Eric Laurentec376dc2021-04-08 20:41:22 +02008753 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008754 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008755 lStatus = PERMISSION_DENIED;
8756 goto Exit;
8757 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008758 if (maxSharedAudioHistoryMs < 0
Andy Hung4d693a32023-07-19 12:47:35 -07008759 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008760 lStatus = BAD_VALUE;
8761 goto Exit;
8762 }
8763 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008764 if (*pSampleRate == 0) {
8765 *pSampleRate = mSampleRate;
8766 }
8767 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008768
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008769 // special case for FAST flag considered OK if fast capture is present and access to
8770 // audio history is not required
8771 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008772 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8773 }
8774
Eric Laurentf14db3c2017-12-08 14:20:36 -08008775 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008776 if ((*flags & inputFlags) != *flags) {
8777 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8778 " input flags (%08x)",
8779 *flags, inputFlags);
8780 *flags = (audio_input_flags_t)(*flags & inputFlags);
8781 }
Eric Laurent81784c32012-11-19 14:55:58 -08008782
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008783 // client expresses a preference for FAST and no access to audio history,
8784 // but we get the final say
8785 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008786 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008787 // we formerly checked for a callback handler (non-0 tid),
8788 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008789 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008790 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008791 // Frame count is not specified (0), or is less than or equal the pipe depth.
8792 // It is OK to provide a higher capacity than requested.
8793 // We will force it to mPipeFramesP2 below.
8794 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008795 // PCM data
8796 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008797 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008798 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008799 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008800 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008801 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008802 hasFastCapture() &&
8803 // there are sufficient fast track slots available
8804 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008805 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008806 // check compatibility with audio effects.
8807 Mutex::Autolock _l(mLock);
8808 // Do not accept FAST flag if the session has software effects
Andy Hungbd72c542023-06-20 18:56:17 -07008809 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008810 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008811 audio_input_flags_t old = *flags;
8812 chain->checkInputFlagCompatibility(flags);
8813 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008814 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8815 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008816 }
8817 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008818 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008819 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8820 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008821 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008822 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8823 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008824 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008825 this, frameCount, mFrameCount, mPipeFramesP2,
8826 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008827 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008828 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008829 }
8830 }
8831
Eric Laurentf14db3c2017-12-08 14:20:36 -08008832 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8833 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8834 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8835 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8836 lStatus = BAD_TYPE;
8837 goto Exit;
8838 }
8839
Glenn Kasten74105912014-07-03 12:28:53 -07008840 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008841 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008842 // fast track: frame count is exactly the pipe depth
8843 frameCount = mPipeFramesP2;
8844 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008845 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008846 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008847 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8848 // or 20 ms if there is a fast capture
8849 // TODO This could be a roundupRatio inline, and const
8850 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8851 * sampleRate + mSampleRate - 1) / mSampleRate;
8852 // minimum number of notification periods is at least kMinNotifications,
8853 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8854 static const size_t kMinNotifications = 3;
8855 static const uint32_t kMinMs = 30;
8856 // TODO This could be a roundupRatio inline
8857 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8858 // TODO This could be a roundupRatio inline
8859 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8860 maxNotificationFrames;
8861 const size_t minFrameCount = maxNotificationFrames *
8862 max(kMinNotifications, minNotificationsByMs);
8863 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008864 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8865 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008866 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008867 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008868 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008869 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008870
8871 { // scope for mLock
8872 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008873 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008874 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008875 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008876 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008877 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008878 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008879 }
Eric Laurent81784c32012-11-19 14:55:58 -08008880
Andy Hung3ff4b552023-06-26 19:20:57 -07008881 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008882 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008883 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung3ff4b552023-06-26 19:20:57 -07008884 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008885 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008886
Glenn Kasten03003332013-08-06 15:40:54 -07008887 lStatus = track->initCheck();
8888 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008889 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008890 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008891 goto Exit;
8892 }
8893 mTracks.add(track);
8894
Eric Laurent05067782016-06-01 18:27:28 -07008895 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008896 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8897 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8898 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008899 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008900 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008901
8902 if (maxSharedAudioHistoryMs != 0) {
8903 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8904 }
Eric Laurent81784c32012-11-19 14:55:58 -08008905 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008906
Eric Laurent81784c32012-11-19 14:55:58 -08008907 lStatus = NO_ERROR;
8908
8909Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008910 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008911 return track;
8912}
8913
Andy Hung71742ab2023-07-07 13:47:37 -07008914status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008915 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008916 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008917{
8918 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8919 sp<ThreadBase> strongMe = this;
8920 status_t status = NO_ERROR;
8921
8922 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008923 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008924 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008925 recordTrack->synchronizedRecordState().startRecording(
Andy Hung2cbc2722023-07-17 17:05:00 -07008926 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008927 event, triggerSession,
8928 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008929 }
8930
8931 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008932 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008933 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008934 if (recordTrack->isInvalid()) {
8935 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008936 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8937 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008938 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008939 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008940 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008941 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8942 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008943 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung3ff4b552023-06-26 19:20:57 -07008944 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008945 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07008946 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008947 }
8948 return status;
8949 }
8950
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008951 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8952 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8953 // or using a separate command thread
Andy Hung3ff4b552023-06-26 19:20:57 -07008954 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008955 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008956 if (recordTrack->isExternalTrack()) {
8957 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008958 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008959 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008960 if (recordTrack->isInvalid()) {
8961 recordTrack->clearSyncStartEvent();
Andy Hung3ff4b552023-06-26 19:20:57 -07008962 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8963 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008964 // STARTING_2 forces destroy to call stopInput.
8965 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008966 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8967 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008968 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008969 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008970 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung3ff4b552023-06-26 19:20:57 -07008971 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008972 // Someone else has changed state, let them take over,
8973 // leave mState in the new state.
8974 recordTrack->clearSyncStartEvent();
8975 return INVALID_OPERATION;
8976 }
8977 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008978 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008979 ALOGW("%s(%d): startInput failed, status %d",
8980 __func__, recordTrack->id(), status);
8981 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8982 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008983 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008984 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008985 return status;
8986 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008987 sendIoConfigEvent_l(
8988 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008989 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008990
8991 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8992
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008993 // Catch up with current buffer indices if thread is already running.
8994 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8995 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8996 // see previously buffered data before it called start(), but with greater risk of overrun.
8997
Andy Hung3ff4b552023-06-26 19:20:57 -07008998 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008999 if (!recordTrack->isDirect()) {
9000 // clear any converter state as new data will be discontinuous
Andy Hung3ff4b552023-06-26 19:20:57 -07009001 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009002 }
Andy Hung3ff4b552023-06-26 19:20:57 -07009003 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009004 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08009005 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08009006 return status;
9007 }
Eric Laurent81784c32012-11-19 14:55:58 -08009008}
9009
Andy Hung71742ab2023-07-07 13:47:37 -07009010void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009011{
Andy Hung71742ab2023-07-07 13:47:37 -07009012 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009013
9014 if (strongEvent != 0) {
Andy Hung02a6c4e2023-06-23 19:27:19 -07009015 sp<IAfTrackBase> ptr =
9016 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9017 if (ptr != nullptr) {
Andy Hung56126702023-07-14 11:00:08 -07009018 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hung02a6c4e2023-06-23 19:27:19 -07009019 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009020 }
Eric Laurent81784c32012-11-19 14:55:58 -08009021 }
9022}
9023
Andy Hung71742ab2023-07-07 13:47:37 -07009024bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009025 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07009026 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07009027 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung3ff4b552023-06-26 19:20:57 -07009028 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009029 return false;
9030 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009031 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung3ff4b552023-06-26 19:20:57 -07009032 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009033
Andy Hungabfab202019-03-07 19:45:54 -08009034 // NOTE: Waiting here is important to keep stop synchronous.
9035 // This is needed for proper patchRecord peer release.
Andy Hung3ff4b552023-06-26 19:20:57 -07009036 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07009037 mWaitWorkCV.broadcast(); // signal thread to stop
9038 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08009039 }
Andy Hungce685402018-10-05 17:23:27 -07009040
Andy Hung3ff4b552023-06-26 19:20:57 -07009041 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009042 ALOGV("Record stopped OK");
9043 return true;
9044 }
Andy Hungce685402018-10-05 17:23:27 -07009045
9046 // don't handle anything - we've been invalidated or restarted and in a different state
9047 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung3ff4b552023-06-26 19:20:57 -07009048 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009049 return false;
9050}
9051
Andy Hung71742ab2023-07-07 13:47:37 -07009052bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009053{
9054 return false;
9055}
9056
Andy Hung71742ab2023-07-07 13:47:37 -07009057status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009058{
9059#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9060 if (!isValidSyncEvent(event)) {
9061 return BAD_VALUE;
9062 }
9063
Glenn Kastend848eb42016-03-08 13:42:11 -08009064 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009065 status_t ret = NAME_NOT_FOUND;
9066
9067 Mutex::Autolock _l(mLock);
9068
9069 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009070 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009071 if (eventSession == track->sessionId()) {
9072 (void) track->setSyncEvent(event);
9073 ret = NO_ERROR;
9074 }
9075 }
9076 return ret;
9077#else
9078 return BAD_VALUE;
9079#endif
9080}
9081
Andy Hung71742ab2023-07-07 13:47:37 -07009082status_t RecordThread::getActiveMicrophones(
Andy Hung44f27182023-07-06 20:56:16 -07009083 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009084{
9085 ALOGV("RecordThread::getActiveMicrophones");
9086 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009087 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009088 return NO_INIT;
9089 }
jiabin9ff780e2018-03-19 18:19:52 -07009090 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9091 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009092}
9093
Andy Hung71742ab2023-07-07 13:47:37 -07009094status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009095 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009096{
Paul McLean12340082019-03-19 09:35:05 -06009097 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009098 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009099 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009100 return NO_INIT;
9101 }
Paul McLean12340082019-03-19 09:35:05 -06009102 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009103}
9104
Andy Hung71742ab2023-07-07 13:47:37 -07009105status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009106{
Paul McLean12340082019-03-19 09:35:05 -06009107 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009108 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009109 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009110 return NO_INIT;
9111 }
Paul McLean12340082019-03-19 09:35:05 -06009112 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009113}
9114
Andy Hung71742ab2023-07-07 13:47:37 -07009115status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009116 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9117 int64_t sharedAudioStartMs) {
9118 AutoMutex _l(mLock);
9119 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9120}
9121
Andy Hung71742ab2023-07-07 13:47:37 -07009122status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009123 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9124 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009125
Eric Laurentec376dc2021-04-08 20:41:22 +02009126 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9127 return BAD_VALUE;
9128 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009129
9130 if (sharedAudioStartMs < 0
9131 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009132 return BAD_VALUE;
9133 }
9134
Eric Laurent2407ce32021-04-26 14:56:03 +02009135 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9136 // As we cannot detect more than one wraparound, only accept values up current write position
9137 // after one wraparound
9138 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9139 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009140 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009141 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9142 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009143 // Bring the start frame position within the input buffer to match the documented
9144 // "best effort" behavior of the API.
9145 if (sharedOffset < 0) {
9146 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07009147 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009148 sharedAudioStartFrames =
9149 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009150 }
9151
Eric Laurentec376dc2021-04-08 20:41:22 +02009152 mSharedAudioPackageName = sharedAudioPackageName;
9153 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009154 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009155 } else {
9156 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009157 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009158 }
9159 return NO_ERROR;
9160}
9161
Andy Hung71742ab2023-07-07 13:47:37 -07009162void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009163 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9164 mSharedAudioStartFrames = -1;
9165 mSharedAudioPackageName = "";
9166}
9167
Andy Hung71742ab2023-07-07 13:47:37 -07009168ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009169{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009170 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009171 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009172 }
9173 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009174 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07009175 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009176 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009177 }
9178 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009179 MetadataUpdate change;
9180 change.recordMetadataUpdate = metadata.tracks;
9181 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009182}
9183
Eric Laurent81784c32012-11-19 14:55:58 -08009184// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07009185void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009186{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009187 track->terminate();
Andy Hung3ff4b552023-06-26 19:20:57 -07009188 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009189
Eric Laurent81784c32012-11-19 14:55:58 -08009190 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009191 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009192 removeTrack_l(track);
9193 }
9194}
9195
Andy Hung71742ab2023-07-07 13:47:37 -07009196void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009197{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009198 String8 result;
9199 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009200 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009201
Eric Laurent81784c32012-11-19 14:55:58 -08009202 mTracks.remove(track);
9203 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009204 if (track->isFastTrack()) {
9205 ALOG_ASSERT(!mFastTrackAvail);
9206 mFastTrackAvail = true;
9207 }
Eric Laurent81784c32012-11-19 14:55:58 -08009208}
9209
Andy Hung71742ab2023-07-07 13:47:37 -07009210void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009211{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009212 AudioStreamIn *input = mInput;
9213 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9214 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009215 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009216 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009217 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009218 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009219 }
Andy Hungbfa64962017-06-12 14:43:19 -07009220
9221 if (input != nullptr) {
9222 dprintf(fd, " Hal stream dump:\n");
9223 (void)input->stream->dump(fd);
9224 }
9225
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009226 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009227 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009228
Glenn Kasten2f90c512015-12-02 11:40:09 -08009229 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9230 // while we are dumping it. It may be inconsistent, but it won't mutate!
9231 // This is a large object so we place it on the heap.
9232 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009233 const std::unique_ptr<FastCaptureDumpState> copy =
9234 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009235 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009236}
9237
Andy Hung71742ab2023-07-07 13:47:37 -07009238void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009239{
Eric Laurent81784c32012-11-19 14:55:58 -08009240 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009241 size_t numtracks = mTracks.size();
9242 size_t numactive = mActiveTracks.size();
9243 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009244 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009245 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009246 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009247 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009248 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009249 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009250 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009251 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009252 if (track != 0) {
9253 bool active = mActiveTracks.indexOf(track) >= 0;
9254 if (active) {
9255 numactiveseen++;
9256 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009257 result.append(prefix);
9258 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009259 }
Eric Laurent81784c32012-11-19 14:55:58 -08009260 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009261 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009262 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009263 }
9264
Marco Nelissenb2208842014-02-07 14:00:50 -08009265 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009266 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009267 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009268 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009269 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009270 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009271 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009272 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009273 result.append(prefix);
9274 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009275 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009276 }
Eric Laurent81784c32012-11-19 14:55:58 -08009277
9278 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009279 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009280}
9281
Andy Hung71742ab2023-07-07 13:47:37 -07009282void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009283{
9284 Mutex::Autolock _l(mLock);
9285 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009286 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009287 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009288 track->setSilenced(silenced);
9289 }
9290 }
9291}
Andy Hung73c02e42015-03-29 01:13:58 -07009292
Andy Hung3ff4b552023-06-26 19:20:57 -07009293void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009294{
Andy Hung44f27182023-07-06 20:56:16 -07009295 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009296 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009297 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009298 const int32_t rear = recordThread->mRsmpInRear;
9299 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009300 if (mRecordTrack->startFrames() >= 0) {
9301 int32_t startFrames = mRecordTrack->startFrames();
9302 // Accept a recent wraparound of mRsmpInRear
9303 if (startFrames <= rear) {
9304 deltaFrames = rear - startFrames;
9305 } else {
9306 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009307 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009308 // start frame cannot be further in the past than start of resampling buffer
9309 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9310 deltaFrames = recordThread->mRsmpInFrames;
9311 }
9312 }
9313 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009314}
9315
Andy Hung3ff4b552023-06-26 19:20:57 -07009316void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009317 size_t *framesAvailable, bool *hasOverrun)
9318{
Andy Hung44f27182023-07-06 20:56:16 -07009319 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009320 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009321 const int32_t rear = recordThread->mRsmpInRear;
9322 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009323 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009324
9325 size_t framesIn;
9326 bool overrun = false;
9327 if (filled < 0) {
9328 // should not happen, but treat like a massive overrun and re-sync
9329 framesIn = 0;
9330 mRsmpInFront = rear;
9331 overrun = true;
9332 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9333 framesIn = (size_t) filled;
9334 } else {
9335 // client is not keeping up with server, but give it latest data
9336 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009337 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9338 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009339 overrun = true;
9340 }
9341 if (framesAvailable != NULL) {
9342 *framesAvailable = framesIn;
9343 }
9344 if (hasOverrun != NULL) {
9345 *hasOverrun = overrun;
9346 }
9347}
9348
Eric Laurent81784c32012-11-19 14:55:58 -08009349// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009350status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009351 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009352{
Andy Hung44f27182023-07-06 20:56:16 -07009353 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009354 if (threadBase == 0) {
9355 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009356 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009357 return NOT_ENOUGH_DATA;
9358 }
Andy Hung71742ab2023-07-07 13:47:37 -07009359 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009360 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009361 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009362 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009363 // FIXME should not be P2 (don't want to increase latency)
9364 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009365 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009366 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009367
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009368 front &= recordThread->mRsmpInFramesP2 - 1;
9369 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009370 if (part1 > (size_t) filled) {
9371 part1 = filled;
9372 }
9373 size_t ask = buffer->frameCount;
9374 ALOG_ASSERT(ask > 0);
9375 if (part1 > ask) {
9376 part1 = ask;
9377 }
9378 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009379 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009380 buffer->raw = NULL;
9381 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009382 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009383 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009384 }
9385
Andy Hung57446612015-04-19 23:56:46 -07009386 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009387 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009388 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009389 return NO_ERROR;
9390}
9391
9392// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009393void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009394 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009395{
Hongwei Wang95e37682019-04-12 11:13:36 -07009396 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009397 if (stepCount == 0) {
9398 return;
9399 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009400 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009401 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009402 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009403 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009404 buffer->frameCount = 0;
9405}
9406
Andy Hung71742ab2023-07-07 13:47:37 -07009407void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009408{
9409 Mutex::Autolock _l(mLock);
9410 checkBtNrec_l();
9411}
9412
Andy Hung71742ab2023-07-07 13:47:37 -07009413void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009414{
9415 // disable AEC and NS if the device is a BT SCO headset supporting those
9416 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009417 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung2cbc2722023-07-17 17:05:00 -07009418 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009419 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9420 for (size_t i = 0; i < mEffectChains.size(); i++) {
9421 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9422 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9423 }
9424 }
9425}
9426
Andy Hung97a893e2015-03-29 01:03:07 -07009427
Andy Hung71742ab2023-07-07 13:47:37 -07009428bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009429 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009430{
9431 bool reconfig = false;
9432
Eric Laurent10351942014-05-08 18:49:52 -07009433 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009434
Eric Laurent10351942014-05-08 18:49:52 -07009435 audio_format_t reqFormat = mFormat;
9436 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009437 // 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 +08009438 [[maybe_unused]] audio_channel_mask_t channelMask =
9439 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009440
9441 AudioParameter param = AudioParameter(keyValuePair);
9442 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009443
9444 // scope for AutoPark extends to end of method
9445 AutoPark<FastCapture> park(mFastCapture);
9446
Eric Laurent10351942014-05-08 18:49:52 -07009447 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9448 // channel count change can be requested. Do we mandate the first client defines the
9449 // HAL sampling rate and channel count or do we allow changes on the fly?
9450 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9451 samplingRate = value;
9452 reconfig = true;
9453 }
9454 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009455 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009456 status = BAD_VALUE;
9457 } else {
9458 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009459 reconfig = true;
9460 }
Eric Laurent10351942014-05-08 18:49:52 -07009461 }
9462 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9463 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009464 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009465 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009466 status = BAD_VALUE;
9467 } else {
9468 channelMask = mask;
9469 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009470 }
Eric Laurent10351942014-05-08 18:49:52 -07009471 }
9472 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9473 // do not accept frame count changes if tracks are open as the track buffer
9474 // size depends on frame count and correct behavior would not be guaranteed
9475 // if frame count is changed after track creation
9476 if (mActiveTracks.size() > 0) {
9477 status = INVALID_OPERATION;
9478 } else {
9479 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009480 }
Eric Laurent10351942014-05-08 18:49:52 -07009481 }
9482 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009483 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009484 }
9485 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9486 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009487 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009488 }
Glenn Kastene198c362013-08-13 09:13:36 -07009489
Eric Laurent10351942014-05-08 18:49:52 -07009490 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009491 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009492 if (status == INVALID_OPERATION) {
9493 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009494 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009495 }
9496 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009497 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009498 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9499 if (mInput->stream->getAudioProperties(&config) == OK &&
9500 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9501 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009502 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009503 status = NO_ERROR;
9504 }
Eric Laurent81784c32012-11-19 14:55:58 -08009505 }
Eric Laurent10351942014-05-08 18:49:52 -07009506 if (status == NO_ERROR) {
9507 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009508 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009509 }
9510 }
Eric Laurent81784c32012-11-19 14:55:58 -08009511 }
Eric Laurent10351942014-05-08 18:49:52 -07009512
Eric Laurent81784c32012-11-19 14:55:58 -08009513 return reconfig;
9514}
9515
Andy Hung71742ab2023-07-07 13:47:37 -07009516String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009517{
Eric Laurent81784c32012-11-19 14:55:58 -08009518 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009519 if (initCheck() == NO_ERROR) {
9520 String8 out_s8;
9521 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9522 return out_s8;
9523 }
Eric Laurent81784c32012-11-19 14:55:58 -08009524 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009525 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009526}
9527
Andy Hung71742ab2023-07-07 13:47:37 -07009528void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009529 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009530 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009531 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009532 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009533 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009534 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009535 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9536 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009537 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009538 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009539 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009540 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009541 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009542 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009543 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009544 break;
9545 }
Andy Hung2cbc2722023-07-17 17:05:00 -07009546 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009547}
9548
Andy Hung71742ab2023-07-07 13:47:37 -07009549void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009550{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009551 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9552 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009553 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009554 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9555 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009556 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9557 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009558 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009559 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009560 ALOGI("HAL format %#x is not linear pcm", mFormat);
9561 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009562 result = mInput->stream->getFrameSize(&mFrameSize);
9563 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009564 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9565 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009566 result = mInput->stream->getBufferSize(&mBufferSize);
9567 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009568 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009569 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9570 "mBufferSize=%zu, mFrameCount=%zu",
9571 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009572
Eric Laurentec376dc2021-04-08 20:41:22 +02009573 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9574 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009575 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009576
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009577 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9578 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009579
9580 audio_input_flags_t flags = mInput->flags;
9581 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9582 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung4d693a32023-07-19 12:47:35 -07009583 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009584 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9585 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9586 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9587 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9588 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9589 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009590}
9591
Andy Hung71742ab2023-07-07 13:47:37 -07009592uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009593{
9594 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009595 uint32_t result;
9596 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9597 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009598 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009599 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009600}
9601
Andy Hung71742ab2023-07-07 13:47:37 -07009602KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009603{
Glenn Kastend848eb42016-03-08 13:42:11 -08009604 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009605 Mutex::Autolock _l(mLock);
9606 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009607 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009608 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009609 if (ids.indexOfKey(sessionId) < 0) {
9610 ids.add(sessionId, true);
9611 }
9612 }
9613 return ids;
9614}
9615
Andy Hung71742ab2023-07-07 13:47:37 -07009616AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009617{
9618 Mutex::Autolock _l(mLock);
9619 AudioStreamIn *input = mInput;
9620 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009621 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009622 return input;
9623}
9624
9625// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07009626sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009627{
9628 if (mInput == NULL) {
9629 return NULL;
9630 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009631 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009632}
9633
Andy Hung71742ab2023-07-07 13:47:37 -07009634status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009635{
Eric Laurent81784c32012-11-19 14:55:58 -08009636 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009637 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009638 chain->setInBuffer(NULL);
9639 chain->setOutBuffer(NULL);
9640
9641 checkSuspendOnAddEffectChain_l(chain);
9642
Eric Laurent1b928682014-10-02 19:41:47 -07009643 // make sure enabled pre processing effects state is communicated to the HAL as we
9644 // just moved them to a new input stream.
9645 chain->syncHalEffectsState();
9646
Eric Laurent81784c32012-11-19 14:55:58 -08009647 mEffectChains.add(chain);
9648
9649 return NO_ERROR;
9650}
9651
Andy Hung71742ab2023-07-07 13:47:37 -07009652size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009653{
9654 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009655
9656 for (size_t i = 0; i < mEffectChains.size(); i++) {
9657 if (chain == mEffectChains[i]) {
9658 mEffectChains.removeAt(i);
9659 break;
9660 }
Eric Laurent81784c32012-11-19 14:55:58 -08009661 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009662 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009663}
9664
Andy Hung71742ab2023-07-07 13:47:37 -07009665status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009666 audio_patch_handle_t *handle)
9667{
9668 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009669
9670 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009671 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009672 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009673 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009674 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009675 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009676 }
9677
Eric Laurentd8365c52017-07-16 15:27:05 -07009678 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009679
9680 // store new source and send to effects
9681 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9682 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009683 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009684 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009685 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009686 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009687
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009688 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009689 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9690 status = hwDevice->createAudioPatch(patch->num_sources,
9691 patch->sources,
9692 patch->num_sinks,
9693 patch->sinks,
9694 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009695 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009696 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9697 patch->sinks[0].ext.mix.usecase.source,
9698 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009699 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009700 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009701
jiabinc52b1ff2019-10-31 17:20:42 -07009702 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009703 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009704 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009705 }
Eric Laurent296fb132015-05-01 11:38:42 -07009706
Andy Hungc2b11cb2020-04-22 09:04:01 -07009707 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009708 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009709 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009710 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009711 // also dispatch to active AudioRecords
9712 for (const auto &track : mActiveTracks) {
9713 track->logEndInterval();
9714 track->logBeginInterval(pathSourcesAsString);
9715 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009716 // Force meteadata update after a route change
9717 mActiveTracks.setHasChanged();
9718
Eric Laurent1c333e22014-05-20 10:48:17 -07009719 return status;
9720}
9721
Andy Hung71742ab2023-07-07 13:47:37 -07009722status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009723{
9724 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009725
jiabinc52b1ff2019-10-31 17:20:42 -07009726 mPatch = audio_patch{};
9727 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009728
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009729 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009730 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9731 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009732 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009733 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009734 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009735 // Force meteadata update after a route change
9736 mActiveTracks.setHasChanged();
9737
Eric Laurent1c333e22014-05-20 10:48:17 -07009738 return status;
9739}
9740
Andy Hung71742ab2023-07-07 13:47:37 -07009741void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009742{
wendy lin56aa82b2020-12-02 15:19:55 +08009743 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009744 mOutDevices = outDevices;
9745 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9746 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009747 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009748 }
9749}
9750
Andy Hung71742ab2023-07-07 13:47:37 -07009751int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009752{
9753 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009754 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009755 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009756 int32_t oldestFront = mRsmpInRear;
9757 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009758 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009759 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009760 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009761 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009762 if (filled > maxFilled) {
9763 oldestFront = front;
9764 maxFilled = filled;
9765 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009766 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009767 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009768 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9769 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009770 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009771}
9772
Andy Hung71742ab2023-07-07 13:47:37 -07009773void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009774{
9775 if (offset == 0) {
9776 return;
9777 }
9778 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009779 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009780 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung3ff4b552023-06-26 19:20:57 -07009781 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009782 }
9783}
9784
Andy Hung71742ab2023-07-07 13:47:37 -07009785void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009786{
9787 // This is the formula for calculating the temporary buffer size.
9788 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9789 // 1 full output buffer, regardless of the alignment of the available input.
9790 // The value is somewhat arbitrary, and could probably be even larger.
9791 // A larger value should allow more old data to be read after a track calls start(),
9792 // without increasing latency.
9793 //
9794 // Note this is independent of the maximum downsampling ratio permitted for capture.
9795 size_t minRsmpInFrames = mFrameCount * 7;
9796
9797 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9798 // capture history available to another client using the same session ID:
9799 // dimension the resampler input buffer accordingly.
9800
9801 // Get oldest client read position: getOldestFront_l() must be called before altering
9802 // mRsmpInRear, or mRsmpInFrames
9803 int32_t previousFront = getOldestFront_l();
9804 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9805 int32_t previousRear = mRsmpInRear;
9806 mRsmpInRear = 0;
9807
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009808 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung71742ab2023-07-07 13:47:37 -07009809 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009810 "resizeInputBuffer_l() called with invalid max shared history %d",
9811 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009812 if (maxSharedAudioHistoryMs != 0) {
9813 // resizeInputBuffer_l should never be called with a non zero shared history if the
9814 // buffer was not already allocated
9815 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9816 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9817 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9818 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009819 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009820 return;
9821 }
9822 mRsmpInFrames = rsmpInFrames;
9823 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009824 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009825 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9826 // initialized
9827 if (mRsmpInFrames < minRsmpInFrames) {
9828 mRsmpInFrames = minRsmpInFrames;
9829 }
9830 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9831
9832 // TODO optimize audio capture buffer sizes ...
9833 // Here we calculate the size of the sliding buffer used as a source
9834 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9835 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9836 // be better to have it derived from the pipe depth in the long term.
9837 // The current value is higher than necessary. However it should not add to latency.
9838
9839 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9840 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9841
9842 void *rsmpInBuffer;
9843 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9844 // if posix_memalign fails, will segv here.
9845 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9846
9847 // Copy audio history if any from old buffer before freeing it
9848 if (previousRear != 0) {
9849 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9850 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9851
9852 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9853 previousFront &= previousRsmpInFramesP2 - 1;
9854 size_t part1 = previousRsmpInFramesP2 - previousFront;
9855 if (part1 > (size_t) unread) {
9856 part1 = unread;
9857 }
9858 if (part1 != 0) {
9859 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9860 part1 * mFrameSize);
9861 mRsmpInRear = part1;
9862 part1 = unread - part1;
9863 if (part1 != 0) {
9864 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9865 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9866 mRsmpInRear += part1;
9867 }
9868 }
9869 // Update front for all clients according to new rear
9870 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9871 } else {
9872 mRsmpInRear = 0;
9873 }
9874 free(mRsmpInBuffer);
9875 mRsmpInBuffer = rsmpInBuffer;
9876}
9877
Andy Hung71742ab2023-07-07 13:47:37 -07009878void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009879{
9880 Mutex::Autolock _l(mLock);
9881 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009882 if (record->getSource()) {
9883 mSource = record->getSource();
9884 }
Eric Laurent83b88082014-06-20 18:31:16 -07009885}
9886
Andy Hung71742ab2023-07-07 13:47:37 -07009887void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009888{
9889 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009890 if (mSource == record->getSource()) {
9891 mSource = mInput;
9892 }
Eric Laurent83b88082014-06-20 18:31:16 -07009893 destroyTrack_l(record);
9894}
9895
Andy Hung71742ab2023-07-07 13:47:37 -07009896void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009897{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009898 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009899 config->role = AUDIO_PORT_ROLE_SINK;
9900 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9901 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009902 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9903 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9904 config->flags.input = mInput->flags;
9905 }
Eric Laurent83b88082014-06-20 18:31:16 -07009906}
Eric Laurent1c333e22014-05-20 10:48:17 -07009907
Eric Laurent6acd1d42017-01-04 14:23:29 -08009908// ----------------------------------------------------------------------------
9909// Mmap
9910// ----------------------------------------------------------------------------
9911
Andy Hung667dec42023-07-07 15:58:48 -07009912// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9913// MmapPlaybackThread or MmapCaptureThread instance.
9914class MmapThreadHandle : public MmapStreamInterface {
9915public:
9916 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9917 ~MmapThreadHandle() override;
9918
9919 // MmapStreamInterface virtuals
9920 status_t createMmapBuffer(int32_t minSizeFrames,
9921 struct audio_mmap_buffer_info* info) final;
9922 status_t getMmapPosition(struct audio_mmap_position* position) final;
9923 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9924 status_t start(const AudioClient& client,
9925 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9926 status_t stop(audio_port_handle_t handle) final;
9927 status_t standby() final;
9928 status_t reportData(const void* buffer, size_t frameCount) final;
9929private:
9930 const sp<IAfMmapThread> mThread;
9931};
9932
9933/* static */
9934sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9935 const sp<IAfMmapThread>& mmapThread) {
9936 return sp<MmapThreadHandle>::make(mmapThread);
9937}
9938
9939MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009940 : mThread(thread)
9941{
Phil Burk9fabbf82017-08-03 12:02:00 -07009942 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009943}
9944
Andy Hung667dec42023-07-07 15:58:48 -07009945// MmapStreamInterface could be directly implemented by MmapThread excepting this
9946// special handling on adapter dtor.
9947MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948{
Phil Burk9fabbf82017-08-03 12:02:00 -07009949 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009950}
9951
Andy Hung667dec42023-07-07 15:58:48 -07009952status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953 struct audio_mmap_buffer_info *info)
9954{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009955 return mThread->createMmapBuffer(minSizeFrames, info);
9956}
9957
Andy Hung667dec42023-07-07 15:58:48 -07009958status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009959{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009960 return mThread->getMmapPosition(position);
9961}
9962
Andy Hung667dec42023-07-07 15:58:48 -07009963status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009964 int64_t *timeNanos) {
9965 return mThread->getExternalPosition(position, timeNanos);
9966}
9967
Andy Hung667dec42023-07-07 15:58:48 -07009968status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009969 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009970{
jiabind1f1cb62020-03-24 11:57:57 -07009971 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009972}
9973
Andy Hung667dec42023-07-07 15:58:48 -07009974status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009975{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009976 return mThread->stop(handle);
9977}
9978
Andy Hung667dec42023-07-07 15:58:48 -07009979status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009980{
Eric Laurent18b57012017-02-13 16:23:52 -08009981 return mThread->standby();
9982}
9983
Andy Hung667dec42023-07-07 15:58:48 -07009984status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9985{
jiabinfc791ee2023-02-15 19:43:40 +00009986 return mThread->reportData(buffer, frameCount);
9987}
9988
Eric Laurent6acd1d42017-01-04 14:23:29 -08009989
Andy Hung71742ab2023-07-07 13:47:37 -07009990MmapThread::MmapThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07009991 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009992 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung2cbc2722023-07-17 17:05:00 -07009993 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009994 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009995 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009996 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009997 mActiveTracks(&this->mLocalLog),
9998 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9999 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010000{
Eric Laurent18b57012017-02-13 16:23:52 -080010001 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010002 readHalParameters_l();
10003}
10004
Andy Hung71742ab2023-07-07 13:47:37 -070010005void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010006{
10007 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10008}
10009
Andy Hung71742ab2023-07-07 13:47:37 -070010010void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010011{
Andy Hung3ff4b552023-06-26 19:20:57 -070010012 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -070010013 {
10014 Mutex::Autolock _l(mLock);
Andy Hung3ff4b552023-06-26 19:20:57 -070010015 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010016 activeTracks.add(t);
10017 }
10018 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010019 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010020 stop(t->portId());
10021 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010022 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010023 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010024 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010025 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010026 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010027 }
10028}
10029
10030
Andy Hung71742ab2023-07-07 13:47:37 -070010031void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010032 audio_stream_type_t streamType __unused,
10033 audio_session_t sessionId,
10034 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010035 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010036 audio_port_handle_t portId)
10037{
10038 mAttr = *attr;
10039 mSessionId = sessionId;
10040 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010041 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010042 mPortId = portId;
10043}
10044
Andy Hung71742ab2023-07-07 13:47:37 -070010045status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010046 struct audio_mmap_buffer_info *info)
10047{
10048 if (mHalStream == 0) {
10049 return NO_INIT;
10050 }
Eric Laurent18b57012017-02-13 16:23:52 -080010051 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010052 return mHalStream->createMmapBuffer(minSizeFrames, info);
10053}
10054
Andy Hung71742ab2023-07-07 13:47:37 -070010055status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010056{
10057 if (mHalStream == 0) {
10058 return NO_INIT;
10059 }
10060 return mHalStream->getMmapPosition(position);
10061}
10062
Andy Hung71742ab2023-07-07 13:47:37 -070010063status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010064{
Eric Laurentdda206a2022-07-08 17:28:35 +020010065 // The HAL must receive track metadata before starting the stream
10066 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010067 status_t ret = mHalStream->start();
10068 if (ret != NO_ERROR) {
10069 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10070 return ret;
10071 }
Andy Hungcf10d742020-04-28 15:38:24 -070010072 if (mStandby) {
10073 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010074 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010075 mStandby = false;
10076 }
Eric Laurent331679c2018-04-16 17:03:16 -070010077 return NO_ERROR;
10078}
10079
Andy Hung71742ab2023-07-07 13:47:37 -070010080status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010081 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010082 audio_port_handle_t *handle)
10083{
Eric Laurenta54f1282017-07-01 19:39:32 -070010084 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010085 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010086 if (mHalStream == 0) {
10087 return NO_INIT;
10088 }
10089
10090 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010091
Eric Laurentdda206a2022-07-08 17:28:35 +020010092 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010093 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010094 acquireWakeLock();
10095 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010096 }
10097
10098 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10099
10100 audio_io_handle_t io = mId;
Andy Hungc5106312023-07-19 16:56:19 -070010101 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010102 client.attributionSource);
10103
Eric Laurenta54f1282017-07-01 19:39:32 -070010104 if (isOutput()) {
10105 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10106 config.sample_rate = mSampleRate;
10107 config.channel_mask = mChannelMask;
10108 config.format = mFormat;
10109 audio_stream_type_t stream = streamType();
10110 audio_output_flags_t flags =
10111 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010112 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010113 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010114 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010115 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010116 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10117 mSessionId,
10118 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010119 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010120 &config,
10121 flags,
10122 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010123 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010124 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010125 &isSpatialized,
10126 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010127 ALOGD_IF(!secondaryOutputs.empty(),
10128 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010130 audio_config_base_t config;
10131 config.sample_rate = mSampleRate;
10132 config.channel_mask = mChannelMask;
10133 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010134 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010135 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010136 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010137 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010138 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010139 &config,
10140 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10141 &deviceId,
10142 &portId);
10143 }
10144 // APM should not chose a different input or output stream for the same set of attributes
10145 // and audo configuration
10146 if (ret != NO_ERROR || io != mId) {
10147 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10148 __FUNCTION__, ret, io, mId);
10149 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150 }
10151
10152 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010153 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010154 } else {
jiabincfc10a42022-06-15 19:26:01 +000010155 {
10156 // Add the track record before starting input so that the silent status for the
10157 // client can be cached.
10158 Mutex::Autolock _l(mLock);
10159 setClientSilencedState_l(portId, false /*silenced*/);
10160 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010161 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010162 }
10163
Eric Laurent331679c2018-04-16 17:03:16 -070010164 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 // abort if start is rejected by audio policy manager
10166 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010167 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010168 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010169 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010170 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010171 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010172 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010173 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174 }
Eric Laurent331679c2018-04-16 17:03:16 -070010175 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010176 } else {
10177 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 }
jiabincfc10a42022-06-15 19:26:01 +000010179 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010180 return PERMISSION_DENIED;
10181 }
10182
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010183 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung3ff4b552023-06-26 19:20:57 -070010184 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10185 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010186 mChannelMask, mSessionId, isOutput(),
10187 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010188 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +000010189 if (!isOutput()) {
10190 track->setSilenced_l(isClientSilenced_l(portId));
10191 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010192
Eric Laurent4eb58f12018-12-07 16:41:02 -080010193 if (isOutput()) {
10194 // force volume update when a new track is added
10195 mHalVolFloat = -1.0f;
10196 } else if (!track->isSilenced_l()) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010197 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -070010198 if (t->isSilenced_l()
10199 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010200 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -070010201 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010202 }
10203 }
10204
Eric Laurent6acd1d42017-01-04 14:23:29 -080010205 mActiveTracks.add(track);
Andy Hungbd72c542023-06-20 18:56:17 -070010206 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010208 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010209 chain->incTrackCnt();
10210 chain->incActiveTrackCnt();
10211 }
10212
Andy Hungc2b11cb2020-04-22 09:04:01 -070010213 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010214 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010215
10216 if (mActiveTracks.size() == 1) {
10217 ret = exitStandby_l();
10218 }
10219
Eric Laurent6acd1d42017-01-04 14:23:29 -080010220 broadcast_l();
10221
Eric Laurentdda206a2022-07-08 17:28:35 +020010222 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010223
Eric Laurentdda206a2022-07-08 17:28:35 +020010224 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010225}
10226
Andy Hung71742ab2023-07-07 13:47:37 -070010227status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010228{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229 ALOGV("%s handle %d", __FUNCTION__, handle);
10230
10231 if (mHalStream == 0) {
10232 return NO_INIT;
10233 }
10234
Eric Laurenta54f1282017-07-01 19:39:32 -070010235 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010236 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010237 return NO_ERROR;
10238 }
10239
Eric Laurent331679c2018-04-16 17:03:16 -070010240 Mutex::Autolock _l(mLock);
10241
Andy Hung3ff4b552023-06-26 19:20:57 -070010242 sp<IAfMmapTrack> track;
10243 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010244 if (handle == t->portId()) {
10245 track = t;
10246 break;
10247 }
10248 }
10249 if (track == 0) {
10250 return BAD_VALUE;
10251 }
10252
10253 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +000010254 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010255
Eric Laurent331679c2018-04-16 17:03:16 -070010256 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010257 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010258 AudioSystem::stopOutput(track->portId());
10259 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010260 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010261 AudioSystem::stopInput(track->portId());
10262 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263 }
Eric Laurent331679c2018-04-16 17:03:16 -070010264 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265
Andy Hungbd72c542023-06-20 18:56:17 -070010266 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010267 if (chain != 0) {
10268 chain->decActiveTrackCnt();
10269 chain->decTrackCnt();
10270 }
10271
Eric Laurentdda206a2022-07-08 17:28:35 +020010272 if (mActiveTracks.isEmpty()) {
10273 mHalStream->stop();
10274 }
10275
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276 broadcast_l();
10277
Eric Laurent6acd1d42017-01-04 14:23:29 -080010278 return NO_ERROR;
10279}
10280
Andy Hung71742ab2023-07-07 13:47:37 -070010281status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010282{
10283 ALOGV("%s", __FUNCTION__);
10284
10285 if (mHalStream == 0) {
10286 return NO_INIT;
10287 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010288 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010289 return INVALID_OPERATION;
10290 }
10291 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010292 if (!mStandby) {
10293 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010294 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010295 mStandby = true;
10296 }
Eric Laurent18b57012017-02-13 16:23:52 -080010297 releaseWakeLock();
10298 return NO_ERROR;
10299}
10300
Andy Hung71742ab2023-07-07 13:47:37 -070010301status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010302 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10303 return INVALID_OPERATION;
10304}
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305
Andy Hung71742ab2023-07-07 13:47:37 -070010306void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307{
10308 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10309 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10310 mFormat = mHALFormat;
10311 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10312 result = mHalStream->getFrameSize(&mFrameSize);
10313 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010314 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10315 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 result = mHalStream->getBufferSize(&mBufferSize);
10317 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10318 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010319
Andy Hungcf10d742020-04-28 15:38:24 -070010320 // TODO: make a readHalParameters call?
10321 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010322 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung4d693a32023-07-19 12:47:35 -070010323 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010324 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10325 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10326 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10327 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10328 /*
10329 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10330 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10331 (int32_t)mHapticChannelMask)
10332 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10333 (int32_t)mHapticChannelCount)
10334 */
10335 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung4d693a32023-07-19 12:47:35 -070010336 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010337 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10338 (int32_t)mFrameCount) // sic - added HAL
10339 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340}
10341
Andy Hung71742ab2023-07-07 13:47:37 -070010342bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010343{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010344 checkSilentMode_l();
10345
10346 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10347
10348 while (!exitPending())
10349 {
Andy Hungbd72c542023-06-20 18:56:17 -070010350 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010351
Andy Hung13850be2019-03-14 11:33:09 -070010352 { // under Thread lock
10353 Mutex::Autolock _l(mLock);
10354
Eric Laurent6acd1d42017-01-04 14:23:29 -080010355 if (mSignalPending) {
10356 // A signal was raised while we were unlocked
10357 mSignalPending = false;
10358 } else {
10359 if (mConfigEvents.isEmpty()) {
10360 // we're about to wait, flush the binder command buffer
10361 IPCThreadState::self()->flushCommands();
10362
10363 if (exitPending()) {
10364 break;
10365 }
10366
Eric Laurent6acd1d42017-01-04 14:23:29 -080010367 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010368 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010370 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010371
10372 checkSilentMode_l();
10373
10374 continue;
10375 }
10376 }
10377
10378 processConfigEvents_l();
10379
10380 processVolume_l();
10381
10382 checkInvalidTracks_l();
10383
10384 mActiveTracks.updatePowerState(this);
10385
Kevin Rocard069c2712018-03-29 19:09:14 -070010386 updateMetadata_l();
10387
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010389 } // release Thread lock
10390
Eric Laurent6acd1d42017-01-04 14:23:29 -080010391 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010392 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010393 }
Andy Hung13850be2019-03-14 11:33:09 -070010394
10395 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396 unlockEffectChains(effectChains);
10397 // Effect chains will be actually deleted here if they were removed from
10398 // mEffectChains list during mixing or effects processing
10399 }
10400
10401 threadLoop_exit();
10402
10403 if (!mStandby) {
10404 threadLoop_standby();
10405 mStandby = true;
10406 }
10407
Eric Laurent6acd1d42017-01-04 14:23:29 -080010408 ALOGV("Thread %p type %d exiting", this, mType);
10409 return false;
10410}
10411
10412// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010413bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414 status_t& status)
10415{
10416 AudioParameter param = AudioParameter(keyValuePair);
10417 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010418 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010419 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010420 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010422 if (sendToHal) {
10423 status = mHalStream->setParameters(keyValuePair);
10424 } else {
10425 status = NO_ERROR;
10426 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010427
10428 return false;
10429}
10430
Andy Hung71742ab2023-07-07 13:47:37 -070010431String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010432{
10433 Mutex::Autolock _l(mLock);
10434 String8 out_s8;
10435 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10436 return out_s8;
10437 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010438 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439}
10440
Andy Hung71742ab2023-07-07 13:47:37 -070010441void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010442 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010443 sp<AudioIoDescriptor> desc;
10444 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010445 switch (event) {
10446 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010447 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010449 isInput = true;
10450 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010452 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010453 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010454 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10455 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457 case AUDIO_INPUT_CLOSED:
10458 case AUDIO_OUTPUT_CLOSED:
10459 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010460 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461 break;
10462 }
Andy Hung2cbc2722023-07-17 17:05:00 -070010463 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464}
10465
Andy Hung71742ab2023-07-07 13:47:37 -070010466status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010467 audio_patch_handle_t *handle)
Andy Hung71ba4b32022-10-06 12:09:49 -070010468NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469{
10470 status_t status = NO_ERROR;
10471
10472 // store new device and send to effects
10473 audio_devices_t type = AUDIO_DEVICE_NONE;
10474 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010475 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10476 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10477 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010478 if (isOutput()) {
10479 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010480 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10481 && !mAudioHwDev->supportsAudioPatches(),
10482 "Enumerated device type(%#x) must not be used "
10483 "as it does not support audio patches",
10484 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010485 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010486 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10487 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010488 }
10489 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010490 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 } else {
10492 type = patch->sources[0].ext.device.type;
10493 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010494 numDevices = mPatch.num_sources;
10495 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010496 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497 }
10498
10499 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010500 if (isOutput()) {
10501 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10502 } else {
10503 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10504 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010505 }
10506
jiabinc52b1ff2019-10-31 17:20:42 -070010507 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010508 // store new source and send to effects
10509 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10510 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10511 for (size_t i = 0; i < mEffectChains.size(); i++) {
10512 mEffectChains[i]->setAudioSource_l(mAudioSource);
10513 }
10514 }
10515 }
10516
10517 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010518 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10519 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010520 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010521 audio_port_config port;
10522 std::optional<audio_source_t> source;
10523 if (isOutput()) {
10524 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010525 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010526 port = patch->sources[0];
10527 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010528 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010529 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010530 *handle = AUDIO_PATCH_HANDLE_NONE;
10531 }
10532
jiabinc52b1ff2019-10-31 17:20:42 -070010533 if (numDevices == 0 || mDeviceId != deviceId) {
10534 if (isOutput()) {
10535 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10536 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010537 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010538 } else {
10539 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10540 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10541 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010542 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010543 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010544 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010545 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010546 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547 }
jiabinc52b1ff2019-10-31 17:20:42 -070010548 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010549 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010550 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010551 // Force meteadata update after a route change
10552 mActiveTracks.setHasChanged();
10553
Eric Laurent6acd1d42017-01-04 14:23:29 -080010554 return status;
10555}
10556
Andy Hung71742ab2023-07-07 13:47:37 -070010557status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558{
10559 status_t status = NO_ERROR;
10560
jiabinc52b1ff2019-10-31 17:20:42 -070010561 mPatch = audio_patch{};
10562 mOutDeviceTypeAddrs.clear();
10563 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564
10565 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10566 supportsAudioPatches : false;
10567
10568 if (supportsAudioPatches) {
10569 status = mHalDevice->releaseAudioPatch(handle);
10570 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010571 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010573 // Force meteadata update after a route change
10574 mActiveTracks.setHasChanged();
10575
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576 return status;
10577}
10578
Andy Hung71742ab2023-07-07 13:47:37 -070010579void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010580{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010581 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 if (isOutput()) {
10583 config->role = AUDIO_PORT_ROLE_SOURCE;
10584 config->ext.mix.hw_module = mAudioHwDev->handle();
10585 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10586 } else {
10587 config->role = AUDIO_PORT_ROLE_SINK;
10588 config->ext.mix.hw_module = mAudioHwDev->handle();
10589 config->ext.mix.usecase.source = mAudioSource;
10590 }
10591}
10592
Andy Hung71742ab2023-07-07 13:47:37 -070010593status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594{
10595 audio_session_t session = chain->sessionId();
10596
10597 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10598 // Attach all tracks with same session ID to this chain.
10599 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010600 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010601 if (session == track->sessionId()) {
10602 chain->incTrackCnt();
10603 chain->incActiveTrackCnt();
10604 }
10605 }
10606
10607 chain->setThread(this);
10608 chain->setInBuffer(nullptr);
10609 chain->setOutBuffer(nullptr);
10610 chain->syncHalEffectsState();
10611
10612 mEffectChains.add(chain);
10613 checkSuspendOnAddEffectChain_l(chain);
10614 return NO_ERROR;
10615}
10616
Andy Hung71742ab2023-07-07 13:47:37 -070010617size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010618{
10619 audio_session_t session = chain->sessionId();
10620
10621 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10622
10623 for (size_t i = 0; i < mEffectChains.size(); i++) {
10624 if (chain == mEffectChains[i]) {
10625 mEffectChains.removeAt(i);
10626 // detach all active tracks from the chain
10627 // detach all tracks with same session ID from this chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010628 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629 if (session == track->sessionId()) {
10630 chain->decActiveTrackCnt();
10631 chain->decTrackCnt();
10632 }
10633 }
10634 break;
10635 }
10636 }
10637 return mEffectChains.size();
10638}
10639
Andy Hung71742ab2023-07-07 13:47:37 -070010640void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010641{
10642 mHalStream->standby();
10643}
10644
Andy Hung71742ab2023-07-07 13:47:37 -070010645void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010646{
Phil Burk7dce7282017-09-27 13:51:41 -070010647 // Do not call callback->onTearDown() because it is redundant for thread exit
10648 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649}
10650
Andy Hung71742ab2023-07-07 13:47:37 -070010651status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652{
10653 return BAD_VALUE;
10654}
10655
Andy Hung71742ab2023-07-07 13:47:37 -070010656bool MmapThread::isValidSyncEvent(
10657 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010658{
10659 return false;
10660}
10661
Andy Hung71742ab2023-07-07 13:47:37 -070010662status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010663 const effect_descriptor_t *desc, audio_session_t sessionId)
10664{
10665 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010666 if (audio_is_global_session(sessionId)) {
10667 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010668 desc->name, mThreadName);
10669 return BAD_VALUE;
10670 }
10671
10672 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10673 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10674 desc->name);
10675 return BAD_VALUE;
10676 }
10677 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010678 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10679 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010680 return BAD_VALUE;
10681 }
10682
10683 // Only allow effects without processing load or latency
10684 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10685 return BAD_VALUE;
10686 }
10687
Andy Hungbd72c542023-06-20 18:56:17 -070010688 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010689 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10690 return BAD_VALUE;
10691 }
10692
Eric Laurent6acd1d42017-01-04 14:23:29 -080010693 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010694}
10695
Andy Hung71742ab2023-07-07 13:47:37 -070010696void MmapThread::checkInvalidTracks_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010697NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010698{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010699 sp<MmapStreamCallback> callback;
Andy Hung3ff4b552023-06-26 19:20:57 -070010700 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010701 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010702 callback = mCallback.promote();
10703 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10704 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010705 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010707 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708 }
10709 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010710 if (callback != 0) {
10711 mLock.unlock();
10712 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10713 mLock.lock();
10714 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010715}
10716
Andy Hung71742ab2023-07-07 13:47:37 -070010717void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010718{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10720 mAttr.content_type, mAttr.usage, mAttr.source);
10721 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010722 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010723 dprintf(fd, " No active clients\n");
10724 }
10725}
10726
Andy Hung71742ab2023-07-07 13:47:37 -070010727void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010728{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010729 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010730 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010731 dprintf(fd, " %zu Tracks\n", numtracks);
10732 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010733 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010734 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010735 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010737 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010738 result.append(prefix);
10739 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740 }
10741 } else {
10742 dprintf(fd, "\n");
10743 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010744 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745}
10746
Andy Hung71742ab2023-07-07 13:47:37 -070010747/* static */
10748sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010749 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010750 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010751 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010752}
10753
10754MmapPlaybackThread::MmapPlaybackThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010755 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010756 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010757 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010758 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010759 mStreamVolume(1.0),
10760 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010761 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010762{
10763 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10764 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung2cbc2722023-07-17 17:05:00 -070010765 mMasterVolume = afThreadCallback->masterVolume_l();
10766 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010767 if (mAudioHwDev) {
10768 if (mAudioHwDev->canSetMasterVolume()) {
10769 mMasterVolume = 1.0;
10770 }
10771
10772 if (mAudioHwDev->canSetMasterMute()) {
10773 mMasterMute = false;
10774 }
10775 }
10776}
10777
Andy Hung71742ab2023-07-07 13:47:37 -070010778void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779 audio_stream_type_t streamType,
10780 audio_session_t sessionId,
10781 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010782 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010783 audio_port_handle_t portId)
10784{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010785 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010786 mStreamType = streamType;
10787}
10788
Andy Hung71742ab2023-07-07 13:47:37 -070010789AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790{
10791 Mutex::Autolock _l(mLock);
10792 AudioStreamOut *output = mOutput;
10793 mOutput = NULL;
10794 return output;
10795}
10796
Andy Hung71742ab2023-07-07 13:47:37 -070010797void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798{
10799 Mutex::Autolock _l(mLock);
10800 // Don't apply master volume in SW if our HAL can do it for us.
10801 if (mAudioHwDev &&
10802 mAudioHwDev->canSetMasterVolume()) {
10803 mMasterVolume = 1.0;
10804 } else {
10805 mMasterVolume = value;
10806 }
10807}
10808
Andy Hung71742ab2023-07-07 13:47:37 -070010809void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010810{
10811 Mutex::Autolock _l(mLock);
10812 // Don't apply master mute in SW if our HAL can do it for us.
10813 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10814 mMasterMute = false;
10815 } else {
10816 mMasterMute = muted;
10817 }
10818}
10819
Andy Hung71742ab2023-07-07 13:47:37 -070010820void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010821{
10822 Mutex::Autolock _l(mLock);
10823 if (stream == mStreamType) {
10824 mStreamVolume = value;
10825 broadcast_l();
10826 }
10827}
10828
Andy Hung71742ab2023-07-07 13:47:37 -070010829float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010830{
10831 Mutex::Autolock _l(mLock);
10832 if (stream == mStreamType) {
10833 return mStreamVolume;
10834 }
10835 return 0.0f;
10836}
10837
Andy Hung71742ab2023-07-07 13:47:37 -070010838void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010839{
10840 Mutex::Autolock _l(mLock);
10841 if (stream == mStreamType) {
10842 mStreamMute= muted;
10843 broadcast_l();
10844 }
10845}
10846
Andy Hung71742ab2023-07-07 13:47:37 -070010847void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010848{
10849 Mutex::Autolock _l(mLock);
10850 if (streamType == mStreamType) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010851 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010852 track->invalidate();
10853 }
10854 broadcast_l();
10855 }
10856}
10857
Andy Hung71742ab2023-07-07 13:47:37 -070010858void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010859{
10860 Mutex::Autolock _l(mLock);
10861 bool trackMatch = false;
Andy Hung3ff4b552023-06-26 19:20:57 -070010862 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010863 if (portIds.find(track->portId()) != portIds.end()) {
10864 track->invalidate();
10865 trackMatch = true;
10866 portIds.erase(track->portId());
10867 }
10868 if (portIds.empty()) {
10869 break;
10870 }
10871 }
10872 if (trackMatch) {
10873 broadcast_l();
10874 }
10875}
10876
Andy Hung71742ab2023-07-07 13:47:37 -070010877void MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010878NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010879{
10880 float volume;
10881
10882 if (mMasterMute || mStreamMute) {
10883 volume = 0;
10884 } else {
10885 volume = mMasterVolume * mStreamVolume;
10886 }
10887
10888 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010889
10890 // Convert volumes from float to 8.24
10891 uint32_t vol = (uint32_t)(volume * (1 << 24));
10892
10893 // Delegate volume control to effect in track effect chain if needed
10894 // only one effect chain can be present on DirectOutputThread, so if
10895 // there is one, the track is connected to it
10896 if (!mEffectChains.isEmpty()) {
10897 mEffectChains[0]->setVolume_l(&vol, &vol);
10898 volume = (float)vol / (1 << 24);
10899 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010900 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010901 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10902 mHalVolFloat = volume; // HW volume control worked, so update value.
10903 mNoCallbackWarningCount = 0;
10904 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010905 sp<MmapStreamCallback> callback = mCallback.promote();
10906 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010907 mHalVolFloat = volume; // SW volume control worked, so update value.
10908 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010909 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010910 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010911 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010913 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10914 ALOGW("Could not set MMAP stream volume: no volume callback!");
10915 mNoCallbackWarningCount++;
10916 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010917 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010918 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010919 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010920 track->setMetadataHasChanged();
Andy Hung2cbc2722023-07-17 17:05:00 -070010921 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010922 /*muteState=*/{mMasterMute,
10923 mStreamVolume == 0.f,
10924 mStreamMute,
10925 // TODO(b/241533526): adjust logic to include mute from AppOps
10926 false /*muteFromPlaybackRestricted*/,
10927 false /*muteFromClientVolume*/,
10928 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010929 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010930 }
10931}
10932
Andy Hung71742ab2023-07-07 13:47:37 -070010933ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010934{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010935 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010936 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010937 }
10938 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070010939 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010940 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010941 playback_track_metadata_v7_t trackMetadata;
10942 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010943 .usage = track->attributes().usage,
10944 .content_type = track->attributes().content_type,
10945 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010946 };
10947 trackMetadata.channel_mask = track->channelMask(),
10948 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10949 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010950 }
10951 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010952
10953 MetadataUpdate change;
10954 change.playbackMetadataUpdate = metadata.tracks;
10955 return change;
10956};
Kevin Rocard069c2712018-03-29 19:09:14 -070010957
Andy Hung71742ab2023-07-07 13:47:37 -070010958void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959{
10960 if (!mMasterMute) {
10961 char value[PROPERTY_VALUE_MAX];
10962 if (property_get("ro.audio.silent", value, "0") > 0) {
10963 char *endptr;
10964 unsigned long ul = strtoul(value, &endptr, 0);
10965 if (*endptr == '\0' && ul != 0) {
10966 ALOGD("Silence is golden");
10967 // The setprop command will not allow a property to be changed after
10968 // the first time it is set, so we don't have to worry about un-muting.
10969 setMasterMute_l(true);
10970 }
10971 }
10972 }
10973}
10974
Andy Hung71742ab2023-07-07 13:47:37 -070010975void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010976{
10977 MmapThread::toAudioPortConfig(config);
10978 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10979 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10980 config->flags.output = mOutput->flags;
10981 }
10982}
10983
Andy Hung71742ab2023-07-07 13:47:37 -070010984status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung4989d312023-06-29 21:19:25 -070010985 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010986{
10987 if (mOutput == nullptr) {
10988 return NO_INIT;
10989 }
10990 struct timespec timestamp;
10991 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10992 if (status == NO_ERROR) {
10993 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10994 }
10995 return status;
10996}
10997
Andy Hung71742ab2023-07-07 13:47:37 -070010998status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010999 // Send to MelProcessor for sound dose measurement.
11000 auto processor = mMelProcessor.load();
11001 if (processor) {
11002 processor->process(buffer, frameCount * mFrameSize);
11003 }
11004
jiabinfc791ee2023-02-15 19:43:40 +000011005 return NO_ERROR;
11006}
11007
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011008// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070011009void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011010 const sp<audio_utils::MelProcessor>& processor)
11011{
11012 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011013 mMelProcessor.store(processor);
11014 if (processor) {
11015 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011016 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011017
11018 // no need to update output format for MMapPlaybackThread since it is
11019 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011020}
11021
11022// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070011023void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011024{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011025 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11026 auto melProcessor = mMelProcessor.load();
11027 if (melProcessor != nullptr) {
11028 melProcessor->pause();
11029 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011030}
11031
Andy Hung71742ab2023-07-07 13:47:37 -070011032void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011034 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011035
Glenn Kastend3bb6452016-12-05 18:14:37 -080011036 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
11037 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011038 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11039}
11040
Andy Hung71742ab2023-07-07 13:47:37 -070011041/* static */
11042sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070011043 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070011044 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011045 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011046}
11047
11048MmapCaptureThread::MmapCaptureThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011049 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011050 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011051 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011052 mInput(input)
11053{
11054 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11055 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11056}
11057
Andy Hung71742ab2023-07-07 13:47:37 -070011058status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011059{
Phil Burkf054fc32018-12-06 09:45:59 -080011060 {
11061 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011062 if (mInput != nullptr && mInput->stream != nullptr) {
11063 mInput->stream->setGain(1.0f);
11064 }
11065 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011066 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011067}
11068
Andy Hung71742ab2023-07-07 13:47:37 -070011069AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011070{
11071 Mutex::Autolock _l(mLock);
11072 AudioStreamIn *input = mInput;
11073 mInput = NULL;
11074 return input;
11075}
Kevin Rocard069c2712018-03-29 19:09:14 -070011076
Andy Hung71742ab2023-07-07 13:47:37 -070011077void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011078{
11079 bool changed = false;
11080 bool silenced = false;
11081
11082 sp<MmapStreamCallback> callback = mCallback.promote();
11083 if (callback == 0) {
11084 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11085 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11086 mNoCallbackWarningCount++;
11087 }
11088 }
11089
11090 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11091 // track is silenced and unmute otherwise
11092 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11093 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11094 changed = true;
11095 silenced = mActiveTracks[i]->isSilenced_l();
11096 }
11097 }
11098
11099 if (changed) {
11100 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11101 }
11102}
11103
Andy Hung71742ab2023-07-07 13:47:37 -070011104ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011105{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011106 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011107 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011108 }
11109 StreamInHalInterface::SinkMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070011110 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011111 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011112 record_track_metadata_v7_t trackMetadata;
11113 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011114 .source = track->attributes().source,
11115 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011116 };
11117 trackMetadata.channel_mask = track->channelMask(),
11118 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11119 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011120 }
11121 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011122 MetadataUpdate change;
11123 change.recordMetadataUpdate = metadata.tracks;
11124 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011125}
11126
Andy Hung71742ab2023-07-07 13:47:37 -070011127void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011128{
11129 Mutex::Autolock _l(mLock);
11130 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011131 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011132 mActiveTracks[i]->setSilenced_l(silenced);
11133 broadcast_l();
11134 }
11135 }
jiabincfc10a42022-06-15 19:26:01 +000011136 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011137}
11138
Andy Hung71742ab2023-07-07 13:47:37 -070011139void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011140{
11141 MmapThread::toAudioPortConfig(config);
11142 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11143 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11144 config->flags.input = mInput->flags;
11145 }
11146}
11147
Andy Hung71742ab2023-07-07 13:47:37 -070011148status_t MmapCaptureThread::getExternalPosition(
Andy Hung4989d312023-06-29 21:19:25 -070011149 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011150{
11151 if (mInput == nullptr) {
11152 return NO_INIT;
11153 }
11154 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11155}
11156
jiabinc658e452022-10-21 20:52:21 +000011157// ----------------------------------------------------------------------------
11158
Andy Hung71742ab2023-07-07 13:47:37 -070011159/* static */
11160sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011161 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -070011162 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011163 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011164}
11165
Andy Hung2cbc2722023-07-17 17:05:00 -070011166BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011167 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011168 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011169
Andy Hung71742ab2023-07-07 13:47:37 -070011170PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -070011171 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011172 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11173 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011174 float volumeLeft = 1.0f;
11175 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011176 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11177 const int trackId = mActiveTracks[0]->id();
11178 mAudioMixer->setParameter(
11179 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11180 mAudioMixer->setParameter(
11181 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11182 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011183 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011184 mIsBitPerfect = true;
11185 } else {
11186 mIsBitPerfect = false;
11187 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11188 // active.
11189 for (const auto& track : mActiveTracks) {
11190 const int trackId = track->id();
11191 mAudioMixer->setParameter(
11192 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11193 }
11194 }
jiabin76d94692022-12-15 21:51:21 +000011195 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11196 mVolumeLeft = volumeLeft;
11197 mVolumeRight = volumeRight;
11198 setVolumeForOutput_l(volumeLeft, volumeRight);
11199 }
jiabinc658e452022-10-21 20:52:21 +000011200 return result;
11201}
11202
Andy Hung71742ab2023-07-07 13:47:37 -070011203void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011204 MixerThread::threadLoop_mix();
11205 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11206}
11207
Glenn Kasten63238ef2015-03-02 15:50:29 -080011208} // namespace android