blob: 9841f7d9feb73c70eaa1343dbe2abc5125b41da2 [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 Hung409572b2023-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 Hung409572b2023-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 Hung409572b2023-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 Hung409572b2023-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 Hung409572b2023-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 Hung409572b2023-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 Hung409572b2023-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 Hung4b17e882023-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 Hung409572b2023-07-19 12:47:35 -0700127// Keep in sync with java definition in media/java/android/media/AudioRecord.java
128static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// retry counts for buffer fill timeout
131// 50 * ~20msecs = 1 second
132static const int8_t kMaxTrackRetries = 50;
133static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// allow less retry attempts on direct output thread.
136// direct outputs can be a scarce resource in audio hardware and should
137// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700138// Notes:
139// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
140// in case the data write is bursty for the AudioTrack. The application
141// should endeavor to write at least once every kMaxTrackRetriesDirectMs
142// to prevent an underrun situation. If the data is bursty, then
143// the application can also throttle the data sent to be even.
144// 2) For compressed audio data, any data present in the AudioTrack buffer
145// will be sent and reset the retry count. This delivers data as
146// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
147// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
148// of data to be available, then any remaining data is delivered.
149// This is required to ensure the last bit of data is delivered before underrun.
150//
151// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
152// or the size of the HAL period for proportional / linear PCM tracks.
153static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800154
155// don't warn about blocked writes or record buffer overflows more often than this
156static const nsecs_t kWarningThrottleNs = seconds(5);
157
158// RecordThread loop sleep time upon application overrun or audio HAL read error
159static const int kRecordThreadSleepUs = 5000;
160
Eric Laurent10351942014-05-08 18:49:52 -0700161// maximum time to wait in sendConfigEvent_l() for a status to be received
162static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// minimum sleep time for the mixer thread loop when tracks are active but in underrun
165static const uint32_t kMinThreadSleepTimeUs = 5000;
166// maximum divider applied to the active sleep time in the mixer thread loop
167static const uint32_t kMaxThreadSleepTimeShift = 2;
168
Andy Hung09a50072014-02-27 14:30:47 -0800169// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700170// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800171static const uint32_t kMinNormalSinkBufferSizeMs = 20;
172// maximum normal sink buffer size
173static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700175// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
176// FIXME This should be based on experimentally observed scheduling jitter
177static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
178
Eric Laurent972a1732013-09-04 09:42:59 -0700179// Offloaded output thread standby delay: allows track transition without going to standby
180static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
181
Eric Laurent51716182016-02-29 18:00:56 -0800182// Direct output thread minimum sleep time in idle or active(underrun) state
183static const nsecs_t kDirectMinSleepTimeUs = 10000;
184
Brian Lindahl65e90012022-07-27 18:01:07 +0200185// Minimum amount of time between checking to see if the timestamp is advancing
186// for underrun detection. If we check too frequently, we may not detect a
187// timestamp update and will falsely detect underrun.
188static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
189
Glenn Kasten1b291842016-07-18 14:55:21 -0700190// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
191// balance between power consumption and latency, and allows threads to be scheduled reliably
192// by the CFS scheduler.
193// FIXME Express other hardcoded references to 20ms with references to this constant and move
194// it appropriately.
195#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800196
Eric Laurent81784c32012-11-19 14:55:58 -0800197// Whether to use fast mixer
198static const enum {
199 FastMixer_Never, // never initialize or use: for debugging only
200 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
201 // normal mixer multiplier is 1
202 FastMixer_Static, // initialize if needed, then use all the time if initialized,
203 // multiplier is calculated based on min & max normal mixer buffer size
204 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 // FIXME for FastMixer_Dynamic:
207 // Supporting this option will require fixing HALs that can't handle large writes.
208 // For example, one HAL implementation returns an error from a large write,
209 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
210 // We could either fix the HAL implementations, or provide a wrapper that breaks
211 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
212} kUseFastMixer = FastMixer_Static;
213
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700214// Whether to use fast capture
215static const enum {
216 FastCapture_Never, // never initialize or use: for debugging only
217 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
218 FastCapture_Static, // initialize if needed, then use all the time if initialized
219} kUseFastCapture = FastCapture_Static;
220
Eric Laurent81784c32012-11-19 14:55:58 -0800221// Priorities for requestPriority
222static const int kPriorityAudioApp = 2;
223static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700224static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800225
Glenn Kastenea38ee72016-04-18 11:08:01 -0700226// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
227// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
228// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700229
230// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800231static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800232
Glenn Kasten03490092014-05-27 12:30:54 -0700233// The minimum and maximum allowed values
234static const int kFastTrackMultiplierMin = 1;
235static const int kFastTrackMultiplierMax = 2;
236
237// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
238static int sFastTrackMultiplier = kFastTrackMultiplier;
239
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700240// See Thread::readOnlyHeap().
241// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
242// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
243// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700244static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700245
Andy Hung409572b2023-07-19 12:47:35 -0700246static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hungd58c4732023-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 Hungd21a2ab2023-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 Hung409572b2023-07-19 12:47:35 -0700315// formatToString() needs to be exact for MediaMetrics purposes.
316// Do not use media/TypeConverter.h toString().
317/* static */
318std::string IAfThreadBase::formatToString(audio_format_t format) {
319 std::string result;
320 FormatConverter::toString(format, result);
321 return result;
322}
323
Andy Hungb68f5eb2019-12-03 16:49:17 -0800324// TODO: move all toString helpers to audio.h
325// under #ifdef __cplusplus #endif
326static std::string patchSinksToString(const struct audio_patch *patch)
327{
328 std::stringstream ss;
329 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700330 if (i > 0) {
331 ss << "|";
332 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800333 ss << "(" << toString(patch->sinks[i].ext.device.type)
334 << ", " << patch->sinks[i].ext.device.address << ")";
335 }
336 return ss.str();
337}
338
339static std::string patchSourcesToString(const struct audio_patch *patch)
340{
341 std::stringstream ss;
342 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700343 if (i > 0) {
344 ss << "|";
345 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800346 ss << "(" << toString(patch->sources[i].ext.device.type)
347 << ", " << patch->sources[i].ext.device.address << ")";
348 }
349 return ss.str();
350}
351
Andy Hung4bd53e72022-11-17 17:21:45 -0800352static std::string toString(audio_latency_mode_t mode) {
353 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000354 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
355 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800356}
357
358// Could be made a template, but other toString overloads for std::vector are confused.
359static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
360 std::string s("{ ");
361 for (const auto& e : elements) {
362 s.append(toString(e));
363 s.append(" ");
364 }
365 s.append("}");
366 return s;
367}
368
Glenn Kasten03490092014-05-27 12:30:54 -0700369static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
370
371static void sFastTrackMultiplierInit()
372{
373 char value[PROPERTY_VALUE_MAX];
374 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
375 char *endptr;
376 unsigned long ul = strtoul(value, &endptr, 0);
377 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
378 sFastTrackMultiplier = (int) ul;
379 }
380 }
381}
382
383// ----------------------------------------------------------------------------
384
Eric Laurent81784c32012-11-19 14:55:58 -0800385#ifdef ADD_BATTERY_DATA
386// To collect the amplifier usage
387static void addBatteryData(uint32_t params) {
388 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
389 if (service == NULL) {
390 // it already logged
391 return;
392 }
393
394 service->addBatteryData(params);
395}
396#endif
397
Andy Hung3f0c9022016-01-15 17:49:46 -0800398// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
399struct {
400 // call when you acquire a partial wakelock
401 void acquire(const sp<IBinder> &wakeLockToken) {
402 pthread_mutex_lock(&mLock);
403 if (wakeLockToken.get() == nullptr) {
404 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
405 } else {
406 if (mCount == 0) {
407 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
408 }
409 ++mCount;
410 }
411 pthread_mutex_unlock(&mLock);
412 }
413
414 // call when you release a partial wakelock.
415 void release(const sp<IBinder> &wakeLockToken) {
416 if (wakeLockToken.get() == nullptr) {
417 return;
418 }
419 pthread_mutex_lock(&mLock);
420 if (--mCount < 0) {
421 ALOGE("negative wakelock count");
422 mCount = 0;
423 }
424 pthread_mutex_unlock(&mLock);
425 }
426
427 // retrieves the boottime timebase offset from monotonic.
428 int64_t getBoottimeOffset() {
429 pthread_mutex_lock(&mLock);
430 int64_t boottimeOffset = mBoottimeOffset;
431 pthread_mutex_unlock(&mLock);
432 return boottimeOffset;
433 }
434
435 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
436 // and the selected timebase.
437 // Currently only TIMEBASE_BOOTTIME is allowed.
438 //
439 // This only needs to be called upon acquiring the first partial wakelock
440 // after all other partial wakelocks are released.
441 //
442 // We do an empirical measurement of the offset rather than parsing
443 // /proc/timer_list since the latter is not a formal kernel ABI.
444 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
445 int clockbase;
446 switch (timebase) {
447 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
448 clockbase = SYSTEM_TIME_BOOTTIME;
449 break;
450 default:
451 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
452 break;
453 }
454 // try three times to get the clock offset, choose the one
455 // with the minimum gap in measurements.
456 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700457 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800458 for (int i = 0; i < tries; ++i) {
459 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
460 const nsecs_t tbase = systemTime(clockbase);
461 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
462 const nsecs_t gap = tmono2 - tmono;
463 if (i == 0 || gap < bestGap) {
464 bestGap = gap;
465 measured = tbase - ((tmono + tmono2) >> 1);
466 }
467 }
468
469 // to avoid micro-adjusting, we don't change the timebase
470 // unless it is significantly different.
471 //
472 // Assumption: It probably takes more than toleranceNs to
473 // suspend and resume the device.
474 static int64_t toleranceNs = 10000; // 10 us
475 if (llabs(*offset - measured) > toleranceNs) {
476 ALOGV("Adjusting timebase offset old: %lld new: %lld",
477 (long long)*offset, (long long)measured);
478 *offset = measured;
479 }
480 }
481
482 pthread_mutex_t mLock;
483 int32_t mCount;
484 int64_t mBoottimeOffset;
485} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800486
487// ----------------------------------------------------------------------------
488// CPU Stats
489// ----------------------------------------------------------------------------
490
491class CpuStats {
492public:
493 CpuStats();
494 void sample(const String8 &title);
495#ifdef DEBUG_CPU_USAGE
496private:
497 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700498 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800499
Andy Hung16698b82018-08-01 10:48:38 -0700500 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800501
502 int mCpuNum; // thread's current CPU number
503 int mCpukHz; // frequency of thread's current CPU in kHz
504#endif
505};
506
507CpuStats::CpuStats()
508#ifdef DEBUG_CPU_USAGE
509 : mCpuNum(-1), mCpukHz(-1)
510#endif
511{
512}
513
Glenn Kasten0f11b512014-01-31 16:18:54 -0800514void CpuStats::sample(const String8 &title
515#ifndef DEBUG_CPU_USAGE
516 __unused
517#endif
518 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800519#ifdef DEBUG_CPU_USAGE
520 // get current thread's delta CPU time in wall clock ns
521 double wcNs;
522 bool valid = mCpuUsage.sampleAndEnable(wcNs);
523
524 // record sample for wall clock statistics
525 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700526 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800527 }
528
529 // get the current CPU number
530 int cpuNum = sched_getcpu();
531
532 // get the current CPU frequency in kHz
533 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
534
535 // check if either CPU number or frequency changed
536 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
537 mCpuNum = cpuNum;
538 mCpukHz = cpukHz;
539 // ignore sample for purposes of cycles
540 valid = false;
541 }
542
543 // if no change in CPU number or frequency, then record sample for cycle statistics
544 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700545 const double cycles = wcNs * cpukHz * 0.000001;
546 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800547 }
548
Eric Tan5b13ff82018-07-27 11:20:17 -0700549 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800550 // mCpuUsage.elapsed() is expensive, so don't call it every loop
551 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700552 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800553 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700554 const double perLoop = elapsed / (double) n;
555 const double perLoop100 = perLoop * 0.01;
556 const double perLoop1k = perLoop * 0.001;
557 const double mean = mWcStats.getMean();
558 const double stddev = mWcStats.getStdDev();
559 const double minimum = mWcStats.getMin();
560 const double maximum = mWcStats.getMax();
561 const double meanCycles = mHzStats.getMean();
562 const double stddevCycles = mHzStats.getStdDev();
563 const double minCycles = mHzStats.getMin();
564 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800565 mCpuUsage.resetElapsed();
566 mWcStats.reset();
567 mHzStats.reset();
568 ALOGD("CPU usage for %s over past %.1f secs\n"
569 " (%u mixer loops at %.1f mean ms per loop):\n"
570 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
571 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
572 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk5b054372023-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 Hung4b17e882023-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 Hung7535ed92023-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 Hung7535ed92023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-07-07 13:47:37 -0700697status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800698{
Tomasz Wasilczyk5b054372023-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 Hung4b17e882023-07-07 13:47:37 -0700707status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700708NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700709{
710 status_t status = NO_ERROR;
711
Eric Laurent72e3f392015-05-20 14:43:50 -0700712 if (event->mRequiresSystemReady && !mSystemReady) {
713 event->mWaitStatus = false;
714 mPendingConfigEvents.add(event);
715 return status;
716 }
Eric Laurent10351942014-05-08 18:49:52 -0700717 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700718 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-07-07 13:47:37 -0700849void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-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 Hung4b17e882023-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 Wasilczyk5b054372023-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 Laurent68a40a82022-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 Hung4b17e882023-07-07 13:47:37 -07001023void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-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 Hungf2f5d642023-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 Hung4b17e882023-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 Hung409572b2023-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 Wasilczyk5b054372023-08-15 20:59:35 +00001072 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung409572b2023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-07-07 13:47:37 -07001393void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001394 audio_session_t sessionId,
Andy Hung920f6572022-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-07-07 13:47:37 -07001618sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-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 Hung116bc262023-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 Hung116bc262023-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 Hung116bc262023-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 Hung7535ed92023-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 Hung7535ed92023-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 Hung7535ed92023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-06-20 18:56:17 -07001727 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001728 {
1729 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-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 Hung7535ed92023-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 Hung4b17e882023-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 Hung7535ed92023-07-17 17:05:00 -07001764 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001765 }
1766 }
1767}
1768
Andy Hung4b17e882023-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 Hung4b17e882023-07-07 13:47:37 -07001776sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-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 Hung4b17e882023-07-07 13:47:37 -07001783sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001784 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001785{
Andy Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung116bc262023-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 Hung7535ed92023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-07-07 13:47:37 -07001862void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001863 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-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++) {
Andy Hung1f6d4cd2023-08-29 12:19:17 -07001868 mEffectChains[i]->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001869 }
1870}
1871
Andy Hung4b17e882023-07-07 13:47:37 -07001872void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001873 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-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++) {
Andy Hung1f6d4cd2023-08-29 12:19:17 -07001877 effectChains[i]->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001878 }
1879}
1880
Andy Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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;
Atneya Nair166663a2023-06-27 19:16:24 -07001943 track->beginBatteryAttribution();
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 Hung4b17e882023-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++;
Atneya Nair166663a2023-06-27 19:16:24 -07001957 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001958 // 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 Hung4b17e882023-07-07 13:47:37 -07001968void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001969 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001970 track->endBatteryAttribution();
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();
Andy Hungdae27702016-10-31 14:01:16 -07001977}
1978
1979template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001980void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001981 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001982 // Updates ActiveTracks client uids to the thread wakelock.
1983 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1984 thread->updateWakeLockUids_l(getWakeLockUids());
1985 mLastActiveTracksGeneration = mActiveTracksGeneration;
1986 }
Andy Hungdae27702016-10-31 14:01:16 -07001987}
Eric Laurent83b88082014-06-20 18:31:16 -07001988
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001989template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001990bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001991 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001992 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001993
1994 for (const sp<T> &track : mActiveTracks) {
1995 // Do not short-circuit as all hasChanged states must be reset
1996 // as all the metadata are going to be sent
1997 hasChanged |= track->readAndClearHasChanged();
1998 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001999 return hasChanged;
2000}
2001
2002template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002003void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002004 const char *funcName, const sp<T> &track) const {
2005 if (mLocalLog != nullptr) {
2006 String8 result;
2007 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002008 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002009 }
2010}
2011
Andy Hung4b17e882023-07-07 13:47:37 -07002012void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002013{
2014 // Thread could be blocked waiting for async
2015 // so signal it to handle state changes immediately
2016 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2017 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2018 mSignalPending = true;
2019 mWaitWorkCV.broadcast();
2020}
2021
Andy Hungd0979812019-02-21 15:51:44 -08002022// Call only from threadLoop() or when it is idle.
2023// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07002024void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08002025{
2026 // Do not log if we have no stats.
2027 // We choose the timestamp verifier because it is the most likely item to be present.
2028 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2029 if (nstats == 0) {
2030 return;
2031 }
2032
2033 // Don't log more frequently than once per 12 hours.
2034 // We use BOOTTIME to include suspend time.
2035 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2036 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2037 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2038 return;
2039 }
2040
2041 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2042 mLastRecordedTimeNs = timeNs;
2043
Ray Essickf27e9872019-12-07 06:28:46 -08002044 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002045
2046#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2047
2048 // thread configuration
2049 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2050 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2051 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2052 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2053 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2054 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2055 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002056 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2057 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002058
2059 // thread statistics
2060 if (mIoJitterMs.getN() > 0) {
2061 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2062 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2063 }
2064 if (mProcessTimeMs.getN() > 0) {
2065 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2066 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2067 }
2068 const auto tsjitter = mTimestampVerifier.getJitterMs();
2069 if (tsjitter.getN() > 0) {
2070 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2071 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2072 }
2073 if (mLatencyMs.getN() > 0) {
2074 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2075 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2076 }
Robert Wu06db0a32021-08-10 19:05:34 +00002077 if (mMonopipePipeDepthStats.getN() > 0) {
2078 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2079 mMonopipePipeDepthStats.getMean());
2080 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2081 mMonopipePipeDepthStats.getStdDev());
2082 }
Andy Hungd0979812019-02-21 15:51:44 -08002083
2084 item->selfrecord();
2085}
2086
Andy Hung4b17e882023-07-07 13:47:37 -07002087product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002088{
Andy Hung7535ed92023-07-17 17:05:00 -07002089 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002090 return PRODUCT_STRATEGY_NONE;
2091 }
2092 return AudioSystem::getStrategyForStream(stream);
2093}
2094
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002095// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002096void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002097 const sp<audio_utils::MelProcessor>& /*processor*/)
2098{
2099 // Do nothing
2100 ALOGW("%s: ThreadBase does not support CSD", __func__);
2101}
2102
2103// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002104void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002105{
2106 // Do nothing
2107 ALOGW("%s: ThreadBase does not support CSD", __func__);
2108}
2109
Eric Laurent81784c32012-11-19 14:55:58 -08002110// ----------------------------------------------------------------------------
2111// Playback
2112// ----------------------------------------------------------------------------
2113
Andy Hung7535ed92023-07-17 17:05:00 -07002114PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002115 AudioStreamOut* output,
2116 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002117 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002118 bool systemReady,
2119 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002120 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002121 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002122 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002123 mMixerBuffer(NULL),
2124 mMixerBufferSize(0),
2125 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2126 mMixerBufferValid(false),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002127 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002128 mEffectBuffer(NULL),
2129 mEffectBufferSize(0),
2130 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2131 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002132 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002133 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002134 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002135 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002136 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002137 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002138 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002139 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002140 mMixerStatus(MIXER_IDLE),
2141 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hungd58c4732023-07-20 21:31:38 -07002142 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002143 mBytesRemaining(0),
2144 mCurrentWriteLength(0),
2145 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002146 mWriteAckSequence(0),
2147 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002148 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002149 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002150 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002151 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002152 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002153 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002154 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002155{
Glenn Kastend7dca052015-03-05 16:05:54 -08002156 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002157 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002158
2159 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2160 // it would be safer to explicitly pass initial masterVolume/masterMute as
2161 // parameter.
2162 //
2163 // If the HAL we are using has support for master volume or master mute,
2164 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2165 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002166 mMasterVolume = afThreadCallback->masterVolume_l();
2167 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002168 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002169 if (mOutput->audioHwDev->canSetMasterVolume()) {
2170 mMasterVolume = 1.0;
2171 }
2172
2173 if (mOutput->audioHwDev->canSetMasterMute()) {
2174 mMasterMute = false;
2175 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002176 mIsMsdDevice = strcmp(
2177 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002178 }
2179
Eric Laurentf1f22e72021-07-13 14:04:14 +02002180 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2181 mMixerChannelMask = mixerConfig->channel_mask;
2182 }
2183
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002184 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002185
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002186 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002187 && mMixerChannelMask != mChannelMask) {
2188 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2189 mChannelMask, mMixerChannelMask);
2190 }
2191
Andy Hungc8fddf32018-08-08 18:32:37 -07002192 // TODO: We may also match on address as well as device type for
2193 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002194 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002195 // TODO: This property should be ensure that only contains one single device type.
2196 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2197 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002198 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2199 : AUDIO_DEVICE_NONE));
2200 }
2201
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002202 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2203 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002204 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002205 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002206 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002207 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002208 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2209 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002210 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2211 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002212}
2213
Andy Hung4b17e882023-07-07 13:47:37 -07002214PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002215{
Andy Hung7535ed92023-07-17 17:05:00 -07002216 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002217 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002218 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002219 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002220 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002221}
2222
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002223// Thread virtuals
2224
Andy Hung4b17e882023-07-07 13:47:37 -07002225void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002226{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002227 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002228 ALOGE("The stream is not open yet"); // This should not happen.
2229 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002230 // Callbacks take strong or weak pointers as a parameter.
2231 // Since PlaybackThread passes itself as a callback handler, it can only
2232 // be done outside of the constructor. Creating weak and especially strong
2233 // pointers to a refcounted object in its own constructor is strongly
2234 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2235 // Even if a function takes a weak pointer, it is possible that it will
2236 // need to convert it to a strong pointer down the line.
2237 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2238 mOutput->stream->setCallback(this) == OK) {
2239 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002240 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002241 }
2242
jiabinf6eb4c32020-02-25 14:06:25 -08002243 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002244 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002245 }
2246 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002247 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002248 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002249}
2250
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002251// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002252void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002253{
2254 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002255 status_t result = mOutput->stream->exit();
2256 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002257}
2258
Andy Hung4b17e882023-07-07 13:47:37 -07002259void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002260{
Eric Laurent81784c32012-11-19 14:55:58 -08002261 String8 result;
2262
Marco Nelissenb2208842014-02-07 14:00:50 -08002263 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002264 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2265 const stream_type_t *st = &mStreamTypes[i];
2266 if (i > 0) {
2267 result.appendFormat(", ");
2268 }
2269 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2270 if (st->mute) {
2271 result.append("M");
2272 }
2273 }
2274 result.append("\n");
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002275 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002276 result.clear();
2277
Eric Laurent81784c32012-11-19 14:55:58 -08002278 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2279 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002280 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002281 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002282
2283 size_t numtracks = mTracks.size();
2284 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002285 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002286 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002287 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002288 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002289 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002290 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002291 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002292 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002293 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002294 if (track != 0) {
2295 bool active = mActiveTracks.indexOf(track) >= 0;
2296 if (active) {
2297 numactiveseen++;
2298 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002299 result.append(prefix);
2300 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002301 }
2302 }
2303 } else {
2304 result.append("\n");
2305 }
2306 if (numactiveseen != numactive) {
2307 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002308 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002309 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002310 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002311 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002312 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002313 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002314 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002315 result.append(prefix);
2316 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002317 }
2318 }
2319 }
2320
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002321 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002322}
2323
Andy Hung4b17e882023-07-07 13:47:37 -07002324void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002325{
Andy Hung04cb8f72020-03-20 13:44:33 -07002326 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002327 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002328 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2329 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002330 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2331 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2332 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2333 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002334 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002335 dprintf(fd, " Total writes: %d\n", mNumWrites);
2336 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2337 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2338 dprintf(fd, " Suspend count: %d\n", mSuspended);
2339 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2340 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2341 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2342 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002343 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002344 AudioStreamOut *output = mOutput;
2345 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002346 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002347 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002348 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2349 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2350 if (mPipeSink.get() != nullptr) {
2351 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2352 }
2353 if (output != nullptr) {
2354 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002355 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002356 }
Eric Laurent81784c32012-11-19 14:55:58 -08002357}
2358
Eric Laurent81784c32012-11-19 14:55:58 -08002359// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002360sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002361 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002362 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002363 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002364 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002365 audio_format_t format,
2366 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002367 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002368 size_t *pNotificationFrameCount,
2369 uint32_t notificationsPerBuffer,
2370 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002371 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002372 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002373 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002374 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002375 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002376 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002377 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002378 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002379 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002380 bool isSpatialized,
2381 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002382{
Glenn Kasten74935e42013-12-19 08:56:45 -08002383 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002384 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002385 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002386 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002387 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002388 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002389 uint32_t sampleRate;
2390
2391 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2392 lStatus = BAD_VALUE;
2393 goto Exit;
2394 }
Eric Laurent21da6472017-11-09 16:29:26 -08002395
2396 if (*pSampleRate == 0) {
2397 *pSampleRate = mSampleRate;
2398 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002399 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002400
2401 // special case for FAST flag considered OK if fast mixer is present
2402 if (hasFastMixer()) {
2403 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2404 }
2405
2406 // Check if requested flags are compatible with output stream flags
2407 if ((*flags & outputFlags) != *flags) {
2408 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2409 *flags, outputFlags);
2410 *flags = (audio_output_flags_t)(*flags & outputFlags);
2411 }
Eric Laurent81784c32012-11-19 14:55:58 -08002412
jiabinc658e452022-10-21 20:52:21 +00002413 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002414 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002415 if (chain.get() != nullptr) {
2416 // Bit-perfect is required according to the configuration and preferred mixer
2417 // attributes, but it is not in the output flag from the client's request. Explicitly
2418 // adding bit-perfect flag to check the compatibility
2419 audio_output_flags_t flagsToCheck =
2420 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2421 chain->checkOutputFlagCompatibility(&flagsToCheck);
2422 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2423 ALOGE("%s cannot create track as there is data-processing effect attached to "
2424 "given session id(%d)", __func__, sessionId);
2425 lStatus = BAD_VALUE;
2426 goto Exit;
2427 }
2428 *flags = flagsToCheck;
2429 }
2430 }
2431
Eric Laurent81784c32012-11-19 14:55:58 -08002432 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002433 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002434 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002435 // PCM data
2436 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002437 // TODO: extract as a data library function that checks that a computationally
2438 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002439 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002440 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2441 (channelMask == AUDIO_CHANNEL_OUT_MONO
2442 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002443 // hardware sample rate
2444 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // normal mixer has an associated fast mixer
2446 hasFastMixer() &&
2447 // there are sufficient fast track slots available
2448 (mFastTrackAvailMask != 0)
2449 // FIXME test that MixerThread for this fast track has a capable output HAL
2450 // FIXME add a permission test also?
2451 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002452 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2453 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002454 // read the fast track multiplier property the first time it is needed
2455 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2456 if (ok != 0) {
2457 ALOGE("%s pthread_once failed: %d", __func__, ok);
2458 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002459 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002460 }
Eric Laurent4c415062016-06-17 16:14:16 -07002461
2462 // check compatibility with audio effects.
2463 { // scope for mLock
2464 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002465 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002466 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002467 AUDIO_SESSION_OUTPUT_STAGE,
2468 AUDIO_SESSION_OUTPUT_MIX,
2469 sessionId,
2470 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002471 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002472 if (chain.get() != nullptr) {
2473 audio_output_flags_t old = *flags;
2474 chain->checkOutputFlagCompatibility(flags);
2475 if (old != *flags) {
2476 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2477 (int)session, (int)old, (int)*flags);
2478 }
Eric Laurent4c415062016-06-17 16:14:16 -07002479 }
2480 }
2481 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002482 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002483 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2484 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002485 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002486 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002487 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002488 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002489 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002490 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002491 audio_is_linear_pcm(format), channelMask, sampleRate,
2492 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002493 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002494 }
2495 }
Eric Laurent21da6472017-11-09 16:29:26 -08002496
2497 if (!audio_has_proportional_frames(format)) {
2498 if (sharedBuffer != 0) {
2499 // Same comment as below about ignoring frameCount parameter for set()
2500 frameCount = sharedBuffer->size();
2501 } else if (frameCount == 0) {
2502 frameCount = mNormalFrameCount;
2503 }
2504 if (notificationFrameCount != frameCount) {
2505 notificationFrameCount = frameCount;
2506 }
2507 } else if (sharedBuffer != 0) {
2508 // FIXME: Ensure client side memory buffers need
2509 // not have additional alignment beyond sample
2510 // (e.g. 16 bit stereo accessed as 32 bit frame).
2511 size_t alignment = audio_bytes_per_sample(format);
2512 if (alignment & 1) {
2513 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2514 alignment = 1;
2515 }
2516 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2517 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2518 if (channelCount > 1) {
2519 // More than 2 channels does not require stronger alignment than stereo
2520 alignment <<= 1;
2521 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002522 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002523 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002524 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002525 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002526 goto Exit;
2527 }
Eric Laurent21da6472017-11-09 16:29:26 -08002528
2529 // When initializing a shared buffer AudioTrack via constructors,
2530 // there's no frameCount parameter.
2531 // But when initializing a shared buffer AudioTrack via set(),
2532 // there _is_ a frameCount parameter. We silently ignore it.
2533 frameCount = sharedBuffer->size() / frameSize;
2534 } else {
2535 size_t minFrameCount = 0;
2536 // For fast tracks we try to respect the application's request for notifications per buffer.
2537 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2538 if (notificationsPerBuffer > 0) {
2539 // Avoid possible arithmetic overflow during multiplication.
2540 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2541 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2542 notificationsPerBuffer, mFrameCount);
2543 } else {
2544 minFrameCount = mFrameCount * notificationsPerBuffer;
2545 }
2546 }
2547 } else {
2548 // For normal PCM streaming tracks, update minimum frame count.
2549 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2550 // cover audio hardware latency.
2551 // This is probably too conservative, but legacy application code may depend on it.
2552 // If you change this calculation, also review the start threshold which is related.
2553 uint32_t latencyMs = latency_l();
2554 if (latencyMs == 0) {
2555 ALOGE("Error when retrieving output stream latency");
2556 lStatus = UNKNOWN_ERROR;
2557 goto Exit;
2558 }
2559
2560 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2561 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2562
Eric Laurent81784c32012-11-19 14:55:58 -08002563 }
Eric Laurent21da6472017-11-09 16:29:26 -08002564 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002565 frameCount = minFrameCount;
2566 }
Eric Laurent81784c32012-11-19 14:55:58 -08002567 }
Eric Laurent21da6472017-11-09 16:29:26 -08002568
2569 // Make sure that application is notified with sufficient margin before underrun.
2570 // The client can divide the AudioTrack buffer into sub-buffers,
2571 // and expresses its desire to server as the notification frame count.
2572 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2573 size_t maxNotificationFrames;
2574 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2575 // notify every HAL buffer, regardless of the size of the track buffer
2576 maxNotificationFrames = mFrameCount;
2577 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002578 // Triple buffer the notification period for a triple buffered mixer period;
2579 // otherwise, double buffering for the notification period is fine.
2580 //
2581 // TODO: This should be moved to AudioTrack to modify the notification period
2582 // on AudioTrack::setBufferSizeInFrames() changes.
2583 const int nBuffering =
2584 (uint64_t{frameCount} * mSampleRate)
2585 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2586
Eric Laurent21da6472017-11-09 16:29:26 -08002587 maxNotificationFrames = frameCount / nBuffering;
2588 // If client requested a fast track but this was denied, then use the smaller maximum.
2589 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2590 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2591 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2592 maxNotificationFrames = maxNotificationFramesFastDenied;
2593 }
2594 }
2595 }
2596 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2597 if (notificationFrameCount == 0) {
2598 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2599 maxNotificationFrames, frameCount);
2600 } else {
2601 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2602 notificationFrameCount, maxNotificationFrames, frameCount);
2603 }
2604 notificationFrameCount = maxNotificationFrames;
2605 }
2606 }
2607
Glenn Kasten74935e42013-12-19 08:56:45 -08002608 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002609 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002610
Glenn Kastenc3df8382014-03-13 15:05:25 -07002611 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002612 case BIT_PERFECT:
2613 if (isBitPerfect) {
2614 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2615 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2616 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2617 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2618 mChannelMask);
2619 lStatus = BAD_VALUE;
2620 goto Exit;
2621 }
2622 }
2623 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002624
2625 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002626 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002627 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002628 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2629 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002630 sampleRate, format, channelMask, mOutput, mFormat);
2631 lStatus = BAD_VALUE;
2632 goto Exit;
2633 }
2634 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002635 break;
2636
2637 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002638 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002639 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2640 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 sampleRate, format, channelMask, mOutput, mFormat);
2642 lStatus = BAD_VALUE;
2643 goto Exit;
2644 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002645 break;
2646
2647 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002648 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002649 ALOGE("createTrack_l() Bad parameter: format %#x \""
2650 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 format, mOutput, mFormat);
2652 lStatus = BAD_VALUE;
2653 goto Exit;
2654 }
Andy Hungcd044842014-08-07 11:04:34 -07002655 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002656 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2657 lStatus = BAD_VALUE;
2658 goto Exit;
2659 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002660 break;
2661
Eric Laurent81784c32012-11-19 14:55:58 -08002662 }
2663
2664 lStatus = initCheck();
2665 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002666 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002667 goto Exit;
2668 }
2669
2670 { // scope for mLock
2671 Mutex::Autolock _l(mLock);
2672
2673 // all tracks in same audio session must share the same routing strategy otherwise
2674 // conflicts will happen when tracks are moved from one output to another by audio policy
2675 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002676 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002677 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002678 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002679 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002680 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002681 if (sessionId == t->sessionId() && strategy != actual) {
2682 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2683 strategy, actual);
2684 lStatus = BAD_VALUE;
2685 goto Exit;
2686 }
2687 }
2688 }
2689
yucliuc9c49cd2020-07-13 16:25:21 -07002690 // Set DIRECT flag if current thread is DirectOutputThread. This can
2691 // happen when the playback is rerouted to direct output thread by
2692 // dynamic audio policy.
2693 // Do NOT report the flag changes back to client, since the client
2694 // doesn't explicitly request a direct flag.
2695 audio_output_flags_t trackFlags = *flags;
2696 if (mType == DIRECT) {
2697 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2698 }
2699
Andy Hung11e74242023-06-26 19:20:57 -07002700 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002701 channelMask, frameCount,
2702 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002703 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002704 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002705 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002706
Glenn Kasten03003332013-08-06 15:40:54 -07002707 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2708 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002709 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002710 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002711 goto Exit;
2712 }
2713 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002714 {
2715 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2716 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002717 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002718 }
2719 }
Eric Laurent81784c32012-11-19 14:55:58 -08002720
Andy Hung116bc262023-06-20 18:56:17 -07002721 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002722 if (chain != 0) {
2723 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2724 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002725 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002726 chain->incTrackCnt();
2727 }
2728
Eric Laurent05067782016-06-01 18:27:28 -07002729 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002730 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2731 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2732 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002733 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002734 }
2735 }
2736
2737 lStatus = NO_ERROR;
2738
2739Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002740 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002741 return track;
2742}
2743
Andy Hung1bc088a2018-02-09 15:57:31 -08002744template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002745ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002746{
Andy Hungc0691382018-09-12 18:01:57 -07002747 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002748 const ssize_t index = mTracks.remove(track);
2749 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002750 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002751 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002752 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002753 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002754 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002755 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002756 }
2757 return index;
2758}
2759
Andy Hung4b17e882023-07-07 13:47:37 -07002760uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002761{
2762 return latency;
2763}
2764
Andy Hung4b17e882023-07-07 13:47:37 -07002765uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002766{
2767 Mutex::Autolock _l(mLock);
2768 return latency_l();
2769}
Andy Hung4b17e882023-07-07 13:47:37 -07002770uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002771{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002772 uint32_t latency;
2773 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2774 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002775 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002776 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002777}
2778
Andy Hung4b17e882023-07-07 13:47:37 -07002779void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002780{
2781 Mutex::Autolock _l(mLock);
2782 // Don't apply master volume in SW if our HAL can do it for us.
2783 if (mOutput && mOutput->audioHwDev &&
2784 mOutput->audioHwDev->canSetMasterVolume()) {
2785 mMasterVolume = 1.0;
2786 } else {
2787 mMasterVolume = value;
2788 }
2789}
2790
Andy Hung4b17e882023-07-07 13:47:37 -07002791void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002792{
2793 mMasterBalance.store(balance);
2794}
2795
Andy Hung4b17e882023-07-07 13:47:37 -07002796void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002797{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002798 if (isDuplicating()) {
2799 return;
2800 }
Eric Laurent81784c32012-11-19 14:55:58 -08002801 Mutex::Autolock _l(mLock);
2802 // Don't apply master mute in SW if our HAL can do it for us.
2803 if (mOutput && mOutput->audioHwDev &&
2804 mOutput->audioHwDev->canSetMasterMute()) {
2805 mMasterMute = false;
2806 } else {
2807 mMasterMute = muted;
2808 }
2809}
2810
Andy Hung4b17e882023-07-07 13:47:37 -07002811void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002812{
2813 Mutex::Autolock _l(mLock);
2814 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002815 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002816}
2817
Andy Hung4b17e882023-07-07 13:47:37 -07002818void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002819{
2820 Mutex::Autolock _l(mLock);
2821 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002822 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002823}
2824
Andy Hung4b17e882023-07-07 13:47:37 -07002825float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002826{
2827 Mutex::Autolock _l(mLock);
2828 return mStreamTypes[stream].volume;
2829}
2830
Andy Hung4b17e882023-07-07 13:47:37 -07002831void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002832{
2833 mOutput->stream->setVolume(left, right);
2834}
2835
Eric Laurent81784c32012-11-19 14:55:58 -08002836// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002837status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung920f6572022-10-06 12:09:49 -07002838NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002839{
2840 status_t status = ALREADY_EXISTS;
2841
Eric Laurent81784c32012-11-19 14:55:58 -08002842 if (mActiveTracks.indexOf(track) < 0) {
2843 // the track is newly added, make sure it fills up all its
2844 // buffers before playing. This is to ensure the client will
2845 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002846 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002847 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002848 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002849 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850 mLock.lock();
2851 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002852 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002853 if (status == NO_ERROR) {
2854 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002855 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856 mLock.lock();
2857 }
2858 return INVALID_OPERATION;
2859 }
2860 // abort if start is rejected by audio policy manager
2861 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002862 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2863 // current playback thread is reopened, which may happen when clients set preferred
2864 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2865 // immediately.
2866 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002867 }
2868#ifdef ADD_BATTERY_DATA
2869 // to track the speaker usage
2870 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2871#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002872 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873 }
2874
Eric Laurent51716182016-02-29 18:00:56 -08002875 // set retry count for buffer fill
2876 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002877 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002878 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002879 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002880 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002881 }
Andy Hung11e74242023-06-26 19:20:57 -07002882 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002883 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002884 track->retryCount() = kMaxTrackStartupRetries;
2885 track->fillingStatus() =
2886 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002887 }
2888
Andy Hung116bc262023-06-20 18:56:17 -07002889 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002890 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2891 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2892 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002893 // Unlock due to VibratorService will lock for this call and will
2894 // call Tracks.mute/unmute which also require thread's lock.
2895 mLock.unlock();
Andy Hung76cb9152023-07-20 21:23:42 -07002896 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002897 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002898 std::optional<media::AudioVibratorInfo> vibratorInfo;
2899 {
2900 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2901 // used to play this track.
Andy Hung85a07452023-08-28 18:36:53 -07002902 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung7535ed92023-07-17 17:05:00 -07002903 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002904 }
jiabin57303cc2018-12-18 15:45:57 -08002905 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002906 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002907 if (vibratorInfo) {
2908 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2909 }
2910
jiabin57303cc2018-12-18 15:45:57 -08002911 // Haptic playback should be enabled by vibrator service.
2912 if (track->getHapticPlaybackEnabled()) {
2913 // Disable haptic playback of all active track to ensure only
2914 // one track playing haptic if current track should play haptic.
2915 for (const auto &t : mActiveTracks) {
2916 t->setHapticPlaybackEnabled(false);
2917 }
jiabin245cdd92018-12-07 17:55:15 -08002918 }
jiabine70bc7f2020-06-30 22:07:55 -07002919
2920 // Set haptic intensity for effect
2921 if (chain != nullptr) {
2922 chain->setHapticIntensity_l(track->id(), intensity);
2923 }
jiabin245cdd92018-12-07 17:55:15 -08002924 }
2925
Andy Hung11e74242023-06-26 19:20:57 -07002926 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002927 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002928 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002929 if (chain != 0) {
2930 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2931 track->sessionId());
2932 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002933 }
2934
Andy Hungc2b11cb2020-04-22 09:04:01 -07002935 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002936 status = NO_ERROR;
2937 }
2938
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002939 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002940 return status;
2941}
2942
Andy Hung4b17e882023-07-07 13:47:37 -07002943bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002944{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002946 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002947 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002948 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002949 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002950 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002951 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002952 if (track->isPausePending()) {
2953 track->pauseAck();
2954 }
Andy Hung11e74242023-06-26 19:20:57 -07002955 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002956 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002957
2958 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002959}
2960
Andy Hung4b17e882023-07-07 13:47:37 -07002961void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002962{
2963 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002964
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002965 String8 result;
2966 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002967 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002968
Eric Laurent81784c32012-11-19 14:55:58 -08002969 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002970 {
2971 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2972 mAudioTrackCallbacks.erase(track);
2973 }
Eric Laurent81784c32012-11-19 14:55:58 -08002974 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002975 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002976 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002977 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2978 mFastTrackAvailMask |= 1 << index;
2979 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07002980 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002981 }
Andy Hung116bc262023-06-20 18:56:17 -07002982 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002983 if (chain != 0) {
2984 chain->decTrackCnt();
2985 }
2986}
2987
Andy Hung4b17e882023-07-07 13:47:37 -07002988String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002989{
Eric Laurent81784c32012-11-19 14:55:58 -08002990 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002991 String8 out_s8;
2992 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2993 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002994 }
Andy Hung920f6572022-10-06 12:09:49 -07002995 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002996}
2997
Andy Hung4b17e882023-07-07 13:47:37 -07002998status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002999 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003000 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003001 return NO_INIT;
3002 }
3003 return mOutput->stream->selectPresentation(presentationId, programId);
3004}
3005
Andy Hung4b17e882023-07-07 13:47:37 -07003006void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003007 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003008 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003009 sp<AudioIoDescriptor> desc;
3010 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003011 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003012 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003013 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003014 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003015 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3016 mSampleRate, mFormat, mChannelMask,
3017 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3018 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003019 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003020 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003021 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003022 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003023 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003024 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003025 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003026 break;
3027 }
Andy Hung7535ed92023-07-17 17:05:00 -07003028 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003029}
3030
Andy Hung4b17e882023-07-07 13:47:37 -07003031void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003032{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003033 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003034}
3035
Andy Hung4b17e882023-07-07 13:47:37 -07003036void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003037{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003038 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003039}
3040
Andy Hung4b17e882023-07-07 13:47:37 -07003041void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003042{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003043 mCallbackThread->setAsyncError();
3044}
3045
Andy Hung4b17e882023-07-07 13:47:37 -07003046void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003047 const std::basic_string<uint8_t>& metadataBs)
3048{
Andy Hung4b17e882023-07-07 13:47:37 -07003049 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003050 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07003051 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003052 if (playbackThread == nullptr) {
3053 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3054 return;
3055 }
3056
jiabinf6eb4c32020-02-25 14:06:25 -08003057 audio_utils::metadata::Data metadata =
3058 audio_utils::metadata::dataFromByteString(metadataBs);
3059 if (metadata.empty()) {
3060 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3061 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3062 (int)metadataBs.size());
3063 return;
3064 }
3065
3066 audio_utils::metadata::ByteString metaDataStr =
3067 audio_utils::metadata::byteStringFromData(metadata);
3068 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3069 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003070 for (const auto& callbackPair : mAudioTrackCallbacks) {
3071 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003072 }
3073 }).detach();
3074}
3075
Andy Hung4b17e882023-07-07 13:47:37 -07003076void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003077{
3078 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003079 // reject out of sequence requests
3080 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3081 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003082 mWaitWorkCV.signal();
3083 }
3084}
3085
Andy Hung4b17e882023-07-07 13:47:37 -07003086void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003087{
3088 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003089 // reject out of sequence requests
3090 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003091 // Register discontinuity when HW drain is completed because that can cause
3092 // the timestamp frame position to reset to 0 for direct and offload threads.
3093 // (Out of sequence requests are ignored, since the discontinuity would be handled
3094 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003095 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003096 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003097 mWaitWorkCV.signal();
3098 }
3099}
3100
Andy Hung4b17e882023-07-07 13:47:37 -07003101void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003102{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003103 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003104 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3105 mSampleRate = audioConfig.sample_rate;
3106 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003107 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003108 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003109 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003110 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003111 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3112 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003113 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003114
3115 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3116 mMixerChannelMask = mChannelMask;
3117 }
3118
Andy Hunge5412692014-05-16 11:25:07 -07003119 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003120 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003121
Eric Laurentf1f22e72021-07-13 14:04:14 +02003122 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3123
Phil Burkca5e6142015-07-14 09:42:29 -07003124 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003125 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003126 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003127 // Get format from the shim, which will be different than the HAL format
3128 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003129 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003130 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003131 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003132 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003133 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003134 LOG_FATAL("HAL format %#x not supported for mixed output",
3135 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003136 }
Phil Burk062e67a2015-02-11 13:40:50 -08003137 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003138 result = mOutput->stream->getBufferSize(&mBufferSize);
3139 LOG_ALWAYS_FATAL_IF(result != OK,
3140 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003141 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003142 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003143 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003144 mFrameCount);
3145 }
3146
Eric Laurentd1f69b02014-12-15 14:33:13 -08003147 mHwSupportsPause = false;
3148 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003149 bool supportsPause = false, supportsResume = false;
3150 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3151 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003152 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003153 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003154 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003155 } else if (supportsResume) {
3156 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003157 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003158 }
3159 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003160 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3161 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3162 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003163
Andy Hungfbfc3952015-01-15 13:33:51 -08003164 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3165 // For best precision, we use float instead of the associated output
3166 // device format (typically PCM 16 bit).
3167
3168 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3169 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3170 mBufferSize = mFrameSize * mFrameCount;
3171
3172 // TODO: We currently use the associated output device channel mask and sample rate.
3173 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3174 // (if a valid mask) to avoid premature downmix.
3175 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3176 // instead of the output device sample rate to avoid loss of high frequency information.
3177 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3178 }
3179
Andy Hung09a50072014-02-27 14:30:47 -08003180 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003181 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003182 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003183 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3184 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003185 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3186 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003187
Eric Laurent81784c32012-11-19 14:55:58 -08003188 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3189 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3190 maxNormalFrameCount = maxNormalFrameCount & ~15;
3191 if (maxNormalFrameCount < minNormalFrameCount) {
3192 maxNormalFrameCount = minNormalFrameCount;
3193 }
3194 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3195 if (multiplier <= 1.0) {
3196 multiplier = 1.0;
3197 } else if (multiplier <= 2.0) {
3198 if (2 * mFrameCount <= maxNormalFrameCount) {
3199 multiplier = 2.0;
3200 } else {
3201 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3202 }
3203 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003204 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003205 }
3206 }
3207 mNormalFrameCount = multiplier * mFrameCount;
3208 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003209 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003210 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3211 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003212 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003213 mNormalFrameCount);
3214
Andy Hung08fb1742015-05-31 23:22:10 -07003215 // Check if we want to throttle the processing to no more than 2x normal rate
3216 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003217 mThreadThrottleTimeMs = 0;
3218 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003219 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3220
Andy Hung010a1a12014-03-13 13:57:33 -07003221 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3222 // Originally this was int16_t[] array, need to remove legacy implications.
3223 free(mSinkBuffer);
3224 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003225
Andy Hung5b10a202014-03-13 13:59:29 -07003226 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3227 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3228 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003229 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003230
Andy Hung69aed5f2014-02-25 17:24:40 -08003231 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3232 // drives the output.
3233 free(mMixerBuffer);
3234 mMixerBuffer = NULL;
3235 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003236 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003237 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003238 * audio_bytes_per_sample(mMixerBufferFormat);
3239 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3240 }
Andy Hung98ef9782014-03-04 14:46:50 -08003241 free(mEffectBuffer);
3242 mEffectBuffer = NULL;
3243 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003244 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003245 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003246 * audio_bytes_per_sample(mEffectBufferFormat);
3247 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3248 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003249
Eric Laurentb62d0362021-10-26 17:40:18 +02003250 if (mType == SPATIALIZER) {
3251 free(mPostSpatializerBuffer);
3252 mPostSpatializerBuffer = nullptr;
3253 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3254 * audio_bytes_per_sample(mEffectBufferFormat);
3255 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3256 }
3257
Mikhail Naganov55773032020-10-01 15:08:13 -07003258 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3259 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003260 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3261 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003262 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003263
Eric Laurent81784c32012-11-19 14:55:58 -08003264 // force reconfiguration of effect chains and engines to take new buffer size and audio
3265 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003266 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003267 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3268 // matter.
3269 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003270 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003271 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung7535ed92023-07-17 17:05:00 -07003272 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003273 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003274 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003275
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003276 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003277 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003278 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07003279 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003280 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3281 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3282 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3283 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3284 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3285 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3286 (int32_t)mHapticChannelMask)
3287 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3288 (int32_t)mHapticChannelCount)
3289 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -07003290 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003291 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3292 (int32_t)mFrameCount) // sic - added HAL
3293 ;
3294 uint32_t latencyMs;
3295 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3296 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3297 }
3298 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003299}
3300
Andy Hung4b17e882023-07-07 13:47:37 -07003301ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003302{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003303 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003304 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003305 }
3306 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003307 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07003308 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003309 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003310 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003311 }
Kevin Rocard12381092018-04-11 09:19:59 -07003312 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003313 MetadataUpdate change;
3314 change.playbackMetadataUpdate = metadata.tracks;
3315 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003316}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003317
Andy Hung4b17e882023-07-07 13:47:37 -07003318void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003319 const StreamOutHalInterface::SourceMetadata& metadata)
3320{
3321 mOutput->stream->updateSourceMetadata(metadata);
3322};
3323
Andy Hung4b17e882023-07-07 13:47:37 -07003324status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003325 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003326{
3327 if (halFrames == NULL || dspFrames == NULL) {
3328 return BAD_VALUE;
3329 }
3330 Mutex::Autolock _l(mLock);
3331 if (initCheck() != NO_ERROR) {
3332 return INVALID_OPERATION;
3333 }
Andy Hung818e7a32016-02-16 18:08:07 -08003334 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003335 *halFrames = framesWritten;
3336
3337 if (isSuspended()) {
3338 // return an estimation of rendered frames when the output is suspended
3339 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003340 *dspFrames = (uint32_t)
3341 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003342 return NO_ERROR;
3343 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003344 status_t status;
3345 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003346 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003347 *dspFrames = (size_t)frames;
3348 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003349 }
3350}
3351
Andy Hung4b17e882023-07-07 13:47:37 -07003352product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003353{
3354 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3355 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3356 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003357 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003358 }
3359 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003360 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003361 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003362 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003363 }
3364 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003365 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003366}
3367
3368
Andy Hung4b17e882023-07-07 13:47:37 -07003369AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003370{
3371 Mutex::Autolock _l(mLock);
3372 return mOutput;
3373}
3374
Andy Hung4b17e882023-07-07 13:47:37 -07003375AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003376{
3377 Mutex::Autolock _l(mLock);
3378 AudioStreamOut *output = mOutput;
3379 mOutput = NULL;
3380 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3381 // must push a NULL and wait for ack
3382 mOutputSink.clear();
3383 mPipeSink.clear();
3384 mNormalSink.clear();
3385 return output;
3386}
3387
3388// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003389sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003390{
3391 if (mOutput == NULL) {
3392 return NULL;
3393 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003394 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003395}
3396
Andy Hung4b17e882023-07-07 13:47:37 -07003397uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003398{
3399 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3400}
3401
Andy Hung4b17e882023-07-07 13:47:37 -07003402status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003403{
3404 if (!isValidSyncEvent(event)) {
3405 return BAD_VALUE;
3406 }
3407
3408 Mutex::Autolock _l(mLock);
3409
3410 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003411 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003412 if (event->triggerSession() == track->sessionId()) {
3413 (void) track->setSyncEvent(event);
3414 return NO_ERROR;
3415 }
3416 }
3417
3418 return NAME_NOT_FOUND;
3419}
3420
Andy Hung4b17e882023-07-07 13:47:37 -07003421bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003422{
3423 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3424}
3425
Andy Hung4b17e882023-07-07 13:47:37 -07003426void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003427 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003428{
Andy Hungfe726a62018-09-27 15:17:25 -07003429 // Miscellaneous track cleanup when removed from the active list,
3430 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003431#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003432 for (const auto& track : tracksToRemove) {
3433 if (track->isExternalTrack()) {
3434 // to track the speaker usage
3435 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003436 }
3437 }
Andy Hungfe726a62018-09-27 15:17:25 -07003438#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003439}
3440
Andy Hung4b17e882023-07-07 13:47:37 -07003441void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003442{
3443 if (!mMasterMute) {
3444 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003445 if (mOutDeviceTypeAddrs.empty()) {
3446 ALOGD("ro.audio.silent is ignored since no output device is set");
3447 return;
3448 }
jiabinc52b1ff2019-10-31 17:20:42 -07003449 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003450 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3451 return;
3452 }
Eric Laurent81784c32012-11-19 14:55:58 -08003453 if (property_get("ro.audio.silent", value, "0") > 0) {
3454 char *endptr;
3455 unsigned long ul = strtoul(value, &endptr, 0);
3456 if (*endptr == '\0' && ul != 0) {
3457 ALOGD("Silence is golden");
3458 // The setprop command will not allow a property to be changed after
3459 // the first time it is set, so we don't have to worry about un-muting.
3460 setMasterMute_l(true);
3461 }
3462 }
3463 }
3464}
3465
3466// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003467ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003468{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003469 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003470 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003471 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003472 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003473
3474 // If an NBAIO sink is present, use it to write the normal mixer's submix
3475 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003476
Andy Hung010a1a12014-03-13 13:57:33 -07003477 const size_t count = mBytesRemaining / mFrameSize;
3478
Simon Wilson2d590962012-11-29 15:18:50 -08003479 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003480 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003481 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003482 if (screenState != mScreenState) {
3483 mScreenState = screenState;
3484 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3485 if (pipe != NULL) {
3486 pipe->setAvgFrames((mScreenState & 1) ?
3487 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3488 }
3489 }
Andy Hung010a1a12014-03-13 13:57:33 -07003490 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003491 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003492
Eric Laurent81784c32012-11-19 14:55:58 -08003493 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003494 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003495
Andy Hung8946a282018-04-19 20:04:56 -07003496#ifdef TEE_SINK
3497 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3498#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003499 } else {
3500 bytesWritten = framesWritten;
3501 }
3502 // otherwise use the HAL / AudioStreamOut directly
3503 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003504 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003505
Eric Laurentbfb1b832013-01-07 09:53:42 -08003506 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003507 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3508 mWriteAckSequence += 2;
3509 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003511 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003513 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003514 // FIXME We should have an implementation of timestamps for direct output threads.
3515 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003516 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003517 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003518
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519 if (mUseAsyncWrite &&
3520 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3521 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003522 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003523 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003524 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003525 }
Eric Laurent81784c32012-11-19 14:55:58 -08003526 }
3527
Eric Laurent81784c32012-11-19 14:55:58 -08003528 mNumWrites++;
3529 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003530 if (mStandby) {
3531 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003532 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003533 mStandby = false;
3534 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003535 return bytesWritten;
3536}
3537
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003538// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07003539void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003540 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003541{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003542 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003543 if (outputSink != nullptr) {
3544 outputSink->startMelComputation(processor);
3545 }
Vlad Popab042ee62022-10-20 18:05:00 +02003546}
3547
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003548// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07003549void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003550{
3551 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003552 if (outputSink != nullptr) {
3553 outputSink->stopMelComputation();
3554 }
Vlad Popab042ee62022-10-20 18:05:00 +02003555}
3556
Andy Hung4b17e882023-07-07 13:47:37 -07003557void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003559 bool supportsDrain = false;
3560 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003561 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3562 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003563 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3564 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003565 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003566 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003567 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003568 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003569 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003570 }
3571}
3572
Andy Hung4b17e882023-07-07 13:47:37 -07003573void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574{
Eric Laurent275e8e92014-11-30 15:14:47 -08003575 {
3576 Mutex::Autolock _l(mLock);
3577 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003578 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003579 track->invalidate();
3580 }
Andy Hungdae27702016-10-31 14:01:16 -07003581 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3582 // After we exit there are no more track changes sent to BatteryNotifier
3583 // because that requires an active threadLoop.
3584 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3585 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003586 }
Eric Laurent81784c32012-11-19 14:55:58 -08003587}
3588
3589/*
3590The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003591 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003592 - mActiveSleepTimeUs from activeSleepTimeUs()
3593 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003594 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3595 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003596 - maxPeriod from frame count and sample rate (MIXER only)
3597
3598The parameters that affect these derived values are:
3599 - frame count
3600 - frame size
3601 - sample rate
3602 - device type: A2DP or not
3603 - device latency
3604 - format: PCM or not
3605 - active sleep time
3606 - idle sleep time
3607*/
3608
Andy Hung4b17e882023-07-07 13:47:37 -07003609void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003610{
Andy Hung25c2dac2014-02-27 14:56:00 -08003611 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003612 mActiveSleepTimeUs = activeSleepTimeUs();
3613 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003614
Andy Hungd58c4732023-07-20 21:31:38 -07003615 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003616
Eric Laurent42537be2016-01-08 17:16:42 -08003617 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3618 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003619 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003620 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3621 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3622 }
3623 }
Eric Laurent81784c32012-11-19 14:55:58 -08003624}
3625
Andy Hung4b17e882023-07-07 13:47:37 -07003626bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003627{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003628 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003629 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003630 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003631 size_t size = mTracks.size();
3632 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003633 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003634 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003635 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003636 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003637 }
3638 }
Eric Laurent13084622016-05-17 10:51:49 -07003639 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003640}
3641
Andy Hung4b17e882023-07-07 13:47:37 -07003642void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003643{
3644 Mutex::Autolock _l(mLock);
3645 invalidateTracks_l(streamType);
3646}
3647
Andy Hung4b17e882023-07-07 13:47:37 -07003648void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003649 Mutex::Autolock _l(mLock);
3650 invalidateTracks_l(portIds);
3651}
3652
Andy Hung4b17e882023-07-07 13:47:37 -07003653bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003654 bool trackMatch = false;
3655 const size_t size = mTracks.size();
3656 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003657 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003658 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3659 t->invalidate();
3660 portIds.erase(t->portId());
3661 trackMatch = true;
3662 }
3663 if (portIds.empty()) {
3664 break;
3665 }
3666 }
3667 return trackMatch;
3668}
3669
jiabinf042b9b2021-05-07 23:46:28 +00003670// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003671IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003672 audio_port_handle_t trackPortId) {
3673 for (size_t i = 0; i < mTracks.size(); i++) {
3674 if (mTracks[i]->portId() == trackPortId) {
3675 return mTracks[i].get();
3676 }
3677 }
3678 return nullptr;
3679}
3680
Andy Hung4b17e882023-07-07 13:47:37 -07003681status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003682{
Glenn Kastend848eb42016-03-08 13:42:11 -08003683 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003684 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003685 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003686
Andy Hungd3639922022-04-28 18:00:49 -07003687 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003688 if (!audio_is_global_session(session)) {
3689 // player sessions on a spatializer output will use a dedicated input buffer and
3690 // will either output multi channel to mEffectBuffer if the track is spatilaized
3691 // or stereo to mPostSpatializerBuffer if not spatialized.
3692 uint32_t channelMask;
3693 bool isSessionSpatialized =
3694 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3695 if (isSessionSpatialized) {
3696 channelMask = mMixerChannelMask;
3697 } else {
3698 channelMask = mChannelMask;
3699 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003700 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003701 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003702 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003703 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003704 &halInBuffer);
3705 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003706
Andy Hung7535ed92023-07-17 17:05:00 -07003707 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003708 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3709 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3710 &halOutBuffer);
3711 if (result != OK) return result;
3712
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003713 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003714
Mikhail Naganov022b9952017-01-04 16:36:51 -08003715 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3716 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003717 } else {
3718 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3719 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3720 // mPostSpatializerBuffer as output buffer
3721 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003722 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003723 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3724 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003725 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003726 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3727 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003728
Eric Laurentb62d0362021-10-26 17:40:18 +02003729 if (session == AUDIO_SESSION_DEVICE) {
3730 halInBuffer = halOutBuffer;
3731 }
3732 }
3733 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003734 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003735 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3736 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3737 &halInBuffer);
3738 if (result != OK) return result;
3739 halOutBuffer = halInBuffer;
3740 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3741 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003742 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003743 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003744 // Only one effect chain can be present in direct output thread and it uses
3745 // the sink buffer as input
3746 if (mType != DIRECT) {
3747 size_t numSamples = mNormalFrameCount
3748 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3749 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003750 const status_t allocateStatus =
3751 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003752 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003753 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003754 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003755
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003756 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003757 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3758 buffer, session);
3759 }
3760 }
3761 }
3762
3763 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003764 // Attach all tracks with same session ID to this chain.
3765 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003766 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003767 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003768 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3769 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003770 track->setMainBuffer(buffer);
3771 chain->incTrackCnt();
3772 }
3773 }
3774
3775 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003776 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003777 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003778 ALOGV("addEffectChain_l() activating track %p on session %d",
3779 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003780 chain->incActiveTrackCnt();
3781 }
3782 }
3783 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003784
Eric Laurentaaa44472014-09-12 17:41:50 -07003785 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003786 chain->setInBuffer(halInBuffer);
3787 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003788 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3789 // chains list in order to be processed last as it contains output device effects.
3790 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3791 // processing effects specific to an output stream before effects applied to all streams
3792 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003793 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3794 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003795 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003796 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003797 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003798 // Effect chain for other sessions are inserted at beginning of effect
3799 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003800 // sessions is not important.
3801 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003802 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3803 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003804 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003805 size_t size = mEffectChains.size();
3806 size_t i = 0;
3807 for (i = 0; i < size; i++) {
3808 if (mEffectChains[i]->sessionId() < session) {
3809 break;
3810 }
3811 }
3812 mEffectChains.insertAt(chain, i);
3813 checkSuspendOnAddEffectChain_l(chain);
3814
3815 return NO_ERROR;
3816}
3817
Andy Hung4b17e882023-07-07 13:47:37 -07003818size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003819{
Glenn Kastend848eb42016-03-08 13:42:11 -08003820 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003821
3822 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3823
3824 for (size_t i = 0; i < mEffectChains.size(); i++) {
3825 if (chain == mEffectChains[i]) {
3826 mEffectChains.removeAt(i);
3827 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003828 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003829 if (session == track->sessionId()) {
3830 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3831 chain.get(), session);
3832 chain->decActiveTrackCnt();
3833 }
3834 }
3835
3836 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003837 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003838 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003839 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003840 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003841 chain->decTrackCnt();
3842 }
3843 }
3844 break;
3845 }
3846 }
3847 return mEffectChains.size();
3848}
3849
Andy Hung4b17e882023-07-07 13:47:37 -07003850status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003851 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003852{
3853 Mutex::Autolock _l(mLock);
3854 return attachAuxEffect_l(track, EffectId);
3855}
3856
Andy Hung4b17e882023-07-07 13:47:37 -07003857status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003858 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003859{
3860 status_t status = NO_ERROR;
3861
3862 if (EffectId == 0) {
3863 track->setAuxBuffer(0, NULL);
3864 } else {
3865 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003866 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003867 if (effect != 0) {
3868 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3869 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3870 } else {
3871 status = INVALID_OPERATION;
3872 }
3873 } else {
3874 status = BAD_VALUE;
3875 }
3876 }
3877 return status;
3878}
3879
Andy Hung4b17e882023-07-07 13:47:37 -07003880void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003881{
3882 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003883 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003884 if (track->auxEffectId() == effectId) {
3885 attachAuxEffect_l(track, 0);
3886 }
3887 }
3888}
3889
Andy Hung4b17e882023-07-07 13:47:37 -07003890bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003891NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003892{
Andy Hung78d8d952023-05-30 18:10:23 -07003893 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003894
Andy Hung11e74242023-06-26 19:20:57 -07003895 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003896
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003897 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003898 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003899
3900 // MIXER
3901 nsecs_t lastWarning = 0;
3902
3903 // DUPLICATING
3904 // FIXME could this be made local to while loop?
3905 writeFrames = 0;
3906
3907 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003908 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003909
Andy Hungd3639922022-04-28 18:00:49 -07003910 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003911 sleepTimeShift = 0;
3912 }
3913
3914 CpuStats cpuStats;
3915 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3916
3917 acquireWakeLock();
3918
Glenn Kasteneef598c2017-04-03 14:41:13 -07003919 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3920 // thread associated with this PlaybackThread.
3921 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3922 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003923 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3924 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003925 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003926 const char *logString = NULL;
3927
rago1bb90822017-05-02 18:31:48 -07003928 // Estimated time for next buffer to be written to hal. This is used only on
3929 // suspended mode (for now) to help schedule the wait time until next iteration.
3930 nsecs_t timeLoopNextNs = 0;
3931
Eric Laurent664539d2013-09-23 18:24:31 -07003932 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003933
Andy Hung2dbffc22018-08-08 18:50:41 -07003934 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003935
Eric Laurentb3f315a2021-07-13 15:09:05 +02003936 sendCheckOutputStageEffectsEvent();
3937
Andy Hung446f4df2019-02-21 12:26:41 -08003938 // loopCount is used for statistics and diagnostics.
3939 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003940 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003941 // Log merge requests are performed during AudioFlinger binder transactions, but
3942 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07003943 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003944
Eric Laurent81784c32012-11-19 14:55:58 -08003945 cpuStats.sample(myName);
3946
Andy Hung116bc262023-06-20 18:56:17 -07003947 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003948 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003949 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07003950 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003951
Andy Hung2dbffc22018-08-08 18:50:41 -07003952 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3953 //
jiabinc52b1ff2019-10-31 17:20:42 -07003954 // Note: we access outDeviceTypes() outside of mLock.
3955 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003956 // Here, we try for the AF lock, but do not block on it as the latency
3957 // is more informational.
Andy Hung85a07452023-08-28 18:36:53 -07003958 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd25fe392023-07-13 16:52:46 -07003959 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003960 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003961 status_t status = INVALID_OPERATION;
3962 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07003963 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07003964 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003965 && swPatches.size() > 0) {
3966 status = swPatches[0].getLatencyMs_l(&latencyMs);
3967 downstreamPatchHandle = swPatches[0].getPatchHandle();
3968 }
3969 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003970 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003971 lastDownstreamPatchHandle = downstreamPatchHandle;
3972 }
3973 if (status == OK) {
3974 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003975 // latency of 5 seconds).
3976 const double minLatency = 0., maxLatency = 5000.;
3977 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003978 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003979 } else {
3980 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003981 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003982 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003983 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003984 }
Andy Hung7535ed92023-07-17 17:05:00 -07003985 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003986 }
3987 } else {
3988 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3989 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003990 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003991 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3992 }
3993 }
3994
Eric Laurentb3f315a2021-07-13 15:09:05 +02003995 if (mCheckOutputStageEffects.exchange(false)) {
3996 checkOutputStageEffects();
3997 }
3998
Vlad Popa7e81cea2023-01-19 16:34:16 +01003999 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08004000 { // scope for mLock
4001
4002 Mutex::Autolock _l(mLock);
4003
Eric Laurent021cf962014-05-13 10:18:14 -07004004 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004005 if (mCheckOutputStageEffects.load()) {
4006 continue;
4007 }
Eric Laurent10351942014-05-08 18:49:52 -07004008
Glenn Kasteneef598c2017-04-03 14:41:13 -07004009 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08004010 if (logString != NULL) {
4011 mNBLogWriter->logTimestamp();
4012 mNBLogWriter->log(logString);
4013 logString = NULL;
4014 }
4015
Dean Wheatley12473e92021-03-18 23:00:55 +11004016 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004017
Eric Laurent81784c32012-11-19 14:55:58 -08004018 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004019 if (mSignalPending) {
4020 // A signal was raised while we were unlocked
4021 mSignalPending = false;
4022 } else if (waitingAsyncCallback_l()) {
4023 if (exitPending()) {
4024 break;
4025 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004026 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004027 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004028 releaseWakeLock_l();
4029 released = true;
4030 }
Andy Hung10cbff12017-02-21 17:30:14 -08004031
4032 const int64_t waitNs = computeWaitTimeNs_l();
4033 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
4034 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
4035 if (status == TIMED_OUT) {
4036 mSignalPending = true; // if timeout recheck everything
4037 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004038 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004039 if (released) {
4040 acquireWakeLock_l();
4041 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004042 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4043 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004044
4045 continue;
4046 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004047 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004048 isSuspended()) {
4049 // put audio hardware into standby after short delay
4050 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004051
4052 threadLoop_standby();
4053
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004054 // This is where we go into standby
4055 if (!mStandby) {
4056 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004057 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004058 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004059 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004060 }
Andy Hungd0979812019-02-21 15:51:44 -08004061 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004062 }
4063
Eric Tan39ec8d62018-07-24 09:49:29 -07004064 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004065 // we're about to wait, flush the binder command buffer
4066 IPCThreadState::self()->flushCommands();
4067
4068 clearOutputTracks();
4069
4070 if (exitPending()) {
4071 break;
4072 }
4073
4074 releaseWakeLock_l();
4075 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004076 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004077 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004078 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004079 acquireWakeLock_l();
4080
4081 mMixerStatus = MIXER_IDLE;
4082 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4083 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004084 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004085 checkSilentMode_l();
4086
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004087 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4088 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004089 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004090 sleepTimeShift = 0;
4091 }
4092
4093 continue;
4094 }
4095 }
Eric Laurent81784c32012-11-19 14:55:58 -08004096 // mMixerStatusIgnoringFastTracks is also updated internally
4097 mMixerStatus = prepareTracks_l(&tracksToRemove);
4098
Andy Hungdae27702016-10-31 14:01:16 -07004099 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004100
Vlad Popa7e81cea2023-01-19 16:34:16 +01004101 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004102
Eric Laurent81784c32012-11-19 14:55:58 -08004103 // prevent any changes in effect chain list and in each effect chain
4104 // during mixing and effect process as the audio buffers could be deleted
4105 // or modified if an effect is created or deleted
4106 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004107
4108 // Determine which session to pick up haptic data.
4109 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004110 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004111 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004112 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004113 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004114 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004115 if (effectChain != nullptr
4116 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004117 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004118 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004119 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004120 break;
4121 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004122 if (activeHapticSessionId == AUDIO_SESSION_NONE
4123 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004124 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004125 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004126 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004127 }
4128 }
4129 }
4130
Andy Hungc1646382019-04-30 16:12:10 -07004131 // Acquire a local copy of active tracks with lock (release w/o lock).
4132 //
4133 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4134 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4135 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4136 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004137
4138 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004139
Jiabin Huangfb476842022-12-06 03:18:10 +00004140 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004141 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004142 }
4143
Eric Laurent19952e12023-04-20 10:08:29 +02004144 // signal actual start of output stream when the render position reported by the kernel
4145 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004146 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4147 && (mKernelPositionOnStandby
4148 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004149 mHalStarted = true;
4150 mWaitHalStartCV.broadcast();
4151 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004152 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004153
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154 if (mBytesRemaining == 0) {
4155 mCurrentWriteLength = 0;
4156 if (mMixerStatus == MIXER_TRACKS_READY) {
4157 // threadLoop_mix() sets mCurrentWriteLength
4158 threadLoop_mix();
4159 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4160 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004161 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004162 // must be written to HAL
4163 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004164 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004165 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004166
4167 // Tally underrun frames as we are inserting 0s here.
4168 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004169 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004170 && !track->isStopped()
4171 && !track->isPaused()
4172 && !track->isTerminated()) {
4173 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4174 __func__, track->id(), track->getTrackStateAsString(),
4175 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004176 track->audioTrackServerProxy()->tallyUnderrunFrames(
4177 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004178 }
4179 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004180 }
4181 }
Andy Hung98ef9782014-03-04 14:46:50 -08004182 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004183 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004184 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004185 // or mSinkBuffer (if there are no effects and there is no data already copied to
4186 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004187 //
4188 // This is done pre-effects computation; if effects change to
4189 // support higher precision, this needs to move.
4190 //
4191 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004192 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004193 uint32_t mixerChannelCount = mEffectBufferValid ?
4194 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004195 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004196 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4197 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4198
David Li88ee0902022-06-22 10:01:21 +08004199 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4200 // do these processes after effects are applied.
4201 if (!mEffectBufferValid) {
4202 // mono blend occurs for mixer threads only (not direct or offloaded)
4203 // and is handled here if we're going directly to the sink.
4204 if (requireMonoBlend()) {
4205 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4206 mNormalFrameCount, true /*limit*/);
4207 }
Andy Hung2ddee192015-12-18 17:34:44 -08004208
David Li88ee0902022-06-22 10:01:21 +08004209 if (!hasFastMixer()) {
4210 // Balance must take effect after mono conversion.
4211 // We do it here if there is no FastMixer.
4212 // mBalance detects zero balance within the class for speed
4213 // (not needed here).
4214 mBalance.setBalance(mMasterBalance.load());
4215 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4216 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004217 }
4218
Andy Hung98ef9782014-03-04 14:46:50 -08004219 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004220 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004221
4222 // If we're going directly to the sink and there are haptic channels,
4223 // we should adjust channels as the sample data is partially interleaved
4224 // in this case.
4225 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4226 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4227 mChannelCount + mHapticChannelCount,
4228 audio_bytes_per_sample(format),
4229 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4230 }
Andy Hung98ef9782014-03-04 14:46:50 -08004231 }
4232
Eric Laurentbfb1b832013-01-07 09:53:42 -08004233 mBytesRemaining = mCurrentWriteLength;
4234 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004235 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4236 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4237 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4238 mBytesWritten += mBytesRemaining;
4239 mFramesWritten += framesRemaining;
4240 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004241 mBytesRemaining = 0;
4242 }
Eric Laurent81784c32012-11-19 14:55:58 -08004243
Eric Laurentbfb1b832013-01-07 09:53:42 -08004244 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004245 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004246 for (size_t i = 0; i < effectChains.size(); i ++) {
4247 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004248 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004249 if (activeHapticSessionId != AUDIO_SESSION_NONE
4250 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004251 // Haptic data is active in this case, copy it directly from
4252 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004253 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4254 audio_channel_count_from_out_mask(mMixerChannelMask) :
4255 mChannelCount;
4256 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4257 hapticSessionChannelCount = mChannelCount;
4258 }
4259
jiabin47affe52019-04-04 18:02:07 -07004260 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004261 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004262 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004263 memcpy_by_audio_format(
4264 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004265 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004266 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004267 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004268 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004269 }
Eric Laurent81784c32012-11-19 14:55:58 -08004270 }
4271 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004272 // Process effect chains for offloaded thread even if no audio
4273 // was read from audio track: process only updates effect state
4274 // and thus does have to be synchronized with audio writes but may have
4275 // to be called while waiting for async write callback
4276 if (mType == OFFLOAD) {
4277 for (size_t i = 0; i < effectChains.size(); i ++) {
4278 effectChains[i]->process_l();
4279 }
4280 }
Eric Laurent81784c32012-11-19 14:55:58 -08004281
Andy Hung98ef9782014-03-04 14:46:50 -08004282 // Only if the Effects buffer is enabled and there is data in the
4283 // Effects buffer (buffer valid), we need to
4284 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004285 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004286 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004287 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004288 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004289 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004290 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004291 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004292 }
4293
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004294 if (!hasFastMixer()) {
4295 // Balance must take effect after mono conversion.
4296 // We do it here if there is no FastMixer.
4297 // mBalance detects zero balance within the class for speed (not needed here).
4298 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004299 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004300 }
4301
Eric Laurentb62d0362021-10-26 17:40:18 +02004302 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4303 // mPostSpatializerBuffer if the haptics track is spatialized.
4304 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4305 // For other thread types, the haptics channels are already in mEffectBuffer.
4306 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4307 const size_t srcBufferSize = mNormalFrameCount *
4308 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4309 mEffectBufferFormat);
4310 const size_t dstBufferSize = mNormalFrameCount
4311 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4312
4313 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4314 mEffectBufferFormat,
4315 (uint8_t*)mEffectBuffer + srcBufferSize,
4316 mEffectBufferFormat,
4317 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004318 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004319 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4320 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4321 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4322 // Clamp PCM float values more than this distance from 0 to insulate
4323 // a HAL which doesn't handle NaN correctly.
4324 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4325 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4326 static_cast<const float*>(effectBuffer),
4327 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4328 } else {
4329 memcpy_by_audio_format(mSinkBuffer, mFormat,
4330 effectBuffer, mEffectBufferFormat, framesToCopy);
4331 }
jiabin245cdd92018-12-07 17:55:15 -08004332 // The sample data is partially interleaved when haptic channels exist,
4333 // we need to adjust channels here.
4334 if (mHapticChannelCount > 0) {
4335 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4336 mChannelCount + mHapticChannelCount,
4337 audio_bytes_per_sample(mFormat),
4338 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4339 }
Andy Hung98ef9782014-03-04 14:46:50 -08004340 }
4341
Eric Laurent81784c32012-11-19 14:55:58 -08004342 // enable changes in effect chain
4343 unlockEffectChains(effectChains);
4344
Vlad Popafce10862023-02-03 10:37:07 +01004345 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004346 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004347 metadataUpdate.playbackMetadataUpdate);
4348 }
4349
Eric Laurentbfb1b832013-01-07 09:53:42 -08004350 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004351 // mSleepTimeUs == 0 means we must write to audio hardware
4352 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004353 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004354 // writePeriodNs is updated >= 0 when ret > 0.
4355 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004357 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004358 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004359 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004360 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004361 if (ret < 0) {
4362 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004363 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004364 mBytesWritten += ret;
4365 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004366 const int64_t frames = ret / mFrameSize;
4367 mFramesWritten += frames;
4368
4369 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4370 // process information relating to write time.
4371 if (audio_has_proportional_frames(mFormat)) {
4372 // we are in a continuous mixing cycle
4373 if (mMixerStatus == MIXER_TRACKS_READY &&
4374 loopCount == lastLoopCountWritten + 1) {
4375
4376 const double jitterMs =
4377 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4378 {frames, writePeriodNs},
4379 {0, 0} /* lastTimestamp */, mSampleRate);
4380 const double processMs =
4381 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4382
4383 Mutex::Autolock _l(mLock);
4384 mIoJitterMs.add(jitterMs);
4385 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004386
4387 if (mPipeSink.get() != nullptr) {
4388 // Using the Monopipe availableToWrite, we estimate the current
4389 // buffer size.
4390 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4391 const ssize_t
4392 availableToWrite = mPipeSink->availableToWrite();
4393 const size_t pipeFrames = monoPipe->maxFrames();
4394 const size_t
4395 remainingFrames = pipeFrames - max(availableToWrite, 0);
4396 mMonopipePipeDepthStats.add(remainingFrames);
4397 }
Andy Hung446f4df2019-02-21 12:26:41 -08004398 }
4399
4400 // write blocked detection
4401 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004402 if ((mType == MIXER || mType == SPATIALIZER)
4403 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004404 mNumDelayedWrites++;
4405 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4406 ATRACE_NAME("underrun");
4407 ALOGW("write blocked for %lld msecs, "
4408 "%d delayed writes, thread %d",
4409 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4410 mNumDelayedWrites, mId);
4411 lastWarning = lastIoEndNs;
4412 }
4413 }
4414 }
4415 // update timing info.
4416 mLastIoBeginNs = lastIoBeginNs;
4417 mLastIoEndNs = lastIoEndNs;
4418 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004419 }
4420 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4421 (mMixerStatus == MIXER_DRAIN_ALL)) {
4422 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004423 }
Andy Hungd3639922022-04-28 18:00:49 -07004424 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004425
4426 if (mThreadThrottle
4427 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004428 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004429 // Limit MixerThread data processing to no more than twice the
4430 // expected processing rate.
4431 //
4432 // This helps prevent underruns with NuPlayer and other applications
4433 // which may set up buffers that are close to the minimum size, or use
4434 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4435 //
4436 // The throttle smooths out sudden large data drains from the device,
4437 // e.g. when it comes out of standby, which often causes problems with
4438 // (1) mixer threads without a fast mixer (which has its own warm-up)
4439 // (2) minimum buffer sized tracks (even if the track is full,
4440 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004441 //
4442 // Total time spent in last processing cycle equals time spent in
4443 // 1. threadLoop_write, as well as time spent in
4444 // 2. threadLoop_mix (significant for heavy mixing, especially
4445 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004446
Andy Hung446f4df2019-02-21 12:26:41 -08004447 // it's OK if deltaMs is an overestimate.
4448
4449 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004450
Ivan Lozanoea04d392017-11-07 14:37:07 -08004451 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004452 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004453 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004454
Andy Hung08fb1742015-05-31 23:22:10 -07004455 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004456 // notify of throttle start on verbose log
4457 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4458 "mixer(%p) throttle begin:"
4459 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004460 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004461 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004462 // Throttle must be attributed to the previous mixer loop's write time
4463 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004464 // This also ensures proper timing statistics.
4465 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004466 } else {
4467 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4468 if (diff > 0) {
4469 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004470 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004471 ALOGD_IF(!isSingleDeviceType(
4472 outDeviceTypes(), audio_is_a2dp_out_device) &&
4473 !isSingleDeviceType(
4474 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004475 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004476 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4477 }
Andy Hung08fb1742015-05-31 23:22:10 -07004478 }
4479 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480 }
Eric Laurent81784c32012-11-19 14:55:58 -08004481
Eric Laurentbfb1b832013-01-07 09:53:42 -08004482 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004483 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004484 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004485 // suspended requires accurate metering of sleep time.
4486 if (isSuspended()) {
4487 // advance by expected sleepTime
4488 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4489 const nsecs_t nowNs = systemTime();
4490
4491 // compute expected next time vs current time.
4492 // (negative deltas are treated as delays).
4493 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4494 if (deltaNs < -kMaxNextBufferDelayNs) {
4495 // Delays longer than the max allowed trigger a reset.
4496 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4497 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4498 timeLoopNextNs = nowNs + deltaNs;
4499 } else if (deltaNs < 0) {
4500 // Delays within the max delay allowed: zero the delta/sleepTime
4501 // to help the system catch up in the next iteration(s)
4502 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4503 deltaNs = 0;
4504 }
4505 // update sleep time (which is >= 0)
4506 mSleepTimeUs = deltaNs / 1000;
4507 }
Eric Laurente93cc032016-05-05 10:15:10 -07004508 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4509 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004510 }
Glenn Kastene7754022014-10-31 12:11:26 -07004511 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004512 }
Eric Laurent81784c32012-11-19 14:55:58 -08004513 }
4514
4515 // Finally let go of removed track(s), without the lock held
4516 // since we can't guarantee the destructors won't acquire that
4517 // same lock. This will also mutate and push a new fast mixer state.
4518 threadLoop_removeTracks(tracksToRemove);
4519 tracksToRemove.clear();
4520
4521 // FIXME I don't understand the need for this here;
4522 // it was in the original code but maybe the
4523 // assignment in saveOutputTracks() makes this unnecessary?
4524 clearOutputTracks();
4525
4526 // Effect chains will be actually deleted here if they were removed from
4527 // mEffectChains list during mixing or effects processing
4528 effectChains.clear();
4529
4530 // FIXME Note that the above .clear() is no longer necessary since effectChains
4531 // is now local to this block, but will keep it for now (at least until merge done).
4532 }
4533
Eric Laurentbfb1b832013-01-07 09:53:42 -08004534 threadLoop_exit();
4535
Eric Laurentcf817a22014-08-04 20:36:31 -07004536 if (!mStandby) {
4537 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004538 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004539 }
4540
4541 releaseWakeLock();
4542
4543 ALOGV("Thread %p type %d exiting", this, mType);
4544 return false;
4545}
4546
Andy Hung4b17e882023-07-07 13:47:37 -07004547void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004548{
Dean Wheatley12473e92021-03-18 23:00:55 +11004549 if (mStandby) {
4550 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4551 return;
4552 } else if (mHwPaused) {
4553 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4554 return;
4555 }
4556
4557 // Gather the framesReleased counters for all active tracks,
4558 // and associate with the sink frames written out. We need
4559 // this to convert the sink timestamp to the track timestamp.
4560 bool kernelLocationUpdate = false;
4561 ExtendedTimestamp timestamp; // use private copy to fetch
4562
4563 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4564 // HAL may be draining some small duration buffered data for fade out.
4565 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4566 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4567 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4568 mSampleRate);
4569
4570 if (isTimestampCorrectionEnabled()) {
4571 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4572 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4573 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4574 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4575 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4576 = correctedTimestamp.mFrames;
4577 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4578 = correctedTimestamp.mTimeNs;
4579 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4580 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4581 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4582
4583 // Note: Downstream latency only added if timestamp correction enabled.
4584 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4585 const int64_t newPosition =
4586 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4587 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4588 // prevent retrograde
4589 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4590 newPosition,
4591 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4592 - mSuspendedFrames));
4593 }
4594 }
4595
4596 // We always fetch the timestamp here because often the downstream
4597 // sink will block while writing.
4598
4599 // We keep track of the last valid kernel position in case we are in underrun
4600 // and the normal mixer period is the same as the fast mixer period, or there
4601 // is some error from the HAL.
4602 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4603 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4604 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4605 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4606 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4607
4608 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4609 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4610 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4611 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4612 }
4613
4614 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4615 kernelLocationUpdate = true;
4616 } else {
4617 ALOGVV("getTimestamp error - no valid kernel position");
4618 }
4619
4620 // copy over kernel info
4621 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4622 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4623 + mSuspendedFrames; // add frames discarded when suspended
4624 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4625 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4626 } else {
4627 mTimestampVerifier.error();
4628 }
4629
4630 // mFramesWritten for non-offloaded tracks are contiguous
4631 // even after standby() is called. This is useful for the track frame
4632 // to sink frame mapping.
4633 bool serverLocationUpdate = false;
4634 if (mFramesWritten != mLastFramesWritten) {
4635 serverLocationUpdate = true;
4636 mLastFramesWritten = mFramesWritten;
4637 }
4638 // Only update timestamps if there is a meaningful change.
4639 // Either the kernel timestamp must be valid or we have written something.
4640 if (kernelLocationUpdate || serverLocationUpdate) {
4641 if (serverLocationUpdate) {
4642 // use the time before we called the HAL write - it is a bit more accurate
4643 // to when the server last read data than the current time here.
4644 //
4645 // If we haven't written anything, mLastIoBeginNs will be -1
4646 // and we use systemTime().
4647 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4648 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4649 ? systemTime() : mLastIoBeginNs;
4650 }
4651
Andy Hung11e74242023-06-26 19:20:57 -07004652 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004653 if (!t->isFastTrack()) {
4654 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004655 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004656 mFramesWritten,
4657 mSampleRate,
4658 mTimestamp);
4659 }
4660 }
4661 }
4662
4663 if (audio_has_proportional_frames(mFormat)) {
4664 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4665 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4666 mLatencyMs.add(latencyMs);
4667 }
4668 }
4669#if 0
4670 // logFormat example
4671 if (z % 100 == 0) {
4672 timespec ts;
4673 clock_gettime(CLOCK_MONOTONIC, &ts);
4674 LOGT("This is an integer %d, this is a float %f, this is my "
4675 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4676 LOGT("A deceptive null-terminated string %\0");
4677 }
4678 ++z;
4679#endif
4680}
4681
Eric Laurentbfb1b832013-01-07 09:53:42 -08004682// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07004683void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung920f6572022-10-06 12:09:49 -07004684NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004685{
Andy Hungfe726a62018-09-27 15:17:25 -07004686 for (const auto& track : tracksToRemove) {
4687 mActiveTracks.remove(track);
4688 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004689 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004690 if (chain != 0) {
4691 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4692 __func__, track->id(), chain.get(), track->sessionId());
4693 chain->decActiveTrackCnt();
4694 }
4695 // If an external client track, inform APM we're no longer active, and remove if needed.
4696 // We do this under lock so that the state is consistent if the Track is destroyed.
4697 if (track->isExternalTrack()) {
4698 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004699 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004700 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004701 }
4702 }
Andy Hungfe726a62018-09-27 15:17:25 -07004703 if (track->isTerminated()) {
4704 // remove from our tracks vector
4705 removeTrack_l(track);
4706 }
jiabineb3bda02020-06-30 14:07:03 -07004707 if (mHapticChannelCount > 0 &&
4708 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4709 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004710 mLock.unlock();
4711 // Unlock due to VibratorService will lock for this call and will
4712 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004713 afutils::onExternalVibrationStop(track->getExternalVibration());
jiabin57303cc2018-12-18 15:45:57 -08004714 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004715
4716 // When the track is stop, set the haptic intensity as MUTE
4717 // for the HapticGenerator effect.
4718 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004719 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004720 }
jiabin245cdd92018-12-07 17:55:15 -08004721 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004722 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004723}
Eric Laurent81784c32012-11-19 14:55:58 -08004724
Andy Hung4b17e882023-07-07 13:47:37 -07004725status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004726{
4727 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004728 ExtendedTimestamp ets;
4729 status_t status = mNormalSink->getTimestamp(ets);
4730 if (status == NO_ERROR) {
4731 status = ets.getBestTimestamp(&timestamp);
4732 }
4733 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004734 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004735 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004736 collectTimestamps_l();
4737 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4738 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004739 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004740 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4741 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4742 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4743 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4744 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004745 }
4746 return INVALID_OPERATION;
4747}
Eric Laurent1c333e22014-05-20 10:48:17 -07004748
Eric Laurenteab90452019-06-24 15:17:46 -07004749// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4750// still applied by the mixer.
4751// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4752// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4753// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004754status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004755{
4756 status_t result = NO_ERROR;
4757 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4758 if (*volume != mLeftVolFloat) {
4759 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004760 // HAL can return INVALID_OPERATION if operation is not supported.
4761 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004762 "Error when setting output stream volume: %d", result);
4763 if (result == NO_ERROR) {
4764 mLeftVolFloat = *volume;
4765 }
4766 }
4767 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4768 // remove stream volume contribution from software volume.
4769 if (mLeftVolFloat == *volume) {
4770 *volume = 1.0f;
4771 }
4772 }
4773 return result;
4774}
4775
Andy Hung4b17e882023-07-07 13:47:37 -07004776status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004777 audio_patch_handle_t *handle)
4778{
Andy Hungf60abce2016-08-26 11:37:54 -07004779 status_t status;
4780 if (property_get_bool("af.patch_park", false /* default_value */)) {
4781 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4782 // or if HAL does not properly lock against access.
4783 AutoPark<FastMixer> park(mFastMixer);
4784 status = PlaybackThread::createAudioPatch_l(patch, handle);
4785 } else {
4786 status = PlaybackThread::createAudioPatch_l(patch, handle);
4787 }
Eric Laurentb0463942022-12-20 16:31:10 +01004788
4789 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004790 return status;
4791}
4792
Andy Hung4b17e882023-07-07 13:47:37 -07004793status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004794 audio_patch_handle_t *handle)
4795{
4796 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004797
4798 // store new device and send to effects
4799 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004800 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004801 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004802 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4803 && !mOutput->audioHwDev->supportsAudioPatches(),
4804 "Enumerated device type(%#x) must not be used "
4805 "as it does not support audio patches",
4806 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004807 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004808 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4809 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004810 }
4811
François Gaffie0c280aa2018-07-25 10:02:15 +02004812 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004813#ifdef ADD_BATTERY_DATA
4814 // when changing the audio output device, call addBatteryData to notify
4815 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004816 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004817 uint32_t params = 0;
4818 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004819 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004820 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004821 }
4822
Eric Laurent054d9d32015-04-24 08:48:48 -07004823 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004824 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004825 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4826 }
4827
4828 if (params != 0) {
4829 addBatteryData(params);
4830 }
4831 }
4832#endif
4833
4834 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004835 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004836 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004837
jiabinc52b1ff2019-10-31 17:20:42 -07004838 // mPatch.num_sinks is not set when the thread is created so that
4839 // the first patch creation triggers an ioConfigChanged callback
4840 bool configChanged = (mPatch.num_sinks == 0) ||
4841 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004842 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004843 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004844 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004845
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004846 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004847 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4848 status = hwDevice->createAudioPatch(patch->num_sources,
4849 patch->sources,
4850 patch->num_sinks,
4851 patch->sinks,
4852 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004853 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004854 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004855 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004856 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004857 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004858
4859 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004860 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004861 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004862 // also dispatch to active AudioTracks for MediaMetrics
4863 for (const auto &track : mActiveTracks) {
4864 track->logEndInterval();
4865 track->logBeginInterval(patchSinksAsString);
4866 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004867
Eric Laurente8726fe2015-06-26 09:39:24 -07004868 if (configChanged) {
4869 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4870 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004871 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004872 mActiveTracks.setHasChanged();
4873
Eric Laurent1c333e22014-05-20 10:48:17 -07004874 return status;
4875}
4876
Andy Hung4b17e882023-07-07 13:47:37 -07004877status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004878{
Andy Hungf60abce2016-08-26 11:37:54 -07004879 status_t status;
4880 if (property_get_bool("af.patch_park", false /* default_value */)) {
4881 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4882 // or if HAL does not properly lock against access.
4883 AutoPark<FastMixer> park(mFastMixer);
4884 status = PlaybackThread::releaseAudioPatch_l(handle);
4885 } else {
4886 status = PlaybackThread::releaseAudioPatch_l(handle);
4887 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004888 return status;
4889}
4890
Andy Hung4b17e882023-07-07 13:47:37 -07004891status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004892{
4893 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004894
jiabinc52b1ff2019-10-31 17:20:42 -07004895 mPatch = audio_patch{};
4896 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004897
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004898 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004899 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4900 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004901 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004902 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004903 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004904 // Force meteadata update after a route change
4905 mActiveTracks.setHasChanged();
4906
Eric Laurent1c333e22014-05-20 10:48:17 -07004907 return status;
4908}
4909
Andy Hung4b17e882023-07-07 13:47:37 -07004910void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004911{
4912 Mutex::Autolock _l(mLock);
4913 mTracks.add(track);
4914}
4915
Andy Hung4b17e882023-07-07 13:47:37 -07004916void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004917{
4918 Mutex::Autolock _l(mLock);
4919 destroyTrack_l(track);
4920}
4921
Andy Hung4b17e882023-07-07 13:47:37 -07004922void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004923{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004924 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004925 config->role = AUDIO_PORT_ROLE_SOURCE;
4926 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4927 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004928 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4929 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4930 config->flags.output = mOutput->flags;
4931 }
Eric Laurent83b88082014-06-20 18:31:16 -07004932}
4933
Eric Laurent81784c32012-11-19 14:55:58 -08004934// ----------------------------------------------------------------------------
4935
Andy Hung4b17e882023-07-07 13:47:37 -07004936/* static */
4937sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07004938 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07004939 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07004940 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07004941}
4942
Andy Hung7535ed92023-07-17 17:05:00 -07004943MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004944 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07004945 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004946 // mAudioMixer below
4947 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004948 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004949 mFastMixerFutex(0),
4950 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004951 // mOutputSink below
4952 // mPipeSink below
4953 // mNormalSink below
4954{
Andy Hung7535ed92023-07-17 17:05:00 -07004955 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004956 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004957 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004958 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004959 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4960 mNormalFrameCount);
4961 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4962
Andy Hungfbfc3952015-01-15 13:33:51 -08004963 if (type == DUPLICATING) {
4964 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4965 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4966 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4967 return;
4968 }
Eric Laurent81784c32012-11-19 14:55:58 -08004969 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004970 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004971 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004972 const NBAIO_Format offers[1] = {Format_from_SR_C(
4973 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004974#if !LOG_NDEBUG
4975 ssize_t index =
4976#else
4977 (void)
4978#endif
4979 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004980 ALOG_ASSERT(index == 0);
4981
4982 // initialize fast mixer depending on configuration
4983 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004984 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004985 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004986 } else {
4987 switch (kUseFastMixer) {
4988 case FastMixer_Never:
4989 initFastMixer = false;
4990 break;
4991 case FastMixer_Always:
4992 initFastMixer = true;
4993 break;
4994 case FastMixer_Static:
4995 case FastMixer_Dynamic:
4996 initFastMixer = mFrameCount < mNormalFrameCount;
4997 break;
4998 }
4999 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5000 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5001 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005002 }
5003 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005004 audio_format_t fastMixerFormat;
5005 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5006 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5007 } else {
5008 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5009 }
5010 if (mFormat != fastMixerFormat) {
5011 // change our Sink format to accept our intermediate precision
5012 mFormat = fastMixerFormat;
5013 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005014 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005015 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5016 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5017 }
Eric Laurent81784c32012-11-19 14:55:58 -08005018
5019 // create a MonoPipe to connect our submix to FastMixer
5020 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005021
Andy Hung1258c1a2014-05-23 21:22:17 -07005022 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005023 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005024 format.mFormat = fastMixerFormat;
5025 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5026
Eric Laurent81784c32012-11-19 14:55:58 -08005027 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5028 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5029 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5030 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005031 const NBAIO_Format offersFast[1] = {format};
5032 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005033#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005034 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005035#else
5036 (void)
5037#endif
Andy Hung920f6572022-10-06 12:09:49 -07005038 monoPipe->negotiate(offersFast, std::size(offersFast),
5039 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005040 ALOG_ASSERT(index == 0);
5041 monoPipe->setAvgFrames((mScreenState & 1) ?
5042 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5043 mPipeSink = monoPipe;
5044
Eric Laurent81784c32012-11-19 14:55:58 -08005045 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005046 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005047 FastMixerStateQueue *sq = mFastMixer->sq();
5048#ifdef STATE_QUEUE_DUMP
5049 sq->setObserverDump(&mStateQueueObserverDump);
5050 sq->setMutatorDump(&mStateQueueMutatorDump);
5051#endif
5052 FastMixerState *state = sq->begin();
5053 FastTrack *fastTrack = &state->mFastTracks[0];
5054 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5055 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5056 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005057 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5058 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5059 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005060 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005061 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005062 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005063 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005064 fastTrack->mGeneration++;
5065 state->mFastTracksGen++;
5066 state->mTrackMask = 1;
5067 // fast mixer will use the HAL output sink
5068 state->mOutputSink = mOutputSink.get();
5069 state->mOutputSinkGen++;
5070 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005071 // specify sink channel mask when haptic channel mask present as it can not
5072 // be calculated directly from channel count
5073 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005074 ? AUDIO_CHANNEL_NONE
5075 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005076 state->mCommand = FastMixerState::COLD_IDLE;
5077 // already done in constructor initialization list
5078 //mFastMixerFutex = 0;
5079 state->mColdFutexAddr = &mFastMixerFutex;
5080 state->mColdGen++;
5081 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005082 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005083 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005084 sq->end();
5085 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5086
Eric Tan0513b5d2018-09-17 10:32:48 -07005087 NBLog::thread_info_t info;
5088 info.id = mId;
5089 info.type = NBLog::FASTMIXER;
5090 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5091
Eric Laurent81784c32012-11-19 14:55:58 -08005092 // start the fast mixer
5093 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5094 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005095 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005096 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005097
5098#ifdef AUDIO_WATCHDOG
5099 // create and start the watchdog
5100 mAudioWatchdog = new AudioWatchdog();
5101 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5102 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5103 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005104 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005105#endif
Andy Hung8946a282018-04-19 20:04:56 -07005106 } else {
5107#ifdef TEE_SINK
5108 // Only use the MixerThread tee if there is no FastMixer.
5109 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5110 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5111#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005112 }
5113
5114 switch (kUseFastMixer) {
5115 case FastMixer_Never:
5116 case FastMixer_Dynamic:
5117 mNormalSink = mOutputSink;
5118 break;
5119 case FastMixer_Always:
5120 mNormalSink = mPipeSink;
5121 break;
5122 case FastMixer_Static:
5123 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5124 break;
5125 }
5126}
5127
Andy Hung4b17e882023-07-07 13:47:37 -07005128MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005129{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005130 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005131 FastMixerStateQueue *sq = mFastMixer->sq();
5132 FastMixerState *state = sq->begin();
5133 if (state->mCommand == FastMixerState::COLD_IDLE) {
5134 int32_t old = android_atomic_inc(&mFastMixerFutex);
5135 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005136 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005137 }
5138 }
5139 state->mCommand = FastMixerState::EXIT;
5140 sq->end();
5141 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5142 mFastMixer->join();
5143 // Though the fast mixer thread has exited, it's state queue is still valid.
5144 // We'll use that extract the final state which contains one remaining fast track
5145 // corresponding to our sub-mix.
5146 state = sq->begin();
5147 ALOG_ASSERT(state->mTrackMask == 1);
5148 FastTrack *fastTrack = &state->mFastTracks[0];
5149 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5150 delete fastTrack->mBufferProvider;
5151 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005152 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005153#ifdef AUDIO_WATCHDOG
5154 if (mAudioWatchdog != 0) {
5155 mAudioWatchdog->requestExit();
5156 mAudioWatchdog->requestExitAndWait();
5157 mAudioWatchdog.clear();
5158 }
5159#endif
5160 }
Andy Hung7535ed92023-07-17 17:05:00 -07005161 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005162 delete mAudioMixer;
5163}
5164
Andy Hung4b17e882023-07-07 13:47:37 -07005165void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005166 PlaybackThread::onFirstRef();
5167
5168 Mutex::Autolock _l(mLock);
5169 if (mOutput != nullptr && mOutput->stream != nullptr) {
5170 status_t status = mOutput->stream->setLatencyModeCallback(this);
5171 if (status != INVALID_OPERATION) {
5172 updateHalSupportedLatencyModes_l();
5173 }
5174 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5175 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5176 mBluetoothLatencyModesEnabled.store(
5177 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5178 }
5179}
Eric Laurent81784c32012-11-19 14:55:58 -08005180
Andy Hung4b17e882023-07-07 13:47:37 -07005181uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005182{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005183 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005184 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5185 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5186 }
5187 return latency;
5188}
5189
Andy Hung4b17e882023-07-07 13:47:37 -07005190ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005191{
5192 // FIXME we should only do one push per cycle; confirm this is true
5193 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005194 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005195 FastMixerStateQueue *sq = mFastMixer->sq();
5196 FastMixerState *state = sq->begin();
5197 if (state->mCommand != FastMixerState::MIX_WRITE &&
5198 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5199 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005200
5201 // FIXME workaround for first HAL write being CPU bound on some devices
5202 ATRACE_BEGIN("write");
5203 mOutput->write((char *)mSinkBuffer, 0);
5204 ATRACE_END();
5205
Eric Laurent81784c32012-11-19 14:55:58 -08005206 int32_t old = android_atomic_inc(&mFastMixerFutex);
5207 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005208 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005209 }
5210#ifdef AUDIO_WATCHDOG
5211 if (mAudioWatchdog != 0) {
5212 mAudioWatchdog->resume();
5213 }
5214#endif
5215 }
5216 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005217#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005218 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005219 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005220#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005221 sq->end();
5222 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5223 if (kUseFastMixer == FastMixer_Dynamic) {
5224 mNormalSink = mPipeSink;
5225 }
5226 } else {
5227 sq->end(false /*didModify*/);
5228 }
5229 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005231}
5232
Andy Hung4b17e882023-07-07 13:47:37 -07005233void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005234{
5235 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005236 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005237 FastMixerStateQueue *sq = mFastMixer->sq();
5238 FastMixerState *state = sq->begin();
5239 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005240 // Report any frames trapped in the Monopipe
5241 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5242 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5243 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5244 "monoPipeWritten:%lld monoPipeLeft:%lld",
5245 (long long)mFramesWritten, (long long)mSuspendedFrames,
5246 (long long)mPipeSink->framesWritten(), pipeFrames);
5247 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5248
Eric Laurent81784c32012-11-19 14:55:58 -08005249 state->mCommand = FastMixerState::COLD_IDLE;
5250 state->mColdFutexAddr = &mFastMixerFutex;
5251 state->mColdGen++;
5252 mFastMixerFutex = 0;
5253 sq->end();
5254 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5255 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5256 if (kUseFastMixer == FastMixer_Dynamic) {
5257 mNormalSink = mOutputSink;
5258 }
5259#ifdef AUDIO_WATCHDOG
5260 if (mAudioWatchdog != 0) {
5261 mAudioWatchdog->pause();
5262 }
5263#endif
5264 } else {
5265 sq->end(false /*didModify*/);
5266 }
5267 }
5268 PlaybackThread::threadLoop_standby();
5269}
5270
Andy Hung4b17e882023-07-07 13:47:37 -07005271bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005272{
5273 return false;
5274}
5275
Andy Hung4b17e882023-07-07 13:47:37 -07005276bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005277{
5278 return !mStandby;
5279}
5280
Andy Hung4b17e882023-07-07 13:47:37 -07005281bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005282{
5283 Mutex::Autolock _l(mLock);
5284 return waitingAsyncCallback_l();
5285}
5286
Eric Laurent81784c32012-11-19 14:55:58 -08005287// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005288void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005289{
5290 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005291 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005293 // discard any pending drain or write ack by incrementing sequence
5294 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5295 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005296 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005297 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5298 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005300 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005301 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005302}
5303
Andy Hung4b17e882023-07-07 13:47:37 -07005304void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005305{
5306 ALOGV("signal playback thread");
5307 broadcast_l();
5308}
5309
Andy Hung4b17e882023-07-07 13:47:37 -07005310void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005311{
5312 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5313 invalidateTracks((audio_stream_type_t)i);
5314 }
5315}
5316
Andy Hung4b17e882023-07-07 13:47:37 -07005317void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005318{
Eric Laurent81784c32012-11-19 14:55:58 -08005319 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005320 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005321 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005322 // increase sleep time progressively when application underrun condition clears.
5323 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5324 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5325 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005326 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005327 sleepTimeShift--;
5328 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005329 mSleepTimeUs = 0;
5330 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005331 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005332
Eric Laurent81784c32012-11-19 14:55:58 -08005333}
5334
Andy Hung4b17e882023-07-07 13:47:37 -07005335void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005336{
5337 // If no tracks are ready, sleep once for the duration of an output
5338 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005339 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005340 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005341 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5342 // Using the Monopipe availableToWrite, we estimate the
5343 // sleep time to retry for more data (before we underrun).
5344 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5345 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5346 const size_t pipeFrames = monoPipe->maxFrames();
5347 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5348 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5349 const size_t framesDelay = std::min(
5350 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5351 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5352 pipeFrames, framesLeft, framesDelay);
5353 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5354 } else {
5355 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5356 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5357 mSleepTimeUs = kMinThreadSleepTimeUs;
5358 }
5359 // reduce sleep time in case of consecutive application underruns to avoid
5360 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5361 // duration we would end up writing less data than needed by the audio HAL if
5362 // the condition persists.
5363 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5364 sleepTimeShift++;
5365 }
Eric Laurent81784c32012-11-19 14:55:58 -08005366 }
5367 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005368 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005369 }
5370 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005371 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5372 // before effects processing or output.
5373 if (mMixerBufferValid) {
5374 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005375 if (mType == SPATIALIZER) {
5376 memset(mSinkBuffer, 0, mSinkBufferSize);
5377 }
Andy Hung98ef9782014-03-04 14:46:50 -08005378 } else {
5379 memset(mSinkBuffer, 0, mSinkBufferSize);
5380 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005381 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005382 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5383 "anticipated start");
5384 }
5385 // TODO add standby time extension fct of effect tail
5386}
5387
5388// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07005389PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005390 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005391{
Andy Hungc0691382018-09-12 18:01:57 -07005392 // clean up deleted track ids in AudioMixer before allocating new tracks
5393 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5394 // for each trackId, destroy it in the AudioMixer
5395 if (mAudioMixer->exists(trackId)) {
5396 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005397 }
5398 });
Andy Hungc0691382018-09-12 18:01:57 -07005399 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005400
5401 mixer_state mixerStatus = MIXER_IDLE;
5402 // find out which tracks need to be processed
5403 size_t count = mActiveTracks.size();
5404 size_t mixedTracks = 0;
5405 size_t tracksWithEffect = 0;
5406 // counts only _active_ fast tracks
5407 size_t fastTracks = 0;
5408 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5409
5410 float masterVolume = mMasterVolume;
5411 bool masterMute = mMasterMute;
5412
5413 if (masterMute) {
5414 masterVolume = 0;
5415 }
5416 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005417 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005418 if (chain != 0) {
5419 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5420 chain->setVolume_l(&v, &v);
5421 masterVolume = (float)((v + (1 << 23)) >> 24);
5422 chain.clear();
5423 }
5424
5425 // prepare a new state to push
5426 FastMixerStateQueue *sq = NULL;
5427 FastMixerState *state = NULL;
5428 bool didModify = false;
5429 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005430 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005431 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005432 sq = mFastMixer->sq();
5433 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005434 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005435 }
5436
Andy Hung69aed5f2014-02-25 17:24:40 -08005437 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005438 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005439
Andy Hungbd3b2b02018-05-21 10:53:11 -07005440 // DeferredOperations handles statistics after setting mixerStatus.
5441 class DeferredOperations {
5442 public:
Andy Hungea840382020-05-05 21:50:17 -07005443 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5444 : mMixerStatus(mixerStatus)
5445 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005446
5447 // when leaving scope, tally frames properly.
5448 ~DeferredOperations() {
5449 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5450 // because that is when the underrun occurs.
5451 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005452 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005453 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005454 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005455 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005456 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005457 }
5458 }
Andy Hungea840382020-05-05 21:50:17 -07005459 // send the max underrun frames for this mixer period
5460 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005461 }
5462
5463 // tallyUnderrunFrames() is called to update the track counters
5464 // with the number of underrun frames for a particular mixer period.
5465 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005466 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005467 mUnderrunFrames.emplace_back(track, underrunFrames);
5468 }
5469
5470 private:
5471 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005472 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005473 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005474 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005475 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005476
jiabin245cdd92018-12-07 17:55:15 -08005477 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005478 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005479 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005480
5481 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005482 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005483
5484 // process fast tracks
5485 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005486 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5487 "%s(%d): FastTrack(%d) present without FastMixer",
5488 __func__, id(), track->id());
5489
jiabin245cdd92018-12-07 17:55:15 -08005490 if (track->getHapticPlaybackEnabled()) {
5491 noFastHapticTrack = false;
5492 }
Eric Laurent81784c32012-11-19 14:55:58 -08005493
5494 // It's theoretically possible (though unlikely) for a fast track to be created
5495 // and then removed within the same normal mix cycle. This is not a problem, as
5496 // the track never becomes active so it's fast mixer slot is never touched.
5497 // The converse, of removing an (active) track and then creating a new track
5498 // at the identical fast mixer slot within the same normal mix cycle,
5499 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005500 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005501 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005502 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5503 FastTrack *fastTrack = &state->mFastTracks[j];
5504
5505 // Determine whether the track is currently in underrun condition,
5506 // and whether it had a recent underrun.
5507 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5508 FastTrackUnderruns underruns = ftDump->mUnderruns;
5509 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005510 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005511 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005512 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005513 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005514 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005515 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005516 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005517 // don't count underruns that occur while stopping or pausing
5518 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005519 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005520 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5521 recentUnderruns > 0) {
5522 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005523 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005524 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005525 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005526 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005527
5528 // This is similar to the state machine for normal tracks,
5529 // with a few modifications for fast tracks.
5530 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005531 switch (track->state()) {
5532 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005533 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005534 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005535 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005536 }
5537 break;
Andy Hung11e74242023-06-26 19:20:57 -07005538 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005539 // ramp down is not yet implemented
5540 track->setPaused();
5541 break;
Andy Hung11e74242023-06-26 19:20:57 -07005542 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005543 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005544 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005545 break;
Andy Hung11e74242023-06-26 19:20:57 -07005546 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005547 if (recentFull > 0 || recentPartial > 0) {
5548 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005549 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005550 }
5551 if (recentUnderruns == 0) {
5552 // no recent underruns: stay active
5553 break;
5554 }
5555 // there has recently been an underrun of some kind
5556 if (track->sharedBuffer() == 0) {
5557 // were any of the recent underruns "empty" (no frames available)?
5558 if (recentEmpty == 0) {
5559 // no, then ignore the partial underruns as they are allowed indefinitely
5560 break;
5561 }
5562 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005563 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005564 break;
5565 }
5566 // indicate to client process that the track was disabled because of underrun;
5567 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005568 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005569 // remove from active list, but state remains ACTIVE [confusing but true]
5570 isActive = false;
5571 break;
5572 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005573 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005574 case IAfTrackBase::STOPPING_2:
5575 case IAfTrackBase::PAUSED:
5576 case IAfTrackBase::STOPPED:
5577 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005578 // Check for presentation complete if track is inactive
5579 // We have consumed all the buffers of this track.
5580 // This would be incomplete if we auto-paused on underrun
5581 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005582 uint32_t latency = 0;
5583 status_t result = mOutput->stream->getLatency(&latency);
5584 ALOGE_IF(result != OK,
5585 "Error when retrieving output stream latency: %d", result);
5586 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005587 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005588 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5589 // track stays in active list until presentation is complete
5590 break;
5591 }
5592 }
5593 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005594 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005595 }
5596 if (track->isStopped()) {
5597 // Can't reset directly, as fast mixer is still polling this track
5598 // track->reset();
5599 // So instead mark this track as needing to be reset after push with ack
5600 resetMask |= 1 << i;
5601 }
5602 isActive = false;
5603 break;
Andy Hung11e74242023-06-26 19:20:57 -07005604 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005605 default:
Andy Hung11e74242023-06-26 19:20:57 -07005606 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005607 }
5608
5609 if (isActive) {
5610 // was it previously inactive?
5611 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005612 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5613 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005614 fastTrack->mBufferProvider = eabp;
5615 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005616 fastTrack->mChannelMask = track->channelMask();
5617 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005618 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005619 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005620 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005621 fastTrack->mGeneration++;
5622 state->mTrackMask |= 1 << j;
5623 didModify = true;
5624 // no acknowledgement required for newly active tracks
5625 }
Andy Hung11e74242023-06-26 19:20:57 -07005626 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005627 float volume;
5628 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5629 volume = 0.f;
5630 } else {
5631 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5632 }
5633
5634 handleVoipVolume_l(&volume);
5635
Eric Laurent81784c32012-11-19 14:55:58 -08005636 // cache the combined master volume and stream type volume for fast mixer; this
5637 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005638 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005639 proxy->framesReleased()).first;
5640 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005641 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005642 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005643 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5644 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5645
Andy Hung7535ed92023-07-17 17:05:00 -07005646 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005647 /*muteState=*/{masterVolume == 0.f,
5648 mStreamTypes[track->streamType()].volume == 0.f,
5649 mStreamTypes[track->streamType()].mute,
5650 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005651 vlf == 0.f && vrf == 0.f,
5652 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005653
5654 vlf *= volume;
5655 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005656
jiabin76d94692022-12-15 21:51:21 +00005657 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005658 ++fastTracks;
5659 } else {
5660 // was it previously active?
5661 if (state->mTrackMask & (1 << j)) {
5662 fastTrack->mBufferProvider = NULL;
5663 fastTrack->mGeneration++;
5664 state->mTrackMask &= ~(1 << j);
5665 didModify = true;
5666 // If any fast tracks were removed, we must wait for acknowledgement
5667 // because we're about to decrement the last sp<> on those tracks.
5668 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5669 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005670 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5671 // AudioTrack may start (which may not be with a start() but with a write()
5672 // after underrun) and immediately paused or released. In that case the
5673 // FastTrack state hasn't had time to update.
5674 // TODO Remove the ALOGW when this theory is confirmed.
5675 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005676 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005677 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005678 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005679 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005680 }
5681 tracksToRemove->add(track);
5682 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005683 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005684 }
jiabin245cdd92018-12-07 17:55:15 -08005685 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5686 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5687 didModify = true;
5688 }
Eric Laurent81784c32012-11-19 14:55:58 -08005689 continue;
5690 }
5691
5692 { // local variable scope to avoid goto warning
5693
5694 audio_track_cblk_t* cblk = track->cblk();
5695
5696 // The first time a track is added we wait
5697 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005698 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005699
5700 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005701 // use the trackId as the AudioMixer name.
5702 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005703 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005704 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005705 track->channelMask(),
5706 track->format(),
5707 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005708 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005709 ALOGW("%s(): AudioMixer cannot create track(%d)"
5710 " mask %#x, format %#x, sessionId %d",
5711 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005712 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005713 tracksToRemove->add(track);
5714 track->invalidate(); // consider it dead.
5715 continue;
5716 }
5717 }
5718
Eric Laurent81784c32012-11-19 14:55:58 -08005719 // make sure that we have enough frames to mix one full buffer.
5720 // enforce this condition only once to enable draining the buffer in case the client
5721 // app does not call stop() and relies on underrun to stop:
5722 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5723 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005724 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005725 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5726 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005727
5728 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005729 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005730 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5731 // add frames already consumed but not yet released by the resampler
5732 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005733 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005734
Eric Laurent81784c32012-11-19 14:55:58 -08005735 uint32_t minFrames = 1;
5736 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5737 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005738 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005739 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005740
5741 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005742 if (ATRACE_ENABLED()) {
5743 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005744 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005745 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005746 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005747 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005748 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005749 !track->isPaused() && !track->isTerminated())
5750 {
Andy Hungc0691382018-09-12 18:01:57 -07005751 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005752
5753 mixedTracks++;
5754
Andy Hung69aed5f2014-02-25 17:24:40 -08005755 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5756 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005757 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005758 if (track->mainBuffer() != mSinkBuffer &&
5759 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005760 if (mEffectBufferEnabled) {
5761 mEffectBufferValid = true; // Later can set directly.
5762 }
Eric Laurent81784c32012-11-19 14:55:58 -08005763 chain = getEffectChain_l(track->sessionId());
5764 // Delegate volume control to effect in track effect chain if needed
5765 if (chain != 0) {
5766 tracksWithEffect++;
5767 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005768 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005769 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005770 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005771 }
5772 }
5773
5774
5775 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005776 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005777 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005778 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5779 if (track->state() == IAfTrackBase::RESUMING) {
5780 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005781 // If a new track is paused immediately after start, do not ramp on resume.
5782 if (cblk->mServer != 0) {
5783 param = AudioMixer::RAMP_VOLUME;
5784 }
Eric Laurent81784c32012-11-19 14:55:58 -08005785 }
Andy Hungc0691382018-09-12 18:01:57 -07005786 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005787 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005788 // FIXME should not make a decision based on mServer
5789 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005790 // If the track is stopped before the first frame was mixed,
5791 // do not apply ramp
5792 param = AudioMixer::RAMP_VOLUME;
5793 }
5794
5795 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005796 uint32_t vl, vr; // in U8.24 integer format
5797 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005798 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005799 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005800 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005801 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005802 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005803 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005804
Eric Laurenteab90452019-06-24 15:17:46 -07005805 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5806 v = 0;
5807 }
5808
5809 handleVoipVolume_l(&v);
5810
5811 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005812 vl = vr = 0;
5813 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005814 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005815 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005816 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005817 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5818 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005819 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005820 if (vlf > GAIN_FLOAT_UNITY) {
5821 ALOGV("Track left volume out of range: %.3g", vlf);
5822 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005823 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005824 if (vrf > GAIN_FLOAT_UNITY) {
5825 ALOGV("Track right volume out of range: %.3g", vrf);
5826 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005827 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005828
Andy Hung7535ed92023-07-17 17:05:00 -07005829 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005830 /*muteState=*/{masterVolume == 0.f,
5831 mStreamTypes[track->streamType()].volume == 0.f,
5832 mStreamTypes[track->streamType()].mute,
5833 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005834 vlf == 0.f && vrf == 0.f,
5835 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005836
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005837 // now apply the master volume and stream type volume and shaper volume
5838 vlf *= v * vh;
5839 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005840 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005841 // then derive vl and vr as U8.24 versions for the effect chain
5842 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5843 vl = (uint32_t) (scaleto8_24 * vlf);
5844 vr = (uint32_t) (scaleto8_24 * vrf);
5845 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005846 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005847 // send level comes from shared memory and so may be corrupt
5848 if (sendLevel > MAX_GAIN_INT) {
5849 ALOGV("Track send level out of range: %04X", sendLevel);
5850 sendLevel = MAX_GAIN_INT;
5851 }
Andy Hung6be49402014-05-30 10:42:03 -07005852 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5853 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005854 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005855
jiabin76d94692022-12-15 21:51:21 +00005856 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005857
Eric Laurent81784c32012-11-19 14:55:58 -08005858 // Delegate volume control to effect in track effect chain if needed
5859 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5860 // Do not ramp volume if volume is controlled by effect
5861 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005862 // Update remaining floating point volume levels
5863 vlf = (float)vl / (1 << 24);
5864 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07005865 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005866 } else {
5867 // force no volume ramp when volume controller was just disabled or removed
5868 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07005869 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005870 param = AudioMixer::VOLUME;
5871 }
Andy Hung11e74242023-06-26 19:20:57 -07005872 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005873 }
5874
Eric Laurent81784c32012-11-19 14:55:58 -08005875 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07005876 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005877 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005878
Andy Hungc0691382018-09-12 18:01:57 -07005879 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5880 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5881 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005882 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005883 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005884 AudioMixer::TRACK,
5885 AudioMixer::FORMAT, (void *)track->format());
5886 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005887 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005888 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005889 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005890
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005891 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005892 mAudioMixer->setParameter(
5893 trackId,
5894 AudioMixer::TRACK,
5895 AudioMixer::MIXER_CHANNEL_MASK,
5896 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5897 } else {
5898 mAudioMixer->setParameter(
5899 trackId,
5900 AudioMixer::TRACK,
5901 AudioMixer::MIXER_CHANNEL_MASK,
5902 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5903 }
5904
Glenn Kastene3aa6592012-12-04 12:22:46 -08005905 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005906 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005907 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005908 if (reqSampleRate == 0) {
5909 reqSampleRate = mSampleRate;
5910 } else if (reqSampleRate > maxSampleRate) {
5911 reqSampleRate = maxSampleRate;
5912 }
Eric Laurent81784c32012-11-19 14:55:58 -08005913 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005914 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005915 AudioMixer::RESAMPLE,
5916 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005917 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005918
Andy Hung8edb8dc2015-03-26 19:13:55 -07005919 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005920 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005921 AudioMixer::TIMESTRETCH,
5922 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005923 // cast away constness for this generic API.
5924 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005925
Andy Hung69aed5f2014-02-25 17:24:40 -08005926 /*
5927 * Select the appropriate output buffer for the track.
5928 *
Andy Hung98ef9782014-03-04 14:46:50 -08005929 * Tracks with effects go into their own effects chain buffer
5930 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005931 *
5932 * Other tracks can use mMixerBuffer for higher precision
5933 * channel accumulation. If this buffer is enabled
5934 * (mMixerBufferEnabled true), then selected tracks will accumulate
5935 * into it.
5936 *
5937 */
5938 if (mMixerBufferEnabled
5939 && (track->mainBuffer() == mSinkBuffer
5940 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005941 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005942 mAudioMixer->setParameter(
5943 trackId,
5944 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005945 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005946 mAudioMixer->setParameter(
5947 trackId,
5948 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005949 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005950 } else {
5951 mAudioMixer->setParameter(
5952 trackId,
5953 AudioMixer::TRACK,
5954 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5955 mAudioMixer->setParameter(
5956 trackId,
5957 AudioMixer::TRACK,
5958 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5959 // TODO: override track->mainBuffer()?
5960 mMixerBufferValid = true;
5961 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005962 } else {
5963 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005964 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005965 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005966 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005967 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005968 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005969 AudioMixer::TRACK,
5970 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5971 }
Eric Laurent81784c32012-11-19 14:55:58 -08005972 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005973 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005974 AudioMixer::TRACK,
5975 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005976 mAudioMixer->setParameter(
5977 trackId,
5978 AudioMixer::TRACK,
5979 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005980 mAudioMixer->setParameter(
5981 trackId,
5982 AudioMixer::TRACK,
5983 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung11e74242023-06-26 19:20:57 -07005984 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005985 mAudioMixer->setParameter(
5986 trackId,
5987 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07005988 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005989
5990 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005991 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005992
5993 // If one track is ready, set the mixer ready if:
5994 // - the mixer was not ready during previous round OR
5995 // - no other track is not ready
5996 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5997 mixerStatus != MIXER_TRACKS_ENABLED) {
5998 mixerStatus = MIXER_TRACKS_READY;
5999 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006000
6001 // Enable the next few lines to instrument a test for underrun log handling.
6002 // TODO: Remove when we have a better way of testing the underrun log.
6003#if 0
6004 static int i;
6005 if ((++i & 0xf) == 0) {
6006 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6007 }
6008#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006009 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006010 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006011 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006012 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6013 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006014 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006015 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006016 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006017
Eric Laurent81784c32012-11-19 14:55:58 -08006018 // clear effect chain input buffer if an active track underruns to avoid sending
6019 // previous audio buffer again to effects
6020 chain = getEffectChain_l(track->sessionId());
6021 if (chain != 0) {
6022 chain->clearInputBuffer();
6023 }
6024
Andy Hungc0691382018-09-12 18:01:57 -07006025 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006026 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6027 track->isStopped() || track->isPaused()) {
6028 // We have consumed all the buffers of this track.
6029 // Remove it from the list of active tracks.
6030 // TODO: use actual buffer filling status instead of latency when available from
6031 // audio HAL
6032 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006033 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006034 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6035 if (track->isStopped()) {
6036 track->reset();
6037 }
6038 tracksToRemove->add(track);
6039 }
6040 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006041 // No buffers for this track. Give it a few chances to
6042 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07006043 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006044 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6045 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006046 tracksToRemove->add(track);
6047 // indicate to client process that the track was disabled because of underrun;
6048 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006049 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006050 // If one track is not ready, mark the mixer also not ready if:
6051 // - the mixer was ready during previous round OR
6052 // - no other track is ready
6053 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6054 mixerStatus != MIXER_TRACKS_READY) {
6055 mixerStatus = MIXER_TRACKS_ENABLED;
6056 }
6057 }
Andy Hungc0691382018-09-12 18:01:57 -07006058 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006059 }
6060
6061 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006062
6063 }
6064
jiabin245cdd92018-12-07 17:55:15 -08006065 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6066 // When there is no fast track playing haptic and FastMixer exists,
6067 // enabling the first FastTrack, which provides mixed data from normal
6068 // tracks, to play haptic data.
6069 FastTrack *fastTrack = &state->mFastTracks[0];
6070 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6071 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6072 didModify = true;
6073 }
6074 }
6075
Eric Laurent81784c32012-11-19 14:55:58 -08006076 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006077 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006078 if (didModify) {
6079 state->mFastTracksGen++;
6080 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6081 if (kUseFastMixer == FastMixer_Dynamic &&
6082 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6083 state->mCommand = FastMixerState::COLD_IDLE;
6084 state->mColdFutexAddr = &mFastMixerFutex;
6085 state->mColdGen++;
6086 mFastMixerFutex = 0;
6087 if (kUseFastMixer == FastMixer_Dynamic) {
6088 mNormalSink = mOutputSink;
6089 }
6090 // If we go into cold idle, need to wait for acknowledgement
6091 // so that fast mixer stops doing I/O.
6092 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6093 pauseAudioWatchdog = true;
6094 }
Eric Laurent81784c32012-11-19 14:55:58 -08006095 }
6096 if (sq != NULL) {
6097 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006098 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6099 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6100 // when bringing the output sink into standby.)
6101 //
6102 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6103 //
6104 // This occurs with BT suspend when we idle the FastMixer with
6105 // active tracks, which may be added or removed.
6106 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006107 }
6108#ifdef AUDIO_WATCHDOG
6109 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6110 mAudioWatchdog->pause();
6111 }
6112#endif
6113
6114 // Now perform the deferred reset on fast tracks that have stopped
6115 while (resetMask != 0) {
6116 size_t i = __builtin_ctz(resetMask);
6117 ALOG_ASSERT(i < count);
6118 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006119 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006120 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6121 track->reset();
6122 }
6123
Andy Hung80d03d22018-04-10 10:32:11 -07006124 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6125 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6126 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6127 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6128 // See also the implementation of destroyTrack_l().
6129 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006130 const int trackId = track->id();
6131 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6132 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006133 }
6134 }
6135
Eric Laurent81784c32012-11-19 14:55:58 -08006136 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006137 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006138
Eric Laurentb3f315a2021-07-13 15:09:05 +02006139 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6140 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006141 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006142 }
6143
6144 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006145 // as long as there are effects we should clear the effects buffer, to avoid
6146 // passing a non-clean buffer to the effect chain
6147 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006148 if (mType == SPATIALIZER) {
6149 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6150 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006151 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006152 // sink or mix buffer must be cleared if all tracks are connected to an
6153 // effect chain as in this case the mixer will not write to the sink or mix buffer
6154 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006155 // always clear sink buffer for spatializer output as the output of the spatializer
6156 // effect will be accumulated into it
6157 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6158 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006159 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006160 if (mMixerBufferValid) {
6161 memset(mMixerBuffer, 0, mMixerBufferSize);
6162 // TODO: In testing, mSinkBuffer below need not be cleared because
6163 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6164 // after mixing.
6165 //
6166 // To enforce this guarantee:
6167 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6168 // (mixedTracks == 0 && fastTracks > 0))
6169 // must imply MIXER_TRACKS_READY.
6170 // Later, we may clear buffers regardless, and skip much of this logic.
6171 }
Andy Hung98ef9782014-03-04 14:46:50 -08006172 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006173 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006174 }
6175
6176 // if any fast tracks, then status is ready
6177 mMixerStatusIgnoringFastTracks = mixerStatus;
6178 if (fastTracks > 0) {
6179 mixerStatus = MIXER_TRACKS_READY;
6180 }
6181 return mixerStatus;
6182}
6183
Eric Laurentad7dd962016-09-22 12:38:37 -07006184// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006185uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006186{
6187 uint32_t trackCount = 0;
6188 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006189 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006190 trackCount++;
6191 }
6192 }
6193 return trackCount;
6194}
6195
Andy Hung4b17e882023-07-07 13:47:37 -07006196bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006197{
Brian Lindahl65e90012022-07-27 18:01:07 +02006198 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6199 // could falsely detect that the frame position has stalled due to underrun because we haven't
6200 // given the Audio HAL enough time to update.
6201 const nsecs_t nowNs = systemTime();
6202 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6203 return mLatchedValue;
6204 }
6205 mPreviousNs = nowNs;
6206 mLatchedValue = false;
6207 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006208 uint64_t position = 0;
6209 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006210 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006211 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006212 if (position != mPreviousPosition) {
6213 mPreviousPosition = position;
6214 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006215 }
6216 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006217 return mLatchedValue;
6218}
6219
Andy Hung4b17e882023-07-07 13:47:37 -07006220void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006221{
6222 mLatchedValue = true;
6223 mPreviousPosition = 0;
6224 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006225}
6226
Andy Hung1bc088a2018-02-09 15:57:31 -08006227// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006228bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006229 audio_channel_mask_t channelMask, audio_format_t format,
6230 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006231{
Andy Hung1bc088a2018-02-09 15:57:31 -08006232 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6233 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006234 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006235 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006236 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006237 ALOGW("%s: invalid format: %#x", __func__, format);
6238 return false;
6239 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006240 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006241 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6242 return false;
6243 }
6244 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006245}
6246
Eric Laurent10351942014-05-08 18:49:52 -07006247// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006248bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006249 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006250{
Eric Laurent81784c32012-11-19 14:55:58 -08006251 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006252 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006253
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006254 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006255
Eric Laurent10351942014-05-08 18:49:52 -07006256 AudioParameter param = AudioParameter(keyValuePair);
6257 int value;
6258 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6259 reconfig = true;
6260 }
6261 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006262 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006263 status = BAD_VALUE;
6264 } else {
6265 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006266 reconfig = true;
6267 }
Eric Laurent10351942014-05-08 18:49:52 -07006268 }
6269 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006270 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006271 status = BAD_VALUE;
6272 } else {
6273 // no need to save value, since it's constant
6274 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006275 }
Eric Laurent10351942014-05-08 18:49:52 -07006276 }
6277 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6278 // do not accept frame count changes if tracks are open as the track buffer
6279 // size depends on frame count and correct behavior would not be guaranteed
6280 // if frame count is changed after track creation
6281 if (!mTracks.isEmpty()) {
6282 status = INVALID_OPERATION;
6283 } else {
6284 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006285 }
Eric Laurent10351942014-05-08 18:49:52 -07006286 }
6287 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006288 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006289 }
Eric Laurent81784c32012-11-19 14:55:58 -08006290
Eric Laurent10351942014-05-08 18:49:52 -07006291 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006292 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006293 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006294 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6295 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006296 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006297 mThreadMetrics.logEndInterval();
6298 mThreadSnapshot.onEnd();
6299 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006300 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006301 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006302 }
Eric Laurent10351942014-05-08 18:49:52 -07006303 if (status == NO_ERROR && reconfig) {
6304 readOutputParameters_l();
6305 delete mAudioMixer;
6306 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006307 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006308 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006309 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006310 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006311 track->channelMask(),
6312 track->format(),
6313 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006314 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006315 "%s(): AudioMixer cannot create track(%d)"
6316 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006317 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006318 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006319 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006320 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006321 }
Eric Laurent81784c32012-11-19 14:55:58 -08006322 }
6323
Dean Wheatley68918102021-03-19 22:09:19 +11006324 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006325}
6326
6327
Andy Hung4b17e882023-07-07 13:47:37 -07006328void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006329{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006330 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006331 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006332 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006333 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006334 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6335 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6336 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006337 if (hasFastMixer()) {
6338 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6339
6340 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6341 // while we are dumping it. It may be inconsistent, but it won't mutate!
6342 // This is a large object so we place it on the heap.
6343 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006344 const std::unique_ptr<FastMixerDumpState> copy =
6345 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006346 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006347
6348#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006349 // Similar for state queue
6350 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6351 observerCopy.dump(fd);
6352 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6353 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006354#endif
6355
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006356#ifdef AUDIO_WATCHDOG
6357 if (mAudioWatchdog != 0) {
6358 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6359 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6360 wdCopy.dump(fd);
6361 }
6362#endif
6363
6364 } else {
6365 dprintf(fd, " No FastMixer\n");
6366 }
Eric Laurent90cea102023-05-15 15:08:27 +02006367
6368 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6369 mBluetoothLatencyModesEnabled ? "" : "not ");
6370 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6371 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6372 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006373}
6374
Andy Hung4b17e882023-07-07 13:47:37 -07006375uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006376{
6377 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6378}
6379
Andy Hung4b17e882023-07-07 13:47:37 -07006380uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006381{
6382 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6383}
6384
Andy Hung4b17e882023-07-07 13:47:37 -07006385void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006386{
6387 PlaybackThread::cacheParameters_l();
6388
6389 // FIXME: Relaxed timing because of a certain device that can't meet latency
6390 // Should be reduced to 2x after the vendor fixes the driver issue
6391 // increase threshold again due to low power audio mode. The way this warning
6392 // threshold is calculated and its usefulness should be reconsidered anyway.
6393 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6394}
6395
Andy Hung4b17e882023-07-07 13:47:37 -07006396void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006397 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006398}
6399
Andy Hung4b17e882023-07-07 13:47:37 -07006400void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006401 // Only handle latency mode if:
6402 // - mBluetoothLatencyModesEnabled is true
6403 // - the HAL supports latency modes
6404 // - the selected device is Bluetooth LE or A2DP
6405 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6406 return;
6407 }
6408 if (mOutDeviceTypeAddrs.size() != 1
6409 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6410 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6411 return;
6412 }
6413
6414 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6415 if (mSupportedLatencyModes.size() == 1) {
6416 // If the HAL only support one latency mode currently, confirm the choice
6417 latencyMode = mSupportedLatencyModes[0];
6418 } else if (mSupportedLatencyModes.size() > 1) {
6419 // Request low latency if:
6420 // - At least one active track is either:
6421 // - a fast track with gaming usage or
6422 // - a track with acessibility usage
6423 for (const auto& track : mActiveTracks) {
6424 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6425 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6426 latencyMode = AUDIO_LATENCY_MODE_LOW;
6427 break;
6428 }
6429 }
6430 }
6431
6432 if (latencyMode != mSetLatencyMode) {
6433 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6434 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6435 __func__, mId, toString(latencyMode).c_str(), status);
6436 if (status == NO_ERROR) {
6437 mSetLatencyMode = latencyMode;
6438 }
6439 }
6440}
6441
Andy Hung4b17e882023-07-07 13:47:37 -07006442void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006443
6444 if (mOutput == nullptr || mOutput->stream == nullptr) {
6445 return;
6446 }
6447 std::vector<audio_latency_mode_t> latencyModes;
6448 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6449 if (status != NO_ERROR) {
6450 latencyModes.clear();
6451 }
6452 if (latencyModes != mSupportedLatencyModes) {
6453 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6454 __func__, mId, status, toString(latencyModes).c_str());
6455 mSupportedLatencyModes.swap(latencyModes);
6456 sendHalLatencyModesChangedEvent_l();
6457 }
6458}
6459
Andy Hung4b17e882023-07-07 13:47:37 -07006460status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006461 std::vector<audio_latency_mode_t>* modes) {
6462 if (modes == nullptr) {
6463 return BAD_VALUE;
6464 }
6465 Mutex::Autolock _l(mLock);
6466 *modes = mSupportedLatencyModes;
6467 return NO_ERROR;
6468}
6469
Andy Hung4b17e882023-07-07 13:47:37 -07006470void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006471 std::vector<audio_latency_mode_t> modes) {
6472 Mutex::Autolock _l(mLock);
6473 if (modes != mSupportedLatencyModes) {
6474 ALOGD("%s: thread(%d) supported latency modes: %s",
6475 __func__, mId, toString(modes).c_str());
6476 mSupportedLatencyModes.swap(modes);
6477 sendHalLatencyModesChangedEvent_l();
6478 }
6479}
6480
Andy Hung4b17e882023-07-07 13:47:37 -07006481status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006482 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6483 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6484 return INVALID_OPERATION;
6485 }
6486 mBluetoothLatencyModesEnabled.store(enabled);
6487 return NO_ERROR;
6488}
6489
Eric Laurent81784c32012-11-19 14:55:58 -08006490// ----------------------------------------------------------------------------
6491
Andy Hung4b17e882023-07-07 13:47:37 -07006492/* static */
6493sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006494 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006495 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6496 const audio_offload_info_t& offloadInfo) {
6497 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006498 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006499}
6500
Andy Hung7535ed92023-07-17 17:05:00 -07006501DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006502 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6503 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006504 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006505 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006506{
Andy Hung7535ed92023-07-17 17:05:00 -07006507 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006508}
6509
Andy Hung4b17e882023-07-07 13:47:37 -07006510DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006511{
6512}
6513
Andy Hung4b17e882023-07-07 13:47:37 -07006514void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006515{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006516 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006517 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6518 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6519}
6520
Andy Hung4b17e882023-07-07 13:47:37 -07006521void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006522{
6523 Mutex::Autolock _l(mLock);
6524 if (mMasterBalance != balance) {
6525 mMasterBalance.store(balance);
6526 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6527 broadcast_l();
6528 }
6529}
6530
Andy Hung4b17e882023-07-07 13:47:37 -07006531void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006532{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006533 float left, right;
6534
Andy Hung333ab962019-05-28 20:23:35 -07006535 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006536 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006537
Andy Hung398ffa22022-12-13 19:19:53 -08006538 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6539 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6540
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006541 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6542 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006543
6544 const int64_t volumeShaperFrames =
6545 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6546 const auto [shaperVolume, shaperActive] =
6547 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006548 mVolumeShaperActive = shaperActive;
6549
Vlad Popae2f5aef2022-07-25 16:00:20 +02006550 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6551 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6552 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6553
6554 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6555
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006556 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006557 left = right = 0;
6558 } else {
6559 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006560 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006561
Glenn Kastenc56f3422014-03-21 17:53:17 -07006562 if (left > GAIN_FLOAT_UNITY) {
6563 left = GAIN_FLOAT_UNITY;
6564 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006565 if (right > GAIN_FLOAT_UNITY) {
6566 right = GAIN_FLOAT_UNITY;
6567 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006568 left *= v;
6569 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006570 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006571 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6572 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6573 right *= mMasterBalanceRight;
6574 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006575 }
6576
Andy Hung7535ed92023-07-17 17:05:00 -07006577 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006578 /*muteState=*/{mMasterMute,
6579 mStreamTypes[track->streamType()].volume == 0.f,
6580 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006581 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006582 clientVolumeMute,
6583 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006584
Eric Laurentbfb1b832013-01-07 09:53:42 -08006585 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006586 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006587 if (left != mLeftVolFloat || right != mRightVolFloat) {
6588 mLeftVolFloat = left;
6589 mRightVolFloat = right;
6590
Eric Laurentbfb1b832013-01-07 09:53:42 -08006591 // Delegate volume control to effect in track effect chain if needed
6592 // only one effect chain can be present on DirectOutputThread, so if
6593 // there is one, the track is connected to it
6594 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006595 // if effect chain exists, volume is handled by it.
6596 // Convert volumes from float to 8.24
6597 uint32_t vl = (uint32_t)(left * (1 << 24));
6598 uint32_t vr = (uint32_t)(right * (1 << 24));
6599 // Direct/Offload effect chains set output volume in setVolume_l().
6600 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6601 } else {
6602 // otherwise we directly set the volume.
6603 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006604 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006605 }
6606 }
6607}
6608
Andy Hung4b17e882023-07-07 13:47:37 -07006609void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006610{
Andy Hung11e74242023-06-26 19:20:57 -07006611 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6612 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006613
Eric Laurent0f0631e2015-07-06 18:01:25 -07006614 if (previousTrack != 0 && latestTrack != 0) {
6615 if (mType == DIRECT) {
6616 if (previousTrack.get() != latestTrack.get()) {
6617 mFlushPending = true;
6618 }
6619 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006620 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6621 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006622 mFlushPending = true;
6623 }
6624 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006625 } else if (previousTrack == 0) {
6626 // there could be an old track added back during track transition for direct
6627 // output, so always issues flush to flush data of the previous track if it
6628 // was already destroyed with HAL paused, then flush can resume the playback
6629 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006630 }
6631 PlaybackThread::onAddNewTrack_l();
6632}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006633
Andy Hung4b17e882023-07-07 13:47:37 -07006634PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006635 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006636)
6637{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006638 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006639 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006640 bool doHwPause = false;
6641 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006642
6643 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006644 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006645 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006646 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006647 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006648 continue;
6649 }
6650
Andy Hung11e74242023-06-26 19:20:57 -07006651 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006652#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006653 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006654#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006655 // Only consider last track started for volume and mixer state control.
6656 // In theory an older track could underrun and restart after the new one starts
6657 // but as we only care about the transition phase between two tracks on a
6658 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006659 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006660 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006661
Kuowei Li23666472021-01-20 10:23:25 +08006662 if (track->isPausePending()) {
6663 track->pauseAck();
6664 // It is possible a track might have been flushed or stopped.
6665 // Other operations such as flush pending might occur on the next prepare.
6666 if (track->isPausing()) {
6667 track->setPaused();
6668 }
6669 // Always perform pause, as an immediate flush will change
6670 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006671 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006672 doHwPause = true;
6673 mHwPaused = true;
6674 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006675 } else if (track->isFlushPending()) {
6676 track->flushAck();
6677 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006678 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006679 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006680 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006681 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006682 if (last) {
6683 mLeftVolFloat = mRightVolFloat = -1.0;
6684 if (mHwPaused) {
6685 doHwResume = true;
6686 mHwPaused = false;
6687 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006688 }
6689 }
6690
Eric Laurent81784c32012-11-19 14:55:58 -08006691 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006692 // for all its buffers to be filled before processing it.
6693 // Allow draining the buffer in case the client
6694 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006695 // hence the test on (track->retryCount() > 1).
6696 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006697 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6698 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006699 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006700
6701 // target retry count that we will use is based on the time we wait for retries.
6702 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6703 // the retry threshold is when we accept any size for PCM data. This is slightly
6704 // smaller than the retry count so we can push small bits of data without a glitch.
6705 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006706 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006707 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006708 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006709 minFrames = mNormalFrameCount;
6710 } else {
6711 minFrames = 1;
6712 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006713
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006714 const size_t framesReady = track->framesReady();
6715 const int trackId = track->id();
6716 if (ATRACE_ENABLED()) {
6717 std::string traceName("nRdy");
6718 traceName += std::to_string(trackId);
6719 ATRACE_INT(traceName.c_str(), framesReady);
6720 }
6721 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006722 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006723 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006724 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006725
Andy Hung11e74242023-06-26 19:20:57 -07006726 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6727 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006728 if (last) {
6729 // make sure processVolume_l() will apply new volume even if 0
6730 mLeftVolFloat = mRightVolFloat = -1.0;
6731 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006732 if (!mHwSupportsPause) {
6733 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006734 }
6735 }
6736
6737 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006738 processVolume_l(track, last);
6739 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006740 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006741 if (previousTrack != 0) {
6742 if (track != previousTrack.get()) {
6743 // Flush any data still being written from last track
6744 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006745 // Invalidate previous track to force a seek when resuming.
6746 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006747 }
6748 }
6749 mPreviousTrack = track;
6750
Eric Laurentd595b7c2013-04-03 17:27:56 -07006751 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006752 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006753 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006754 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006755 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006756 doHwResume = true;
6757 mHwPaused = false;
6758 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006759 }
Eric Laurent81784c32012-11-19 14:55:58 -08006760 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006761 // clear effect chain input buffer if the last active track started underruns
6762 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006763 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006764 mEffectChains[0]->clearInputBuffer();
6765 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006766 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006767 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006768 if (last && mHwPaused) {
6769 doHwResume = true;
6770 mHwPaused = false;
6771 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006772 }
6773 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6774 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006775 // We have consumed all the buffers of this track.
6776 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006777 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006778 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006779 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006780 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006781 if (presComplete) {
6782 mOutput->presentationComplete();
6783 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006784 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006785 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006786 }
Eric Laurent81784c32012-11-19 14:55:58 -08006787 if (track->isStopped()) {
6788 track->reset();
6789 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006790 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006791 }
6792 } else {
6793 // No buffers for this track. Give it a few chances to
6794 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006795 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006796 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006797 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006798 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006799 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006800 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006801 } else {
6802 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6803 tracksToRemove->add(track);
6804 // indicate to client process that the track was disabled because of
6805 // underrun; it will then automatically call start() when data is available
6806 track->disable();
6807 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6808 // unlike mixerthread, HAL can be paused for direct output
6809 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6810 "minFrames = %u, mFormat = %#x",
6811 framesReady, minFrames, mFormat);
6812 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6813 doHwPause = true;
6814 mHwPaused = true;
6815 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006816 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006817 } else if (last) {
6818 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006819 }
6820 }
6821 }
6822 }
6823
Eric Laurentd1f69b02014-12-15 14:33:13 -08006824 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006825 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006826 for (size_t i = 0; i < mTracks.size(); i++) {
6827 if (mTracks[i]->isFlushPending()) {
6828 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006829 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006830 }
6831 }
6832 }
6833
6834 // make sure the pause/flush/resume sequence is executed in the right order.
6835 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6836 // before flush and then resume HW. This can happen in case of pause/flush/resume
6837 // if resume is received before pause is executed.
6838 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006839 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006840 status_t result = mOutput->stream->pause();
6841 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006842 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006843 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006844 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006845 flushHw_l();
6846 }
6847 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006848 status_t result = mOutput->stream->resume();
6849 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006850 }
Eric Laurent81784c32012-11-19 14:55:58 -08006851 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006852 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006853
6854 return mixerStatus;
6855}
6856
Andy Hung4b17e882023-07-07 13:47:37 -07006857void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006858{
Eric Laurent81784c32012-11-19 14:55:58 -08006859 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006860 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006861 // output audio to hardware
6862 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006863 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006864 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006865 status_t status = mActiveTrack->getNextBuffer(&buffer);
6866 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006867 // no need to pad with 0 for compressed audio
6868 if (audio_has_proportional_frames(mFormat)) {
6869 memset(curBuf, 0, frameCount * mFrameSize);
6870 }
Eric Laurent81784c32012-11-19 14:55:58 -08006871 break;
6872 }
6873 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6874 frameCount -= buffer.frameCount;
6875 curBuf += buffer.frameCount * mFrameSize;
6876 mActiveTrack->releaseBuffer(&buffer);
6877 }
Andy Hung2098f272014-02-27 14:00:06 -08006878 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006879 mSleepTimeUs = 0;
6880 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006881 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006882}
6883
Andy Hung4b17e882023-07-07 13:47:37 -07006884void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006885{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006886 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006887 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006888 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006889 return;
6890 }
Andy Hung85ba3332021-04-27 17:40:26 -07006891 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6892 mSleepTimeUs = mActiveSleepTimeUs;
6893 } else {
6894 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006895 }
Andy Hung85ba3332021-04-27 17:40:26 -07006896 // Note: In S or later, we do not write zeroes for
6897 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006898}
6899
Andy Hung4b17e882023-07-07 13:47:37 -07006900void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006901{
6902 {
6903 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006904 for (size_t i = 0; i < mTracks.size(); i++) {
6905 if (mTracks[i]->isFlushPending()) {
6906 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006907 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006908 }
6909 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006910 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006911 flushHw_l();
6912 }
6913 }
6914 PlaybackThread::threadLoop_exit();
6915}
6916
6917// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07006918bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006919{
6920 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006921 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006922
6923 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6924 // after a timeout and we will enter standby then.
6925 if (mTracks.size() > 0) {
6926 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006927 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07006928 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006929 }
6930
Eric Laurent5cff4032015-05-26 13:49:58 -07006931 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006932}
6933
Eric Laurent10351942014-05-08 18:49:52 -07006934// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006935bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006936 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006937{
6938 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006939 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006940
Eric Laurent10351942014-05-08 18:49:52 -07006941 AudioParameter param = AudioParameter(keyValuePair);
6942 int value;
6943 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006944 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006945 }
Eric Laurent10351942014-05-08 18:49:52 -07006946 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6947 // do not accept frame count changes if tracks are open as the track buffer
6948 // size depends on frame count and correct behavior would not be garantied
6949 // if frame count is changed after track creation
6950 if (!mTracks.isEmpty()) {
6951 status = INVALID_OPERATION;
6952 } else {
6953 reconfig = true;
6954 }
6955 }
6956 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006957 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006958 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006959 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006960 if (!mStandby) {
6961 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006962 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006963 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006964 }
Eric Laurent10351942014-05-08 18:49:52 -07006965 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006966 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006967 }
6968 if (status == NO_ERROR && reconfig) {
6969 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006970 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006971 }
6972 }
6973
Dean Wheatley68918102021-03-19 22:09:19 +11006974 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006975}
6976
Andy Hung4b17e882023-07-07 13:47:37 -07006977uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006978{
6979 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006980 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006981 time = PlaybackThread::activeSleepTimeUs();
6982 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006983 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006984 }
6985 return time;
6986}
6987
Andy Hung4b17e882023-07-07 13:47:37 -07006988uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006989{
6990 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006991 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006992 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6993 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006994 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006995 }
6996 return time;
6997}
6998
Andy Hung4b17e882023-07-07 13:47:37 -07006999uint32_t DirectOutputThread::suspendSleepTimeUs() 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 = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
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 Hung4b17e882023-07-07 13:47:37 -07007010void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007011{
7012 PlaybackThread::cacheParameters_l();
7013
7014 // use shorter standby delay as on normal output to release
7015 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007016 // no delay on outputs with HW A/V sync
7017 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007018 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007019 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007020 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007021 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007022 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007023 }
Eric Laurent81784c32012-11-19 14:55:58 -08007024}
7025
Andy Hung4b17e882023-07-07 13:47:37 -07007026void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007027{
ziyangch8f194f12021-12-01 13:48:04 -08007028 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007029 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007030 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007031 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007032 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007033 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007034 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007035}
7036
Andy Hung4b17e882023-07-07 13:47:37 -07007037int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007038 // If a VolumeShaper is active, we must wake up periodically to update volume.
7039 const int64_t NS_PER_MS = 1000000;
7040 return mVolumeShaperActive ?
7041 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7042}
7043
Eric Laurent81784c32012-11-19 14:55:58 -08007044// ----------------------------------------------------------------------------
7045
Andy Hung4b17e882023-07-07 13:47:37 -07007046AsyncCallbackThread::AsyncCallbackThread(
7047 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007048 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007049 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007050 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007051 mDrainSequence(0),
7052 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007053{
7054}
7055
Andy Hung4b17e882023-07-07 13:47:37 -07007056void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007057{
7058 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7059}
7060
Andy Hung4b17e882023-07-07 13:47:37 -07007061bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007062{
7063 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007064 uint32_t writeAckSequence;
7065 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007066 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007067
7068 {
7069 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007070 while (!((mWriteAckSequence & 1) ||
7071 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007072 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007073 exitPending())) {
7074 mWaitWorkCV.wait(mLock);
7075 }
7076
Eric Laurentbfb1b832013-01-07 09:53:42 -08007077 if (exitPending()) {
7078 break;
7079 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007080 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7081 mWriteAckSequence, mDrainSequence);
7082 writeAckSequence = mWriteAckSequence;
7083 mWriteAckSequence &= ~1;
7084 drainSequence = mDrainSequence;
7085 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007086 asyncError = mAsyncError;
7087 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007088 }
7089 {
Andy Hung4b17e882023-07-07 13:47:37 -07007090 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007091 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007092 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007093 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007094 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007095 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007096 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007097 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007098 if (asyncError) {
7099 playbackThread->onAsyncError();
7100 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007101 }
7102 }
7103 }
7104 return false;
7105}
7106
Andy Hung4b17e882023-07-07 13:47:37 -07007107void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007108{
7109 ALOGV("AsyncCallbackThread::exit");
7110 Mutex::Autolock _l(mLock);
7111 requestExit();
7112 mWaitWorkCV.broadcast();
7113}
7114
Andy Hung4b17e882023-07-07 13:47:37 -07007115void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007116{
7117 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007118 // bit 0 is cleared
7119 mWriteAckSequence = sequence << 1;
7120}
7121
Andy Hung4b17e882023-07-07 13:47:37 -07007122void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007123{
7124 Mutex::Autolock _l(mLock);
7125 // ignore unexpected callbacks
7126 if (mWriteAckSequence & 2) {
7127 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007128 mWaitWorkCV.signal();
7129 }
7130}
7131
Andy Hung4b17e882023-07-07 13:47:37 -07007132void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007133{
7134 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007135 // bit 0 is cleared
7136 mDrainSequence = sequence << 1;
7137}
7138
Andy Hung4b17e882023-07-07 13:47:37 -07007139void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007140{
7141 Mutex::Autolock _l(mLock);
7142 // ignore unexpected callbacks
7143 if (mDrainSequence & 2) {
7144 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007145 mWaitWorkCV.signal();
7146 }
7147}
7148
Andy Hung4b17e882023-07-07 13:47:37 -07007149void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007150{
7151 Mutex::Autolock _l(mLock);
7152 mAsyncError = true;
7153 mWaitWorkCV.signal();
7154}
7155
Eric Laurentbfb1b832013-01-07 09:53:42 -08007156
7157// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007158
7159/* static */
7160sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007161 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007162 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7163 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007164 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007165}
7166
Andy Hung7535ed92023-07-17 17:05:00 -07007167OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007168 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7169 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007170 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007171 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007172{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007173 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007174 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007175 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007176}
7177
Andy Hung4b17e882023-07-07 13:47:37 -07007178void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007179{
7180 if (mFlushPending || mHwPaused) {
7181 // If a flush is pending or track was paused, just discard buffered data
7182 flushHw_l();
7183 } else {
7184 mMixerStatus = MIXER_DRAIN_ALL;
7185 threadLoop_drain();
7186 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007187 if (mUseAsyncWrite) {
7188 ALOG_ASSERT(mCallbackThread != 0);
7189 mCallbackThread->exit();
7190 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007191 PlaybackThread::threadLoop_exit();
7192}
7193
Andy Hung4b17e882023-07-07 13:47:37 -07007194PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007195 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007196)
7197{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007198 size_t count = mActiveTracks.size();
7199
7200 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007201 bool doHwPause = false;
7202 bool doHwResume = false;
7203
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007204 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007205
Eric Laurentbfb1b832013-01-07 09:53:42 -08007206 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007207 for (const sp<IAfTrack>& t : mActiveTracks) {
7208 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007209#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007210 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007211#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007212 // Only consider last track started for volume and mixer state control.
7213 // In theory an older track could underrun and restart after the new one starts
7214 // but as we only care about the transition phase between two tracks on a
7215 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007216 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007217 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007218
Haynes Mathew George7844f672014-01-15 12:32:55 -08007219 if (track->isInvalid()) {
7220 ALOGW("An invalidated track shouldn't be in active list");
7221 tracksToRemove->add(track);
7222 continue;
7223 }
7224
Andy Hung11e74242023-06-26 19:20:57 -07007225 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007226 ALOGW("An idle track shouldn't be in active list");
7227 continue;
7228 }
7229
Kuowei Li23666472021-01-20 10:23:25 +08007230 if (track->isPausePending()) {
7231 track->pauseAck();
7232 // It is possible a track might have been flushed or stopped.
7233 // Other operations such as flush pending might occur on the next prepare.
7234 if (track->isPausing()) {
7235 track->setPaused();
7236 }
7237 // Always perform pause if last, as an immediate flush will change
7238 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007239 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007240 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007241 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007242 mHwPaused = true;
7243 }
7244 // If we were part way through writing the mixbuffer to
7245 // the HAL we must save this until we resume
7246 // BUG - this will be wrong if a different track is made active,
7247 // in that case we want to discard the pending data in the
7248 // mixbuffer and tell the client to present it again when the
7249 // track is resumed
7250 mPausedWriteLength = mCurrentWriteLength;
7251 mPausedBytesRemaining = mBytesRemaining;
7252 mBytesRemaining = 0; // stop writing
7253 }
7254 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007255 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007256 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007257 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007258 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007259 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007260 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007261 track->flushAck();
7262 if (last) {
7263 mFlushPending = true;
7264 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007265 } else if (track->isResumePending()){
7266 track->resumeAck();
7267 if (last) {
7268 if (mPausedBytesRemaining) {
7269 // Need to continue write that was interrupted
7270 mCurrentWriteLength = mPausedWriteLength;
7271 mBytesRemaining = mPausedBytesRemaining;
7272 mPausedBytesRemaining = 0;
7273 }
7274 if (mHwPaused) {
7275 doHwResume = true;
7276 mHwPaused = false;
7277 // threadLoop_mix() will handle the case that we need to
7278 // resume an interrupted write
7279 }
7280 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007281 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007282
Eric Laurent3df841a2016-07-15 15:15:40 -07007283 mLeftVolFloat = mRightVolFloat = -1.0;
7284
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007285 // Do not handle new data in this iteration even if track->framesReady()
7286 mixerStatus = MIXER_TRACKS_ENABLED;
7287 }
7288 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007289 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007290 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007291 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7292 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007293 if (last) {
7294 // make sure processVolume_l() will apply new volume even if 0
7295 mLeftVolFloat = mRightVolFloat = -1.0;
7296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007297 }
7298
7299 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007300 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007301 if (previousTrack != 0) {
7302 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007303 // Flush any data still being written from last track
7304 mBytesRemaining = 0;
7305 if (mPausedBytesRemaining) {
7306 // Last track was paused so we also need to flush saved
7307 // mixbuffer state and invalidate track so that it will
7308 // re-submit that unwritten data when it is next resumed
7309 mPausedBytesRemaining = 0;
7310 // Invalidate is a bit drastic - would be more efficient
7311 // to have a flag to tell client that some of the
7312 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007313 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007314 }
7315 // flush data already sent to the DSP if changing audio session as audio
7316 // comes from a different source. Also invalidate previous track to force a
7317 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007318 if (previousTrack->sessionId() != track->sessionId()) {
7319 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007320 }
7321 }
7322 }
7323 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007324 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007325 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007326 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007327 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007328 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007329 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007330 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007331 mixerStatus = MIXER_TRACKS_READY;
7332 }
7333 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007334 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007335 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007336 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007337 // Hardware buffer can hold a large amount of audio so we must
7338 // wait for all current track's data to drain before we say
7339 // that the track is stopped.
7340 if (mBytesRemaining == 0) {
7341 // Only start draining when all data in mixbuffer
7342 // has been written
7343 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007344 track->setState(IAfTrackBase::STOPPING_2);
7345 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007346 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7347 if (last && !mStandby) {
7348 // do not modify drain sequence if we are already draining. This happens
7349 // when resuming from pause after drain.
7350 if ((mDrainSequence & 1) == 0) {
7351 mSleepTimeUs = 0;
7352 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7353 mixerStatus = MIXER_DRAIN_TRACK;
7354 mDrainSequence += 2;
7355 }
7356 if (mHwPaused) {
7357 // It is possible to move from PAUSED to STOPPING_1 without
7358 // a resume so we must ensure hardware is running
7359 doHwResume = true;
7360 mHwPaused = false;
7361 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007362 }
7363 }
Eric Laurente93cc032016-05-05 10:15:10 -07007364 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007365 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007366 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007367 }
7368 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007369 // Drain has completed or we are in standby, signal presentation complete
7370 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007371 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007372 mOutput->presentationComplete();
7373 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007374 track->reset();
7375 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007376 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007377 if (!mUseAsyncWrite) {
7378 // If we don't get explicit drain notification we must
7379 // register discontinuity regardless of whether this is
7380 // the previous (!last) or the upcoming (last) track
7381 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007382 mTimestampVerifier.discontinuity(
7383 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007384 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007385 }
7386 } else {
7387 // No buffers for this track. Give it a few chances to
7388 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007389 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007390 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007391 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007392 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007393 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007394 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007395 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7396 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007397 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007398 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007399 // it will then automatically call start() when data is available
7400 track->disable();
7401 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007402 } else if (last){
7403 mixerStatus = MIXER_TRACKS_ENABLED;
7404 }
7405 }
7406 }
7407 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007408 if (track->isReady()) { // check ready to prevent premature start.
7409 processVolume_l(track, last);
7410 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007411 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007412
Eric Laurentea0fade2013-10-04 16:23:48 -07007413 // make sure the pause/flush/resume sequence is executed in the right order.
7414 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7415 // before flush and then resume HW. This can happen in case of pause/flush/resume
7416 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007417 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007418 status_t result = mOutput->stream->pause();
7419 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007420 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007421 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007422 if (mFlushPending) {
7423 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007424 }
Eric Laurentfd477972013-10-25 18:10:40 -07007425 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007426 status_t result = mOutput->stream->resume();
7427 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007428 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007429
Eric Laurentbfb1b832013-01-07 09:53:42 -08007430 // remove all the tracks that need to be...
7431 removeTracks_l(*tracksToRemove);
7432
7433 return mixerStatus;
7434}
7435
Eric Laurentbfb1b832013-01-07 09:53:42 -08007436// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007437bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007438{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007439 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7440 mWriteAckSequence, mDrainSequence);
7441 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007442 return true;
7443 }
7444 return false;
7445}
7446
Andy Hung4b17e882023-07-07 13:47:37 -07007447bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007448{
7449 Mutex::Autolock _l(mLock);
7450 return waitingAsyncCallback_l();
7451}
7452
Andy Hung4b17e882023-07-07 13:47:37 -07007453void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007454{
Eric Laurente659ef42014-09-29 13:06:46 -07007455 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007456 // Flush anything still waiting in the mixbuffer
7457 mCurrentWriteLength = 0;
7458 mBytesRemaining = 0;
7459 mPausedWriteLength = 0;
7460 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007461 // reset bytes written count to reflect that DSP buffers are empty after flush.
7462 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007463
Eric Laurentbfb1b832013-01-07 09:53:42 -08007464 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007465 // discard any pending drain or write ack by incrementing sequence
7466 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7467 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007468 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007469 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7470 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007471 }
7472}
7473
Andy Hung4b17e882023-07-07 13:47:37 -07007474void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007475{
7476 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007477 if (PlaybackThread::invalidateTracks_l(streamType)) {
7478 mFlushPending = true;
7479 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007480}
7481
Andy Hung4b17e882023-07-07 13:47:37 -07007482void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007483 Mutex::Autolock _l(mLock);
7484 if (PlaybackThread::invalidateTracks_l(portIds)) {
7485 mFlushPending = true;
7486 }
7487}
7488
Eric Laurentbfb1b832013-01-07 09:53:42 -08007489// ----------------------------------------------------------------------------
7490
Andy Hung4b17e882023-07-07 13:47:37 -07007491/* static */
7492sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007493 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007494 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007495 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007496}
7497
Andy Hung7535ed92023-07-17 17:05:00 -07007498DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007499 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007500 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007501 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007502 mWaitTimeMs(UINT_MAX)
7503{
7504 addOutputTrack(mainThread);
7505}
7506
Andy Hung4b17e882023-07-07 13:47:37 -07007507DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007508{
7509 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7510 mOutputTracks[i]->destroy();
7511 }
7512}
7513
Andy Hung4b17e882023-07-07 13:47:37 -07007514void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007515{
7516 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007517 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007518 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007519 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007520 if (mMixerBufferValid) {
7521 memset(mMixerBuffer, 0, mMixerBufferSize);
7522 } else {
7523 memset(mSinkBuffer, 0, mSinkBufferSize);
7524 }
Eric Laurent81784c32012-11-19 14:55:58 -08007525 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007526 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007527 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007528 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007529 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007530}
7531
Andy Hung4b17e882023-07-07 13:47:37 -07007532void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007533{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007534 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007535 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007536 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007537 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007538 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007539 }
7540 } else if (mBytesWritten != 0) {
7541 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7542 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007543 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007544 } else {
7545 // flush remaining overflow buffers in output tracks
7546 writeFrames = 0;
7547 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007548 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007549 }
7550}
7551
Andy Hung4b17e882023-07-07 13:47:37 -07007552ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007553{
7554 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007555 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7556
7557 // Consider the first OutputTrack for timestamp and frame counting.
7558
7559 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7560 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7561 // we always claim success.
7562 if (i == 0) {
7563 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7564 ALOGD_IF(correction != 0 && writeFrames != 0,
7565 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7566 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7567 mFramesWritten -= correction;
7568 }
7569
7570 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007571 }
Andy Hungcf10d742020-04-28 15:38:24 -07007572 if (mStandby) {
7573 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007574 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007575 mStandby = false;
7576 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007577 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007578}
7579
Andy Hung4b17e882023-07-07 13:47:37 -07007580void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007581{
7582 // DuplicatingThread implements standby by stopping all tracks
7583 for (size_t i = 0; i < outputTracks.size(); i++) {
7584 outputTracks[i]->stop();
7585 }
7586}
7587
Andy Hung4b17e882023-07-07 13:47:37 -07007588void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007589{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007590 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007591
7592 std::stringstream ss;
7593 const size_t numTracks = mOutputTracks.size();
7594 ss << " " << numTracks << " OutputTracks";
7595 if (numTracks > 0) {
7596 ss << ":";
7597 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007598 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007599 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007600 if (thread.get() != nullptr) {
7601 ss << thread.get() << ", " << thread->id();
7602 } else {
7603 ss << "null";
7604 }
7605 ss << ")";
7606 }
7607 }
7608 ss << "\n";
7609 std::string result = ss.str();
7610 write(fd, result.c_str(), result.size());
7611}
7612
Andy Hung4b17e882023-07-07 13:47:37 -07007613void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007614{
7615 outputTracks = mOutputTracks;
7616}
7617
Andy Hung4b17e882023-07-07 13:47:37 -07007618void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007619{
7620 outputTracks.clear();
7621}
7622
Andy Hung4b17e882023-07-07 13:47:37 -07007623void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007624{
7625 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007626 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7627 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7628 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7629 const size_t frameCount =
7630 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7631 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7632 // from different OutputTracks and their associated MixerThreads (e.g. one may
7633 // nearly empty and the other may be dropping data).
7634
Svet Ganov33761132021-05-13 22:51:08 +00007635 // TODO b/182392769: use attribution source util, move to server edge
7636 AttributionSourceState attributionSource = AttributionSourceState();
7637 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007638 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007639 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007640 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007641 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007642 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007643 this,
7644 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007645 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007646 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007647 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007648 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007649 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7650 if (status != NO_ERROR) {
7651 ALOGE("addOutputTrack() initCheck failed %d", status);
7652 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007653 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007654 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7655 mOutputTracks.add(outputTrack);
7656 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7657 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007658}
7659
Andy Hung4b17e882023-07-07 13:47:37 -07007660void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007661{
7662 Mutex::Autolock _l(mLock);
7663 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7664 if (mOutputTracks[i]->thread() == thread) {
7665 mOutputTracks[i]->destroy();
7666 mOutputTracks.removeAt(i);
7667 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007668 if (thread->getOutput() == mOutput) {
7669 mOutput = NULL;
7670 }
Eric Laurent81784c32012-11-19 14:55:58 -08007671 return;
7672 }
7673 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007674 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007675}
7676
7677// caller must hold mLock
Andy Hung4b17e882023-07-07 13:47:37 -07007678void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007679{
7680 mWaitTimeMs = UINT_MAX;
7681 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007682 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007683 if (strong != 0) {
7684 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7685 if (waitTimeMs < mWaitTimeMs) {
7686 mWaitTimeMs = waitTimeMs;
7687 }
7688 }
7689 }
7690}
7691
Andy Hung4b17e882023-07-07 13:47:37 -07007692bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007693{
7694 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007695 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007696 if (thread == 0) {
7697 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7698 outputTracks[i].get());
7699 return false;
7700 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007701 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007702 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007703 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007704 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7705 thread.get());
7706 return false;
7707 }
7708 }
7709 return true;
7710}
7711
Andy Hung4b17e882023-07-07 13:47:37 -07007712void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007713 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007714{
Kevin Rocard12381092018-04-11 09:19:59 -07007715 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7716 outputTrack->setMetadatas(metadata.tracks);
7717 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007718}
7719
Andy Hung4b17e882023-07-07 13:47:37 -07007720uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007721{
7722 return (mWaitTimeMs * 1000) / 2;
7723}
7724
Andy Hung4b17e882023-07-07 13:47:37 -07007725void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007726{
7727 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7728 updateWaitTime_l();
7729
7730 MixerThread::cacheParameters_l();
7731}
7732
Eric Laurentb3f315a2021-07-13 15:09:05 +02007733// ----------------------------------------------------------------------------
7734
Andy Hung4b17e882023-07-07 13:47:37 -07007735/* static */
7736sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007737 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007738 AudioStreamOut* output,
7739 audio_io_handle_t id,
7740 bool systemReady,
7741 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007742 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007743}
7744
Andy Hung7535ed92023-07-17 17:05:00 -07007745SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007746 AudioStreamOut* output,
7747 audio_io_handle_t id,
7748 bool systemReady,
7749 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007750 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007751{
7752}
7753
Andy Hung4b17e882023-07-07 13:47:37 -07007754void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007755 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007756
Andy Hung41ccf7f2022-12-14 14:25:49 -08007757 const pid_t tid = getTid();
7758 if (tid == -1) {
7759 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7760 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7761 } else {
7762 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7763 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007764 stream()->setHalThreadPriority(priorityBoost);
7765 }
7766 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007767}
7768
Andy Hung4b17e882023-07-07 13:47:37 -07007769void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007770 // if mSupportedLatencyModes is empty, the HAL stream does not support
7771 // latency mode control and we can exit.
7772 if (mSupportedLatencyModes.empty()) {
7773 return;
7774 }
7775 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7776 if (mSupportedLatencyModes.size() == 1) {
7777 // If the HAL only support one latency mode currently, confirm the choice
7778 latencyMode = mSupportedLatencyModes[0];
7779 } else if (mSupportedLatencyModes.size() > 1) {
7780 // Request low latency if:
7781 // - The low latency mode is requested by the spatializer controller
7782 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7783 // AND
7784 // - At least one active track is spatialized
7785 bool hasSpatializedActiveTrack = false;
7786 for (const auto& track : mActiveTracks) {
7787 if (track->isSpatialized()) {
7788 hasSpatializedActiveTrack = true;
7789 break;
7790 }
7791 }
7792 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7793 latencyMode = AUDIO_LATENCY_MODE_LOW;
7794 }
7795 }
7796
7797 if (latencyMode != mSetLatencyMode) {
7798 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007799 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7800 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007801 if (status == NO_ERROR) {
7802 mSetLatencyMode = latencyMode;
7803 }
7804 }
7805}
7806
Andy Hung4b17e882023-07-07 13:47:37 -07007807status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007808 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7809 return BAD_VALUE;
7810 }
7811 Mutex::Autolock _l(mLock);
7812 mRequestedLatencyMode = mode;
7813 return NO_ERROR;
7814}
7815
Andy Hung4b17e882023-07-07 13:47:37 -07007816void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007817{
7818 bool hasVirtualizer = false;
7819 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007820 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007821 {
7822 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07007823 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007824 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007825 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007826 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7827 }
7828
7829 finalDownMixer = mFinalDownMixer;
7830 mFinalDownMixer.clear();
7831 }
7832
7833 if (hasVirtualizer) {
7834 if (finalDownMixer != nullptr) {
7835 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007836 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007837 }
7838 finalDownMixer.clear();
7839 } else if (!hasDownMixer) {
7840 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07007841 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007842 EFFECT_UIID_DOWNMIX, &descriptors);
7843 if (status != NO_ERROR) {
7844 return;
7845 }
7846 ALOG_ASSERT(!descriptors.empty(),
7847 "%s getDescriptors() returned no error but empty list", __func__);
7848
7849 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7850 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007851 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007852
7853 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7854 ALOGW("%s error creating downmixer %d", __func__, status);
7855 finalDownMixer.clear();
7856 } else {
7857 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007858 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007859 }
7860 }
7861
7862 {
7863 Mutex::Autolock _l(mLock);
7864 mFinalDownMixer = finalDownMixer;
7865 }
7866}
7867
Eric Laurent81784c32012-11-19 14:55:58 -08007868// ----------------------------------------------------------------------------
7869// Record
7870// ----------------------------------------------------------------------------
7871
Andy Hung7535ed92023-07-17 17:05:00 -07007872sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007873 AudioStreamIn* input,
7874 audio_io_handle_t id,
7875 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007876 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07007877}
7878
Andy Hung7535ed92023-07-17 17:05:00 -07007879RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007880 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007881 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007882 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007883 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07007884 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007885 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007886 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007887 mActiveTracks(&this->mLocalLog),
7888 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007889 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007890 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007891 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7892 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007893 // mFastCapture below
7894 , mFastCaptureFutex(0)
7895 // mInputSource
7896 // mPipeSink
7897 // mPipeSource
7898 , mPipeFramesP2(0)
7899 // mPipeMemory
7900 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007901 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007902 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007903{
Glenn Kastend7dca052015-03-05 16:05:54 -08007904 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07007905 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007906
George Burgess IVa8f90c12020-05-14 11:27:19 -07007907 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007908 mIsMsdDevice = strcmp(
7909 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7910 }
7911
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007912 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007913
Andy Hungc8fddf32018-08-08 18:32:37 -07007914 // TODO: We may also match on address as well as device type for
7915 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007916 // TODO: This property should be ensure that only contains one single device type.
7917 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7918 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007919 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7920 : AUDIO_DEVICE_NONE));
7921
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007922 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007923 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007924 size_t numCounterOffers = 0;
7925 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007926#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007927 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007928#else
7929 (void)
7930#endif
7931 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007932 ALOG_ASSERT(index == 0);
7933
7934 // initialize fast capture depending on configuration
7935 bool initFastCapture;
7936 switch (kUseFastCapture) {
7937 case FastCapture_Never:
7938 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007939 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007940 break;
7941 case FastCapture_Always:
7942 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007943 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007944 break;
7945 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007946 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7947 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7948 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7949 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7950 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007951 break;
7952 // case FastCapture_Dynamic:
7953 }
7954
7955 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007956 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007957 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007958 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7959 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007960 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007961 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007962 const sp<MemoryDealer> roHeap(readOnlyHeap());
7963 sp<IMemory> pipeMemory;
7964 if ((roHeap == 0) ||
7965 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007966 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007967 ALOGE("not enough memory for pipe buffer size=%zu; "
7968 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7969 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7970 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007971 goto failed;
7972 }
7973 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7974 memset(pipeBuffer, 0, pipeSize);
7975 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007976 const NBAIO_Format offersFast[1] = {format};
7977 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007978 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007979 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007980 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007981 mPipeSink = pipe;
7982 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007983 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007984 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007985 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007986 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007987 mPipeSource = pipeReader;
7988 mPipeFramesP2 = pipeFramesP2;
7989 mPipeMemory = pipeMemory;
7990
7991 // create fast capture
7992 mFastCapture = new FastCapture();
7993 FastCaptureStateQueue *sq = mFastCapture->sq();
7994#ifdef STATE_QUEUE_DUMP
7995 // FIXME
7996#endif
7997 FastCaptureState *state = sq->begin();
7998 state->mCblk = NULL;
7999 state->mInputSource = mInputSource.get();
8000 state->mInputSourceGen++;
8001 state->mPipeSink = pipe;
8002 state->mPipeSinkGen++;
8003 state->mFrameCount = mFrameCount;
8004 state->mCommand = FastCaptureState::COLD_IDLE;
8005 // already done in constructor initialization list
8006 //mFastCaptureFutex = 0;
8007 state->mColdFutexAddr = &mFastCaptureFutex;
8008 state->mColdGen++;
8009 state->mDumpState = &mFastCaptureDumpState;
8010#ifdef TEE_SINK
8011 // FIXME
8012#endif
Andy Hung7535ed92023-07-17 17:05:00 -07008013 mFastCaptureNBLogWriter =
8014 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008015 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8016 sq->end();
8017 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8018
8019 // start the fast capture
8020 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8021 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008022 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008023 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008024#ifdef AUDIO_WATCHDOG
8025 // FIXME
8026#endif
8027
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008028 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008029 }
Andy Hung8946a282018-04-19 20:04:56 -07008030#ifdef TEE_SINK
8031 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8032 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8033#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008034failed: ;
8035
8036 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008037}
8038
Andy Hung4b17e882023-07-07 13:47:37 -07008039RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008040{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008041 if (mFastCapture != 0) {
8042 FastCaptureStateQueue *sq = mFastCapture->sq();
8043 FastCaptureState *state = sq->begin();
8044 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8045 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8046 if (old == -1) {
8047 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8048 }
8049 }
8050 state->mCommand = FastCaptureState::EXIT;
8051 sq->end();
8052 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8053 mFastCapture->join();
8054 mFastCapture.clear();
8055 }
Andy Hung7535ed92023-07-17 17:05:00 -07008056 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8057 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008058 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008059}
8060
Andy Hung4b17e882023-07-07 13:47:37 -07008061void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008062{
Glenn Kastend7dca052015-03-05 16:05:54 -08008063 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008064}
8065
Andy Hung4b17e882023-07-07 13:47:37 -07008066void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008067{
8068 ALOGV(" preExit()");
8069 Mutex::Autolock _l(mLock);
8070 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008071 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008072 track->invalidate();
8073 }
8074 mActiveTracks.clear();
8075 mStartStopCond.broadcast();
8076}
8077
Andy Hung4b17e882023-07-07 13:47:37 -07008078bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008079{
Eric Laurent81784c32012-11-19 14:55:58 -08008080 nsecs_t lastWarning = 0;
8081
8082 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008083
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008084reacquire_wakelock:
Andy Hung11e74242023-06-26 19:20:57 -07008085 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008086 {
8087 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008088 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008089 }
8090
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008091 // used to request a deferred sleep, to be executed later while mutex is unlocked
8092 uint32_t sleepUs = 0;
8093
Andy Hung446f4df2019-02-21 12:26:41 -08008094 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8095
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008096 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008097 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008098 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008099
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008100 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008101 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008102
Glenn Kasten735f45f2014-08-18 15:51:59 -07008103 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008104 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008105
Glenn Kasten735f45f2014-08-18 15:51:59 -07008106 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008107 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008108
Eric Laurent33403f02020-05-29 18:35:06 -07008109 bool silenceFastCapture = false;
8110
Eric Laurent81784c32012-11-19 14:55:58 -08008111 { // scope for mLock
8112 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008113
Eric Laurent021cf962014-05-13 10:18:14 -07008114 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008115
Eric Laurent000a4192014-01-29 15:17:32 -08008116 // check exitPending here because checkForNewParameters_l() and
8117 // checkForNewParameters_l() can temporarily release mLock
8118 if (exitPending()) {
8119 break;
8120 }
8121
Eric Laurent5c25d562016-07-13 17:17:45 -07008122 // sleep with mutex unlocked
8123 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008124 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008125 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8126 ATRACE_END();
8127 sleepUs = 0;
8128 continue;
8129 }
8130
Glenn Kasten2b806402013-11-20 16:37:38 -08008131 // if no active track(s), then standby and release wakelock
8132 size_t size = mActiveTracks.size();
8133 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008134 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008135 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008136 releaseWakeLock_l();
8137 ALOGV("RecordThread: loop stopping");
8138 // go to sleep
8139 mWaitWorkCV.wait(mLock);
8140 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008141 goto reacquire_wakelock;
8142 }
8143
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008144 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008145 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008146 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008147
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008148 activeTrack = mActiveTracks[i];
8149 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008150 if (activeTrack->isFastTrack()) {
8151 ALOG_ASSERT(fastTrackToRemove == 0);
8152 fastTrackToRemove = activeTrack;
8153 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008154 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008155 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008156 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008157 continue;
8158 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008159
Andy Hung11e74242023-06-26 19:20:57 -07008160 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008161 switch (activeTrackState) {
8162
Andy Hung11e74242023-06-26 19:20:57 -07008163 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008164 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008165 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008166 doBroadcast = true;
8167 size--;
8168 continue;
8169
Andy Hung11e74242023-06-26 19:20:57 -07008170 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008171 sleepUs = 10000;
8172 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008173 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008174 continue;
8175
Andy Hung11e74242023-06-26 19:20:57 -07008176 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008177 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008178 if (mStandby) {
8179 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008180 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008181 mStandby = false;
8182 }
Andy Hung11e74242023-06-26 19:20:57 -07008183 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008184 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008185 break;
8186
Andy Hung11e74242023-06-26 19:20:57 -07008187 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008188 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008189 break;
8190
Andy Hung11e74242023-06-26 19:20:57 -07008191 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8192 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8193 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008194 default:
Andy Hungce685402018-10-05 17:23:27 -07008195 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8196 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008197 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008198
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008199 if (activeTrack->isFastTrack()) {
8200 ALOG_ASSERT(!mFastTrackAvail);
8201 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008202 // if the active fast track is silenced either:
8203 // 1) silence the whole capture from fast capture buffer if this is
8204 // the only active track
8205 // 2) invalidate this track: this will cause the client to reconnect and possibly
8206 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008207 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008208 if (activeTrack->isSilenced()) {
8209 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008210 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008211 } else {
8212 silenceFastCapture = true;
8213 }
8214 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008215 // Invalidate fast tracks if access to audio history is required as this is not
8216 // possible with fast tracks. Once the fast track has been invalidated, no new
8217 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8218 if (mMaxSharedAudioHistoryMs != 0) {
8219 invalidate = true;
8220 }
8221 if (invalidate) {
8222 activeTrack->invalidate();
8223 ALOG_ASSERT(fastTrackToRemove == 0);
8224 fastTrackToRemove = activeTrack;
8225 removeTrack_l(activeTrack);
8226 mActiveTracks.remove(activeTrack);
8227 size--;
8228 continue;
8229 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008230 fastTrack = activeTrack;
8231 }
Eric Laurent33403f02020-05-29 18:35:06 -07008232
8233 activeTracks.add(activeTrack);
8234 i++;
8235
Glenn Kasten9e982352013-08-14 14:39:50 -07008236 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008237
Andy Hungdae27702016-10-31 14:01:16 -07008238 mActiveTracks.updatePowerState(this);
8239
Kevin Rocard069c2712018-03-29 19:09:14 -07008240 updateMetadata_l();
8241
Eric Laurent5c25d562016-07-13 17:17:45 -07008242 if (allStopped) {
8243 standbyIfNotAlreadyInStandby();
8244 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008245 if (doBroadcast) {
8246 mStartStopCond.broadcast();
8247 }
8248
8249 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008250 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008251 if (sleepUs == 0) {
8252 sleepUs = kRecordThreadSleepUs;
8253 }
8254 continue;
8255 }
8256 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008257
Eric Laurent81784c32012-11-19 14:55:58 -08008258 lockEffectChains_l(effectChains);
8259 }
8260
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008261 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008262
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008263 size_t size = effectChains.size();
8264 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008265 // thread mutex is not locked, but effect chain is locked
8266 effectChains[i]->process_l();
8267 }
8268
Glenn Kasten735f45f2014-08-18 15:51:59 -07008269 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008270 if (mFastCapture != 0) {
8271 FastCaptureStateQueue *sq = mFastCapture->sq();
8272 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008273 bool didModify = false;
8274 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008275 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8276 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8277 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8278 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8279 if (old == -1) {
8280 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8281 }
8282 }
8283 state->mCommand = FastCaptureState::READ_WRITE;
8284#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008285 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008286 FastThreadDumpState::kSamplingNforLowRamDevice :
8287 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008288#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008289 didModify = true;
8290 }
8291 audio_track_cblk_t *cblkOld = state->mCblk;
8292 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8293 if (cblkNew != cblkOld) {
8294 state->mCblk = cblkNew;
8295 // block until acked if removing a fast track
8296 if (cblkOld != NULL) {
8297 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8298 }
8299 didModify = true;
8300 }
jiabin01c8f562018-07-19 17:47:28 -07008301 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8302 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8303 if (state->mFastPatchRecordBufferProvider != abp) {
8304 state->mFastPatchRecordBufferProvider = abp;
8305 state->mFastPatchRecordFormat = fastTrack == 0 ?
8306 AUDIO_FORMAT_INVALID : fastTrack->format();
8307 didModify = true;
8308 }
Eric Laurent33403f02020-05-29 18:35:06 -07008309 if (state->mSilenceCapture != silenceFastCapture) {
8310 state->mSilenceCapture = silenceFastCapture;
8311 didModify = true;
8312 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008313 sq->end(didModify);
8314 if (didModify) {
8315 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008316#if 0
8317 if (kUseFastCapture == FastCapture_Dynamic) {
8318 mNormalSource = mPipeSource;
8319 }
8320#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008321 }
8322 }
8323
Glenn Kasten735f45f2014-08-18 15:51:59 -07008324 // now run the fast track destructor with thread mutex unlocked
8325 fastTrackToRemove.clear();
8326
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008327 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8328 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8329 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8330 // If destination is non-contiguous, first read past the nominal end of buffer, then
8331 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008332
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008333 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008334 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008335 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008336
8337 // If an NBAIO source is present, use it to read the normal capture's data
8338 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008339 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008340
8341 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8342 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8343 // we immediately retry the read() to get data and prevent another overflow.
8344 for (int retries = 0; retries <= 2; ++retries) {
8345 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8346 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8347 framesToRead);
8348 if (framesRead != OVERRUN) break;
8349 }
8350
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008351 const ssize_t availableToRead = mPipeSource->availableToRead();
8352 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008353 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008354 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008355 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8356 "more frames to read than fifo size, %zd > %zu",
8357 availableToRead, mPipeFramesP2);
8358 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8359 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8360 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8361 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008362 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8363 }
8364 if (framesRead < 0) {
8365 status_t status = (status_t) framesRead;
8366 switch (status) {
8367 case OVERRUN:
8368 ALOGW("overrun on read from pipe");
8369 framesRead = 0;
8370 break;
8371 case NEGOTIATE:
8372 ALOGE("re-negotiation is needed");
8373 framesRead = -1; // Will cause an attempt to recover.
8374 break;
8375 default:
8376 ALOGE("unknown error %d on read from pipe", status);
8377 break;
8378 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008379 }
8380 // otherwise use the HAL / AudioStreamIn directly
8381 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008382 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008383 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008384 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008385 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008386 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008387 if (result < 0) {
8388 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008389 } else {
8390 framesRead = bytesRead / mFrameSize;
8391 }
8392 }
8393
Andy Hung446f4df2019-02-21 12:26:41 -08008394 const int64_t lastIoEndNs = systemTime(); // end IO timing
8395
Andy Hung3f0c9022016-01-15 17:49:46 -08008396 // Update server timestamp with server stats
8397 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008398 if (framesRead >= 0) {
8399 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8400 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8401 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008402
8403 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008404 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008405 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008406 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008407 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8408 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8409 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008410 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008411 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8412
8413 mTimestampVerifier.add(position, time, mSampleRate);
8414
8415 // Correct timestamps
8416 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008417 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008418 id(), (long long)time, (long long)position);
8419 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8420 position = correctedTimestamp.mFrames;
8421 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008422 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008423 id(), (long long)time, (long long)position);
8424 }
8425
Andy Hung3f0c9022016-01-15 17:49:46 -08008426 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8427 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8428 // Note: In general record buffers should tend to be empty in
8429 // a properly running pipeline.
8430 //
8431 // Also, it is not advantageous to call get_presentation_position during the read
8432 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008433 } else {
8434 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008435 }
8436 }
Andy Hunge6c37112019-02-26 17:38:10 -08008437
8438 // From the timestamp, input read latency is negative output write latency.
8439 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008440 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008441 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8442 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8443 mLatencyMs.add(latencyMs);
8444 }
8445
Andy Hung3f0c9022016-01-15 17:49:46 -08008446 // Use this to track timestamp information
8447 // ALOGD("%s", mTimestamp.toString().c_str());
8448
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008449 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008450 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008451 // Force input into standby so that it tries to recover at next read attempt
8452 inputStandBy();
8453 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008454 }
8455 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008456 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008457 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008458 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008459 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008460
Andy Hung8946a282018-04-19 20:04:56 -07008461#ifdef TEE_SINK
8462 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8463#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008464 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008465 {
8466 size_t part1 = mRsmpInFramesP2 - rear;
8467 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008468 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008469 (framesRead - part1) * mFrameSize);
8470 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008472 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008473
8474 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008475
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008476 // loop over each active track
8477 for (size_t i = 0; i < size; i++) {
8478 activeTrack = activeTracks[i];
8479
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008480 // skip fast tracks, as those are handled directly by FastCapture
8481 if (activeTrack->isFastTrack()) {
8482 continue;
8483 }
8484
Andy Hung73c02e42015-03-29 01:13:58 -07008485 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008486 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8487
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008488 enum {
8489 OVERRUN_UNKNOWN,
8490 OVERRUN_TRUE,
8491 OVERRUN_FALSE
8492 } overrun = OVERRUN_UNKNOWN;
8493
8494 // loop over getNextBuffer to handle circular sink
8495 for (;;) {
8496
Andy Hung11e74242023-06-26 19:20:57 -07008497 activeTrack->sinkBuffer().frameCount = ~0;
8498 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8499 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008500 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8501
Andy Hung73c02e42015-03-29 01:13:58 -07008502 // check available frames and handle overrun conditions
8503 // if the record track isn't draining fast enough.
8504 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008505 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008506 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008507 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008508 overrun = OVERRUN_TRUE;
8509 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008510 if (framesOut == 0 || framesIn == 0) {
8511 break;
8512 }
8513
Andy Hung6770c6f2015-04-07 13:43:36 -07008514 // Don't allow framesOut to be larger than what is possible with resampling
8515 // from framesIn.
8516 // This isn't strictly necessary but helps limit buffer resizing in
8517 // RecordBufferConverter. TODO: remove when no longer needed.
8518 framesOut = min(framesOut,
8519 destinationFramesPossible(
Andy Hung11e74242023-06-26 19:20:57 -07008520 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008521
8522 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008523 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008524 // straight from RecordThread buffer to RecordTrack buffer.
8525 AudioBufferProvider::Buffer buffer;
8526 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008527 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008528 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008529 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008530 ALOGV_IF(buffer.frameCount != framesOut,
8531 "%s() read less than expected (%zu vs %zu)",
8532 __func__, buffer.frameCount, framesOut);
8533 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008534 memcpy(activeTrack->sinkBuffer().raw,
8535 buffer.raw, buffer.frameCount * mFrameSize);
8536 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008537 } else {
8538 framesOut = 0;
8539 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008540 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008541 }
8542 } else {
8543 // process frames from the RecordThread buffer provider to the RecordTrack
8544 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008545 framesOut = activeTrack->recordBufferConverter()->convert(
8546 activeTrack->sinkBuffer().raw,
8547 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008548 framesOut);
8549 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008550
8551 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8552 overrun = OVERRUN_FALSE;
8553 }
8554
Andy Hung93bb5732023-05-04 21:16:34 -07008555 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8556 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008557 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008558 if (framesToDrop == 0) {
8559 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008560 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008561 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008562 // Sanitize before releasing if the track has no access to the source data
8563 // An idle UID receives silence from non virtual devices until active
8564 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008565 memset(activeTrack->sinkBuffer().raw,
8566 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008567 }
Andy Hung11e74242023-06-26 19:20:57 -07008568 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008569 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008571 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008572 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008573 }
8574 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008575
8576 switch (overrun) {
8577 case OVERRUN_TRUE:
8578 // client isn't retrieving buffers fast enough
8579 if (!activeTrack->setOverflow()) {
8580 nsecs_t now = systemTime();
8581 // FIXME should lastWarning per track?
8582 if ((now - lastWarning) > kWarningThrottleNs) {
8583 ALOGW("RecordThread: buffer overflow");
8584 lastWarning = now;
8585 }
8586 }
8587 break;
8588 case OVERRUN_FALSE:
8589 activeTrack->clearOverflow();
8590 break;
8591 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008592 break;
8593 }
8594
Andy Hung3f0c9022016-01-15 17:49:46 -08008595 // update frame information and push timestamp out
8596 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008597 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008598 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8599 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008600 }
8601
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008602unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008603 // enable changes in effect chain
8604 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008605 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008606 if (audio_has_proportional_frames(mFormat)
8607 && loopCount == lastLoopCountRead + 1) {
8608 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8609 const double jitterMs =
8610 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8611 {framesRead, readPeriodNs},
8612 {0, 0} /* lastTimestamp */, mSampleRate);
8613 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8614
8615 Mutex::Autolock _l(mLock);
8616 mIoJitterMs.add(jitterMs);
8617 mProcessTimeMs.add(processMs);
8618 }
8619 // update timing info.
8620 mLastIoBeginNs = lastIoBeginNs;
8621 mLastIoEndNs = lastIoEndNs;
8622 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008623 }
8624
Glenn Kasten93e471f2013-08-19 08:40:07 -07008625 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008626
8627 {
8628 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008629 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008630 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008631 track->invalidate();
8632 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008633 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008634 mStartStopCond.broadcast();
8635 }
8636
8637 releaseWakeLock();
8638
8639 ALOGV("RecordThread %p exiting", this);
8640 return false;
8641}
8642
Andy Hung4b17e882023-07-07 13:47:37 -07008643void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008644{
8645 if (!mStandby) {
8646 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008647 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008648 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008649 mStandby = true;
8650 }
8651}
8652
Andy Hung4b17e882023-07-07 13:47:37 -07008653void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008654{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008655 // Idle the fast capture if it's currently running
8656 if (mFastCapture != 0) {
8657 FastCaptureStateQueue *sq = mFastCapture->sq();
8658 FastCaptureState *state = sq->begin();
8659 if (!(state->mCommand & FastCaptureState::IDLE)) {
8660 state->mCommand = FastCaptureState::COLD_IDLE;
8661 state->mColdFutexAddr = &mFastCaptureFutex;
8662 state->mColdGen++;
8663 mFastCaptureFutex = 0;
8664 sq->end();
8665 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8666 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8667#if 0
8668 if (kUseFastCapture == FastCapture_Dynamic) {
8669 // FIXME
8670 }
8671#endif
8672#ifdef AUDIO_WATCHDOG
8673 // FIXME
8674#endif
8675 } else {
8676 sq->end(false /*didModify*/);
8677 }
8678 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008679 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008680 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008681
8682 // If going into standby, flush the pipe source.
8683 if (mPipeSource.get() != nullptr) {
8684 const ssize_t flushed = mPipeSource->flush();
8685 if (flushed > 0) {
8686 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8687 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8688 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8689 }
8690 }
Eric Laurent81784c32012-11-19 14:55:58 -08008691}
8692
Glenn Kasten05997e22014-03-13 15:08:33 -07008693// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07008694sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008695 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008696 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008697 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008698 audio_format_t format,
8699 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008700 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008701 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008702 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008703 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008704 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008705 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008706 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008707 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008708 audio_port_handle_t portId,
8709 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008710{
Glenn Kasten74935e42013-12-19 08:56:45 -08008711 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008712 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008713 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008714 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008715 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008716 audio_input_flags_t requestedFlags = *flags;
8717 uint32_t sampleRate;
8718
8719 lStatus = initCheck();
8720 if (lStatus != NO_ERROR) {
8721 ALOGE("createRecordTrack_l() audio driver not initialized");
8722 goto Exit;
8723 }
8724
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008725 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8726 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8727 lStatus = BAD_VALUE;
8728 goto Exit;
8729 }
8730
Eric Laurentec376dc2021-04-08 20:41:22 +02008731 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008732 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008733 lStatus = PERMISSION_DENIED;
8734 goto Exit;
8735 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008736 if (maxSharedAudioHistoryMs < 0
Andy Hung409572b2023-07-19 12:47:35 -07008737 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008738 lStatus = BAD_VALUE;
8739 goto Exit;
8740 }
8741 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008742 if (*pSampleRate == 0) {
8743 *pSampleRate = mSampleRate;
8744 }
8745 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008746
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008747 // special case for FAST flag considered OK if fast capture is present and access to
8748 // audio history is not required
8749 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008750 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8751 }
8752
Eric Laurentf14db3c2017-12-08 14:20:36 -08008753 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008754 if ((*flags & inputFlags) != *flags) {
8755 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8756 " input flags (%08x)",
8757 *flags, inputFlags);
8758 *flags = (audio_input_flags_t)(*flags & inputFlags);
8759 }
Eric Laurent81784c32012-11-19 14:55:58 -08008760
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008761 // client expresses a preference for FAST and no access to audio history,
8762 // but we get the final say
8763 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008764 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008765 // we formerly checked for a callback handler (non-0 tid),
8766 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008767 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008768 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008769 // Frame count is not specified (0), or is less than or equal the pipe depth.
8770 // It is OK to provide a higher capacity than requested.
8771 // We will force it to mPipeFramesP2 below.
8772 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008773 // PCM data
8774 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008775 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008776 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008777 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008778 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008779 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008780 hasFastCapture() &&
8781 // there are sufficient fast track slots available
8782 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008783 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008784 // check compatibility with audio effects.
8785 Mutex::Autolock _l(mLock);
8786 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008787 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008788 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008789 audio_input_flags_t old = *flags;
8790 chain->checkInputFlagCompatibility(flags);
8791 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008792 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8793 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008794 }
8795 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008796 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008797 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8798 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008799 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008800 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8801 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008802 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008803 this, frameCount, mFrameCount, mPipeFramesP2,
8804 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008805 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008806 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008807 }
8808 }
8809
Eric Laurentf14db3c2017-12-08 14:20:36 -08008810 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8811 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8812 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8813 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8814 lStatus = BAD_TYPE;
8815 goto Exit;
8816 }
8817
Glenn Kasten74105912014-07-03 12:28:53 -07008818 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008819 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008820 // fast track: frame count is exactly the pipe depth
8821 frameCount = mPipeFramesP2;
8822 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008823 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008824 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008825 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8826 // or 20 ms if there is a fast capture
8827 // TODO This could be a roundupRatio inline, and const
8828 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8829 * sampleRate + mSampleRate - 1) / mSampleRate;
8830 // minimum number of notification periods is at least kMinNotifications,
8831 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8832 static const size_t kMinNotifications = 3;
8833 static const uint32_t kMinMs = 30;
8834 // TODO This could be a roundupRatio inline
8835 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8836 // TODO This could be a roundupRatio inline
8837 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8838 maxNotificationFrames;
8839 const size_t minFrameCount = maxNotificationFrames *
8840 max(kMinNotifications, minNotificationsByMs);
8841 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008842 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8843 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008844 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008845 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008846 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008847 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008848
8849 { // scope for mLock
8850 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008851 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008852 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008853 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008854 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008855 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008856 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008857 }
Eric Laurent81784c32012-11-19 14:55:58 -08008858
Andy Hung11e74242023-06-26 19:20:57 -07008859 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008860 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008861 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07008862 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008863 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008864
Glenn Kasten03003332013-08-06 15:40:54 -07008865 lStatus = track->initCheck();
8866 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008867 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008868 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008869 goto Exit;
8870 }
8871 mTracks.add(track);
8872
Eric Laurent05067782016-06-01 18:27:28 -07008873 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008874 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8875 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8876 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008877 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008878 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008879
8880 if (maxSharedAudioHistoryMs != 0) {
8881 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8882 }
Eric Laurent81784c32012-11-19 14:55:58 -08008883 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008884
Eric Laurent81784c32012-11-19 14:55:58 -08008885 lStatus = NO_ERROR;
8886
8887Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008888 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008889 return track;
8890}
8891
Andy Hung4b17e882023-07-07 13:47:37 -07008892status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008893 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008894 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008895{
8896 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8897 sp<ThreadBase> strongMe = this;
8898 status_t status = NO_ERROR;
8899
8900 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008901 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008902 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07008903 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07008904 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008905 event, triggerSession,
8906 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008907 }
8908
8909 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008910 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008911 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008912 if (recordTrack->isInvalid()) {
8913 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008914 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8915 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008916 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008917 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008918 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008919 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8920 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008921 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07008922 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008923 } else {
Andy Hung11e74242023-06-26 19:20:57 -07008924 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008925 }
8926 return status;
8927 }
8928
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008929 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8930 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8931 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07008932 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008933 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008934 if (recordTrack->isExternalTrack()) {
8935 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008936 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008937 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008938 if (recordTrack->isInvalid()) {
8939 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07008940 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8941 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008942 // STARTING_2 forces destroy to call stopInput.
8943 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008944 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8945 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008946 }
Andy Hung11e74242023-06-26 19:20:57 -07008947 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008948 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07008949 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008950 // Someone else has changed state, let them take over,
8951 // leave mState in the new state.
8952 recordTrack->clearSyncStartEvent();
8953 return INVALID_OPERATION;
8954 }
8955 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008956 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008957 ALOGW("%s(%d): startInput failed, status %d",
8958 __func__, recordTrack->id(), status);
8959 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8960 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008961 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008962 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008963 return status;
8964 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008965 sendIoConfigEvent_l(
8966 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008967 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008968
8969 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8970
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008971 // Catch up with current buffer indices if thread is already running.
8972 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8973 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8974 // see previously buffered data before it called start(), but with greater risk of overrun.
8975
Andy Hung11e74242023-06-26 19:20:57 -07008976 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008977 if (!recordTrack->isDirect()) {
8978 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07008979 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008980 }
Andy Hung11e74242023-06-26 19:20:57 -07008981 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008982 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008983 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008984 return status;
8985 }
Eric Laurent81784c32012-11-19 14:55:58 -08008986}
8987
Andy Hung4b17e882023-07-07 13:47:37 -07008988void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008989{
Andy Hung4b17e882023-07-07 13:47:37 -07008990 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008991
8992 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07008993 sp<IAfTrackBase> ptr =
8994 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8995 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07008996 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07008997 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008998 }
Eric Laurent81784c32012-11-19 14:55:58 -08008999 }
9000}
9001
Andy Hung4b17e882023-07-07 13:47:37 -07009002bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009003 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07009004 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07009005 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07009006 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009007 return false;
9008 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009009 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07009010 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009011
Andy Hungabfab202019-03-07 19:45:54 -08009012 // NOTE: Waiting here is important to keep stop synchronous.
9013 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07009014 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07009015 mWaitWorkCV.broadcast(); // signal thread to stop
9016 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08009017 }
Andy Hungce685402018-10-05 17:23:27 -07009018
Andy Hung11e74242023-06-26 19:20:57 -07009019 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009020 ALOGV("Record stopped OK");
9021 return true;
9022 }
Andy Hungce685402018-10-05 17:23:27 -07009023
9024 // don't handle anything - we've been invalidated or restarted and in a different state
9025 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07009026 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009027 return false;
9028}
9029
Andy Hung4b17e882023-07-07 13:47:37 -07009030bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009031{
9032 return false;
9033}
9034
Andy Hung4b17e882023-07-07 13:47:37 -07009035status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009036{
9037#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9038 if (!isValidSyncEvent(event)) {
9039 return BAD_VALUE;
9040 }
9041
Glenn Kastend848eb42016-03-08 13:42:11 -08009042 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009043 status_t ret = NAME_NOT_FOUND;
9044
9045 Mutex::Autolock _l(mLock);
9046
9047 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009048 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009049 if (eventSession == track->sessionId()) {
9050 (void) track->setSyncEvent(event);
9051 ret = NO_ERROR;
9052 }
9053 }
9054 return ret;
9055#else
9056 return BAD_VALUE;
9057#endif
9058}
9059
Andy Hung4b17e882023-07-07 13:47:37 -07009060status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07009061 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009062{
9063 ALOGV("RecordThread::getActiveMicrophones");
9064 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009065 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009066 return NO_INIT;
9067 }
jiabin9ff780e2018-03-19 18:19:52 -07009068 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9069 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009070}
9071
Andy Hung4b17e882023-07-07 13:47:37 -07009072status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009073 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009074{
Paul McLean12340082019-03-19 09:35:05 -06009075 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009076 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009077 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009078 return NO_INIT;
9079 }
Paul McLean12340082019-03-19 09:35:05 -06009080 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009081}
9082
Andy Hung4b17e882023-07-07 13:47:37 -07009083status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009084{
Paul McLean12340082019-03-19 09:35:05 -06009085 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009086 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 }
Paul McLean12340082019-03-19 09:35:05 -06009090 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009091}
9092
Andy Hung4b17e882023-07-07 13:47:37 -07009093status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009094 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9095 int64_t sharedAudioStartMs) {
9096 AutoMutex _l(mLock);
9097 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9098}
9099
Andy Hung4b17e882023-07-07 13:47:37 -07009100status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009101 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9102 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009103
Eric Laurentec376dc2021-04-08 20:41:22 +02009104 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9105 return BAD_VALUE;
9106 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009107
9108 if (sharedAudioStartMs < 0
9109 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009110 return BAD_VALUE;
9111 }
9112
Eric Laurent2407ce32021-04-26 14:56:03 +02009113 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9114 // As we cannot detect more than one wraparound, only accept values up current write position
9115 // after one wraparound
9116 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9117 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009118 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009119 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9120 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009121 // Bring the start frame position within the input buffer to match the documented
9122 // "best effort" behavior of the API.
9123 if (sharedOffset < 0) {
9124 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009125 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009126 sharedAudioStartFrames =
9127 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009128 }
9129
Eric Laurentec376dc2021-04-08 20:41:22 +02009130 mSharedAudioPackageName = sharedAudioPackageName;
9131 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009132 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009133 } else {
9134 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009135 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009136 }
9137 return NO_ERROR;
9138}
9139
Andy Hung4b17e882023-07-07 13:47:37 -07009140void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009141 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9142 mSharedAudioStartFrames = -1;
9143 mSharedAudioPackageName = "";
9144}
9145
Andy Hung4b17e882023-07-07 13:47:37 -07009146ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009147{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009148 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009149 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009150 }
9151 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009152 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009153 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009154 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009155 }
9156 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009157 MetadataUpdate change;
9158 change.recordMetadataUpdate = metadata.tracks;
9159 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009160}
9161
Eric Laurent81784c32012-11-19 14:55:58 -08009162// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07009163void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009164{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009165 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009166 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009167
Eric Laurent81784c32012-11-19 14:55:58 -08009168 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009169 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009170 removeTrack_l(track);
9171 }
9172}
9173
Andy Hung4b17e882023-07-07 13:47:37 -07009174void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009175{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009176 String8 result;
9177 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009178 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009179
Eric Laurent81784c32012-11-19 14:55:58 -08009180 mTracks.remove(track);
9181 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009182 if (track->isFastTrack()) {
9183 ALOG_ASSERT(!mFastTrackAvail);
9184 mFastTrackAvail = true;
9185 }
Eric Laurent81784c32012-11-19 14:55:58 -08009186}
9187
Andy Hung4b17e882023-07-07 13:47:37 -07009188void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009189{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009190 AudioStreamIn *input = mInput;
9191 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9192 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009193 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009194 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009195 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009196 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009197 }
Andy Hungbfa64962017-06-12 14:43:19 -07009198
9199 if (input != nullptr) {
9200 dprintf(fd, " Hal stream dump:\n");
9201 (void)input->stream->dump(fd);
9202 }
9203
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009204 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009205 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009206
Glenn Kasten2f90c512015-12-02 11:40:09 -08009207 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9208 // while we are dumping it. It may be inconsistent, but it won't mutate!
9209 // This is a large object so we place it on the heap.
9210 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009211 const std::unique_ptr<FastCaptureDumpState> copy =
9212 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009213 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009214}
9215
Andy Hung4b17e882023-07-07 13:47:37 -07009216void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009217{
Eric Laurent81784c32012-11-19 14:55:58 -08009218 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009219 size_t numtracks = mTracks.size();
9220 size_t numactive = mActiveTracks.size();
9221 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009222 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009223 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009224 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009225 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009226 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009227 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009228 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009229 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009230 if (track != 0) {
9231 bool active = mActiveTracks.indexOf(track) >= 0;
9232 if (active) {
9233 numactiveseen++;
9234 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009235 result.append(prefix);
9236 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009237 }
Eric Laurent81784c32012-11-19 14:55:58 -08009238 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009239 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009240 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009241 }
9242
Marco Nelissenb2208842014-02-07 14:00:50 -08009243 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009244 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009245 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009246 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009247 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009248 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009249 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009250 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009251 result.append(prefix);
9252 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009253 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009254 }
Eric Laurent81784c32012-11-19 14:55:58 -08009255
9256 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009257 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009258}
9259
Andy Hung4b17e882023-07-07 13:47:37 -07009260void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009261{
9262 Mutex::Autolock _l(mLock);
9263 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009264 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009265 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009266 track->setSilenced(silenced);
9267 }
9268 }
9269}
Andy Hung73c02e42015-03-29 01:13:58 -07009270
Andy Hung11e74242023-06-26 19:20:57 -07009271void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009272{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009273 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009274 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009275 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009276 const int32_t rear = recordThread->mRsmpInRear;
9277 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009278 if (mRecordTrack->startFrames() >= 0) {
9279 int32_t startFrames = mRecordTrack->startFrames();
9280 // Accept a recent wraparound of mRsmpInRear
9281 if (startFrames <= rear) {
9282 deltaFrames = rear - startFrames;
9283 } else {
9284 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009285 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009286 // start frame cannot be further in the past than start of resampling buffer
9287 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9288 deltaFrames = recordThread->mRsmpInFrames;
9289 }
9290 }
9291 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009292}
9293
Andy Hung11e74242023-06-26 19:20:57 -07009294void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009295 size_t *framesAvailable, bool *hasOverrun)
9296{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009297 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009298 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009299 const int32_t rear = recordThread->mRsmpInRear;
9300 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009301 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009302
9303 size_t framesIn;
9304 bool overrun = false;
9305 if (filled < 0) {
9306 // should not happen, but treat like a massive overrun and re-sync
9307 framesIn = 0;
9308 mRsmpInFront = rear;
9309 overrun = true;
9310 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9311 framesIn = (size_t) filled;
9312 } else {
9313 // client is not keeping up with server, but give it latest data
9314 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009315 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9316 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009317 overrun = true;
9318 }
9319 if (framesAvailable != NULL) {
9320 *framesAvailable = framesIn;
9321 }
9322 if (hasOverrun != NULL) {
9323 *hasOverrun = overrun;
9324 }
9325}
9326
Eric Laurent81784c32012-11-19 14:55:58 -08009327// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009328status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009329 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009330{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009331 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009332 if (threadBase == 0) {
9333 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009334 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009335 return NOT_ENOUGH_DATA;
9336 }
Andy Hung4b17e882023-07-07 13:47:37 -07009337 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009338 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009339 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009340 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009341 // FIXME should not be P2 (don't want to increase latency)
9342 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009343 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009344 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009345
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009346 front &= recordThread->mRsmpInFramesP2 - 1;
9347 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009348 if (part1 > (size_t) filled) {
9349 part1 = filled;
9350 }
9351 size_t ask = buffer->frameCount;
9352 ALOG_ASSERT(ask > 0);
9353 if (part1 > ask) {
9354 part1 = ask;
9355 }
9356 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009357 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009358 buffer->raw = NULL;
9359 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009360 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009361 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009362 }
9363
Andy Hung57446612015-04-19 23:56:46 -07009364 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009365 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009366 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009367 return NO_ERROR;
9368}
9369
9370// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009371void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009372 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009373{
Hongwei Wang95e37682019-04-12 11:13:36 -07009374 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009375 if (stepCount == 0) {
9376 return;
9377 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009378 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009379 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009380 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009381 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009382 buffer->frameCount = 0;
9383}
9384
Andy Hung4b17e882023-07-07 13:47:37 -07009385void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009386{
9387 Mutex::Autolock _l(mLock);
9388 checkBtNrec_l();
9389}
9390
Andy Hung4b17e882023-07-07 13:47:37 -07009391void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009392{
9393 // disable AEC and NS if the device is a BT SCO headset supporting those
9394 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009395 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009396 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009397 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9398 for (size_t i = 0; i < mEffectChains.size(); i++) {
9399 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9400 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9401 }
9402 }
9403}
9404
Andy Hung97a893e2015-03-29 01:03:07 -07009405
Andy Hung4b17e882023-07-07 13:47:37 -07009406bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009407 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009408{
9409 bool reconfig = false;
9410
Eric Laurent10351942014-05-08 18:49:52 -07009411 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009412
Eric Laurent10351942014-05-08 18:49:52 -07009413 audio_format_t reqFormat = mFormat;
9414 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009415 // 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 +08009416 [[maybe_unused]] audio_channel_mask_t channelMask =
9417 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009418
9419 AudioParameter param = AudioParameter(keyValuePair);
9420 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009421
9422 // scope for AutoPark extends to end of method
9423 AutoPark<FastCapture> park(mFastCapture);
9424
Eric Laurent10351942014-05-08 18:49:52 -07009425 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9426 // channel count change can be requested. Do we mandate the first client defines the
9427 // HAL sampling rate and channel count or do we allow changes on the fly?
9428 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9429 samplingRate = value;
9430 reconfig = true;
9431 }
9432 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009433 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009434 status = BAD_VALUE;
9435 } else {
9436 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009437 reconfig = true;
9438 }
Eric Laurent10351942014-05-08 18:49:52 -07009439 }
9440 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9441 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009442 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009443 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009444 status = BAD_VALUE;
9445 } else {
9446 channelMask = mask;
9447 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009448 }
Eric Laurent10351942014-05-08 18:49:52 -07009449 }
9450 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9451 // do not accept frame count changes if tracks are open as the track buffer
9452 // size depends on frame count and correct behavior would not be guaranteed
9453 // if frame count is changed after track creation
9454 if (mActiveTracks.size() > 0) {
9455 status = INVALID_OPERATION;
9456 } else {
9457 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009458 }
Eric Laurent10351942014-05-08 18:49:52 -07009459 }
9460 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009461 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009462 }
9463 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9464 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009465 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009466 }
Glenn Kastene198c362013-08-13 09:13:36 -07009467
Eric Laurent10351942014-05-08 18:49:52 -07009468 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009469 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009470 if (status == INVALID_OPERATION) {
9471 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009472 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009473 }
9474 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009475 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009476 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9477 if (mInput->stream->getAudioProperties(&config) == OK &&
9478 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9479 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009480 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009481 status = NO_ERROR;
9482 }
Eric Laurent81784c32012-11-19 14:55:58 -08009483 }
Eric Laurent10351942014-05-08 18:49:52 -07009484 if (status == NO_ERROR) {
9485 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009486 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009487 }
9488 }
Eric Laurent81784c32012-11-19 14:55:58 -08009489 }
Eric Laurent10351942014-05-08 18:49:52 -07009490
Eric Laurent81784c32012-11-19 14:55:58 -08009491 return reconfig;
9492}
9493
Andy Hung4b17e882023-07-07 13:47:37 -07009494String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009495{
Eric Laurent81784c32012-11-19 14:55:58 -08009496 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009497 if (initCheck() == NO_ERROR) {
9498 String8 out_s8;
9499 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9500 return out_s8;
9501 }
Eric Laurent81784c32012-11-19 14:55:58 -08009502 }
Andy Hung920f6572022-10-06 12:09:49 -07009503 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009504}
9505
Andy Hung4b17e882023-07-07 13:47:37 -07009506void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009507 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009508 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009509 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009510 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009511 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009512 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009513 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9514 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009515 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009516 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009517 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009518 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009519 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009520 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009521 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009522 break;
9523 }
Andy Hung7535ed92023-07-17 17:05:00 -07009524 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009525}
9526
Andy Hung4b17e882023-07-07 13:47:37 -07009527void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009528{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009529 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9530 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009531 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009532 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9533 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009534 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9535 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009536 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009537 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009538 ALOGI("HAL format %#x is not linear pcm", mFormat);
9539 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009540 result = mInput->stream->getFrameSize(&mFrameSize);
9541 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009542 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9543 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009544 result = mInput->stream->getBufferSize(&mBufferSize);
9545 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009546 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009547 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9548 "mBufferSize=%zu, mFrameCount=%zu",
9549 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009550
Eric Laurentec376dc2021-04-08 20:41:22 +02009551 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9552 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009553 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009554
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009555 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9556 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009557
9558 audio_input_flags_t flags = mInput->flags;
9559 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9560 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07009561 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009562 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9563 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9564 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9565 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9566 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9567 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009568}
9569
Andy Hung4b17e882023-07-07 13:47:37 -07009570uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009571{
9572 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009573 uint32_t result;
9574 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9575 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009576 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009577 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009578}
9579
Andy Hung4b17e882023-07-07 13:47:37 -07009580KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009581{
Glenn Kastend848eb42016-03-08 13:42:11 -08009582 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009583 Mutex::Autolock _l(mLock);
9584 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009585 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009586 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009587 if (ids.indexOfKey(sessionId) < 0) {
9588 ids.add(sessionId, true);
9589 }
9590 }
9591 return ids;
9592}
9593
Andy Hung4b17e882023-07-07 13:47:37 -07009594AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009595{
9596 Mutex::Autolock _l(mLock);
9597 AudioStreamIn *input = mInput;
9598 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009599 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009600 return input;
9601}
9602
9603// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009604sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009605{
9606 if (mInput == NULL) {
9607 return NULL;
9608 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009609 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009610}
9611
Andy Hung4b17e882023-07-07 13:47:37 -07009612status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009613{
Eric Laurent81784c32012-11-19 14:55:58 -08009614 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009615 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009616 chain->setInBuffer(NULL);
9617 chain->setOutBuffer(NULL);
9618
9619 checkSuspendOnAddEffectChain_l(chain);
9620
Eric Laurent1b928682014-10-02 19:41:47 -07009621 // make sure enabled pre processing effects state is communicated to the HAL as we
9622 // just moved them to a new input stream.
9623 chain->syncHalEffectsState();
9624
Eric Laurent81784c32012-11-19 14:55:58 -08009625 mEffectChains.add(chain);
9626
9627 return NO_ERROR;
9628}
9629
Andy Hung4b17e882023-07-07 13:47:37 -07009630size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009631{
9632 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009633
9634 for (size_t i = 0; i < mEffectChains.size(); i++) {
9635 if (chain == mEffectChains[i]) {
9636 mEffectChains.removeAt(i);
9637 break;
9638 }
Eric Laurent81784c32012-11-19 14:55:58 -08009639 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009640 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009641}
9642
Andy Hung4b17e882023-07-07 13:47:37 -07009643status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009644 audio_patch_handle_t *handle)
9645{
9646 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009647
9648 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009649 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009650 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009651 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009652 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009653 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009654 }
9655
Eric Laurentd8365c52017-07-16 15:27:05 -07009656 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009657
9658 // store new source and send to effects
9659 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9660 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009661 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009662 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009663 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009664 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009665
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009666 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009667 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9668 status = hwDevice->createAudioPatch(patch->num_sources,
9669 patch->sources,
9670 patch->num_sinks,
9671 patch->sinks,
9672 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009673 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009674 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9675 patch->sinks[0].ext.mix.usecase.source,
9676 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009677 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009678 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009679
jiabinc52b1ff2019-10-31 17:20:42 -07009680 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009681 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009682 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009683 }
Eric Laurent296fb132015-05-01 11:38:42 -07009684
Andy Hungc2b11cb2020-04-22 09:04:01 -07009685 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009686 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009687 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009688 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009689 // also dispatch to active AudioRecords
9690 for (const auto &track : mActiveTracks) {
9691 track->logEndInterval();
9692 track->logBeginInterval(pathSourcesAsString);
9693 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009694 // Force meteadata update after a route change
9695 mActiveTracks.setHasChanged();
9696
Eric Laurent1c333e22014-05-20 10:48:17 -07009697 return status;
9698}
9699
Andy Hung4b17e882023-07-07 13:47:37 -07009700status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009701{
9702 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009703
jiabinc52b1ff2019-10-31 17:20:42 -07009704 mPatch = audio_patch{};
9705 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009706
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009707 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009708 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9709 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009710 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009711 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009712 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009713 // Force meteadata update after a route change
9714 mActiveTracks.setHasChanged();
9715
Eric Laurent1c333e22014-05-20 10:48:17 -07009716 return status;
9717}
9718
Andy Hung4b17e882023-07-07 13:47:37 -07009719void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009720{
wendy lin56aa82b2020-12-02 15:19:55 +08009721 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009722 mOutDevices = outDevices;
9723 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9724 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009725 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009726 }
9727}
9728
Andy Hung4b17e882023-07-07 13:47:37 -07009729int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009730{
9731 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009732 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009733 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009734 int32_t oldestFront = mRsmpInRear;
9735 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009736 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009737 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009738 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009739 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009740 if (filled > maxFilled) {
9741 oldestFront = front;
9742 maxFilled = filled;
9743 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009744 }
Andy Hung920f6572022-10-06 12:09:49 -07009745 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009746 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9747 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009748 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009749}
9750
Andy Hung4b17e882023-07-07 13:47:37 -07009751void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009752{
9753 if (offset == 0) {
9754 return;
9755 }
9756 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009757 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009758 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009759 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009760 }
9761}
9762
Andy Hung4b17e882023-07-07 13:47:37 -07009763void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009764{
9765 // This is the formula for calculating the temporary buffer size.
9766 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9767 // 1 full output buffer, regardless of the alignment of the available input.
9768 // The value is somewhat arbitrary, and could probably be even larger.
9769 // A larger value should allow more old data to be read after a track calls start(),
9770 // without increasing latency.
9771 //
9772 // Note this is independent of the maximum downsampling ratio permitted for capture.
9773 size_t minRsmpInFrames = mFrameCount * 7;
9774
9775 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9776 // capture history available to another client using the same session ID:
9777 // dimension the resampler input buffer accordingly.
9778
9779 // Get oldest client read position: getOldestFront_l() must be called before altering
9780 // mRsmpInRear, or mRsmpInFrames
9781 int32_t previousFront = getOldestFront_l();
9782 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9783 int32_t previousRear = mRsmpInRear;
9784 mRsmpInRear = 0;
9785
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009786 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009787 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009788 "resizeInputBuffer_l() called with invalid max shared history %d",
9789 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009790 if (maxSharedAudioHistoryMs != 0) {
9791 // resizeInputBuffer_l should never be called with a non zero shared history if the
9792 // buffer was not already allocated
9793 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9794 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9795 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9796 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009797 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009798 return;
9799 }
9800 mRsmpInFrames = rsmpInFrames;
9801 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009802 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009803 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9804 // initialized
9805 if (mRsmpInFrames < minRsmpInFrames) {
9806 mRsmpInFrames = minRsmpInFrames;
9807 }
9808 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9809
9810 // TODO optimize audio capture buffer sizes ...
9811 // Here we calculate the size of the sliding buffer used as a source
9812 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9813 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9814 // be better to have it derived from the pipe depth in the long term.
9815 // The current value is higher than necessary. However it should not add to latency.
9816
9817 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9818 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9819
9820 void *rsmpInBuffer;
9821 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9822 // if posix_memalign fails, will segv here.
9823 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9824
9825 // Copy audio history if any from old buffer before freeing it
9826 if (previousRear != 0) {
9827 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9828 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9829
9830 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9831 previousFront &= previousRsmpInFramesP2 - 1;
9832 size_t part1 = previousRsmpInFramesP2 - previousFront;
9833 if (part1 > (size_t) unread) {
9834 part1 = unread;
9835 }
9836 if (part1 != 0) {
9837 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9838 part1 * mFrameSize);
9839 mRsmpInRear = part1;
9840 part1 = unread - part1;
9841 if (part1 != 0) {
9842 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9843 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9844 mRsmpInRear += part1;
9845 }
9846 }
9847 // Update front for all clients according to new rear
9848 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9849 } else {
9850 mRsmpInRear = 0;
9851 }
9852 free(mRsmpInBuffer);
9853 mRsmpInBuffer = rsmpInBuffer;
9854}
9855
Andy Hung4b17e882023-07-07 13:47:37 -07009856void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009857{
9858 Mutex::Autolock _l(mLock);
9859 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009860 if (record->getSource()) {
9861 mSource = record->getSource();
9862 }
Eric Laurent83b88082014-06-20 18:31:16 -07009863}
9864
Andy Hung4b17e882023-07-07 13:47:37 -07009865void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009866{
9867 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009868 if (mSource == record->getSource()) {
9869 mSource = mInput;
9870 }
Eric Laurent83b88082014-06-20 18:31:16 -07009871 destroyTrack_l(record);
9872}
9873
Andy Hung4b17e882023-07-07 13:47:37 -07009874void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009875{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009876 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009877 config->role = AUDIO_PORT_ROLE_SINK;
9878 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9879 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009880 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9881 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9882 config->flags.input = mInput->flags;
9883 }
Eric Laurent83b88082014-06-20 18:31:16 -07009884}
Eric Laurent1c333e22014-05-20 10:48:17 -07009885
Eric Laurent6acd1d42017-01-04 14:23:29 -08009886// ----------------------------------------------------------------------------
9887// Mmap
9888// ----------------------------------------------------------------------------
9889
Andy Hung765de282023-07-07 15:58:48 -07009890// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9891// MmapPlaybackThread or MmapCaptureThread instance.
9892class MmapThreadHandle : public MmapStreamInterface {
9893public:
9894 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9895 ~MmapThreadHandle() override;
9896
9897 // MmapStreamInterface virtuals
9898 status_t createMmapBuffer(int32_t minSizeFrames,
9899 struct audio_mmap_buffer_info* info) final;
9900 status_t getMmapPosition(struct audio_mmap_position* position) final;
9901 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9902 status_t start(const AudioClient& client,
9903 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9904 status_t stop(audio_port_handle_t handle) final;
9905 status_t standby() final;
9906 status_t reportData(const void* buffer, size_t frameCount) final;
9907private:
9908 const sp<IAfMmapThread> mThread;
9909};
9910
9911/* static */
9912sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9913 const sp<IAfMmapThread>& mmapThread) {
9914 return sp<MmapThreadHandle>::make(mmapThread);
9915}
9916
9917MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009918 : mThread(thread)
9919{
Phil Burk9fabbf82017-08-03 12:02:00 -07009920 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009921}
9922
Andy Hung765de282023-07-07 15:58:48 -07009923// MmapStreamInterface could be directly implemented by MmapThread excepting this
9924// special handling on adapter dtor.
9925MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009926{
Phil Burk9fabbf82017-08-03 12:02:00 -07009927 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009928}
9929
Andy Hung765de282023-07-07 15:58:48 -07009930status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009931 struct audio_mmap_buffer_info *info)
9932{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009933 return mThread->createMmapBuffer(minSizeFrames, info);
9934}
9935
Andy Hung765de282023-07-07 15:58:48 -07009936status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009937{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009938 return mThread->getMmapPosition(position);
9939}
9940
Andy Hung765de282023-07-07 15:58:48 -07009941status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009942 int64_t *timeNanos) {
9943 return mThread->getExternalPosition(position, timeNanos);
9944}
9945
Andy Hung765de282023-07-07 15:58:48 -07009946status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009947 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948{
jiabind1f1cb62020-03-24 11:57:57 -07009949 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009950}
9951
Andy Hung765de282023-07-07 15:58:48 -07009952status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009954 return mThread->stop(handle);
9955}
9956
Andy Hung765de282023-07-07 15:58:48 -07009957status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009958{
Eric Laurent18b57012017-02-13 16:23:52 -08009959 return mThread->standby();
9960}
9961
Andy Hung765de282023-07-07 15:58:48 -07009962status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9963{
jiabinfc791ee2023-02-15 19:43:40 +00009964 return mThread->reportData(buffer, frameCount);
9965}
9966
Eric Laurent6acd1d42017-01-04 14:23:29 -08009967
Andy Hung4b17e882023-07-07 13:47:37 -07009968MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -07009969 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009970 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -07009971 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009972 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009973 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009974 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009975 mActiveTracks(&this->mLocalLog),
9976 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9977 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009978{
Eric Laurent18b57012017-02-13 16:23:52 -08009979 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009980 readHalParameters_l();
9981}
9982
Andy Hung4b17e882023-07-07 13:47:37 -07009983void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009984{
9985 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9986}
9987
Andy Hung4b17e882023-07-07 13:47:37 -07009988void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009989{
Andy Hung11e74242023-06-26 19:20:57 -07009990 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009991 {
9992 Mutex::Autolock _l(mLock);
Andy Hung11e74242023-06-26 19:20:57 -07009993 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009994 activeTracks.add(t);
9995 }
9996 }
Andy Hung11e74242023-06-26 19:20:57 -07009997 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009998 stop(t->portId());
9999 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010000 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010001 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010002 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010003 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010004 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005 }
10006}
10007
10008
Andy Hung4b17e882023-07-07 13:47:37 -070010009void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010010 audio_stream_type_t streamType __unused,
10011 audio_session_t sessionId,
10012 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010013 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010014 audio_port_handle_t portId)
10015{
10016 mAttr = *attr;
10017 mSessionId = sessionId;
10018 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010019 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010020 mPortId = portId;
10021}
10022
Andy Hung4b17e882023-07-07 13:47:37 -070010023status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010024 struct audio_mmap_buffer_info *info)
10025{
10026 if (mHalStream == 0) {
10027 return NO_INIT;
10028 }
Eric Laurent18b57012017-02-13 16:23:52 -080010029 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010030 return mHalStream->createMmapBuffer(minSizeFrames, info);
10031}
10032
Andy Hung4b17e882023-07-07 13:47:37 -070010033status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010034{
10035 if (mHalStream == 0) {
10036 return NO_INIT;
10037 }
10038 return mHalStream->getMmapPosition(position);
10039}
10040
Andy Hung4b17e882023-07-07 13:47:37 -070010041status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010042{
Eric Laurentdda206a2022-07-08 17:28:35 +020010043 // The HAL must receive track metadata before starting the stream
10044 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010045 status_t ret = mHalStream->start();
10046 if (ret != NO_ERROR) {
10047 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10048 return ret;
10049 }
Andy Hungcf10d742020-04-28 15:38:24 -070010050 if (mStandby) {
10051 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010052 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010053 mStandby = false;
10054 }
Eric Laurent331679c2018-04-16 17:03:16 -070010055 return NO_ERROR;
10056}
10057
Andy Hung4b17e882023-07-07 13:47:37 -070010058status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010059 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060 audio_port_handle_t *handle)
10061{
Eric Laurenta54f1282017-07-01 19:39:32 -070010062 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010063 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064 if (mHalStream == 0) {
10065 return NO_INIT;
10066 }
10067
10068 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010069
Eric Laurentdda206a2022-07-08 17:28:35 +020010070 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010071 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010072 acquireWakeLock();
10073 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010074 }
10075
10076 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10077
10078 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010079 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010080 client.attributionSource);
10081
Eric Laurenta54f1282017-07-01 19:39:32 -070010082 if (isOutput()) {
10083 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10084 config.sample_rate = mSampleRate;
10085 config.channel_mask = mChannelMask;
10086 config.format = mFormat;
10087 audio_stream_type_t stream = streamType();
10088 audio_output_flags_t flags =
10089 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010090 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010091 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010092 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010093 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010094 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10095 mSessionId,
10096 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010097 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010098 &config,
10099 flags,
10100 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010101 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010102 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010103 &isSpatialized,
10104 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010105 ALOGD_IF(!secondaryOutputs.empty(),
10106 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010108 audio_config_base_t config;
10109 config.sample_rate = mSampleRate;
10110 config.channel_mask = mChannelMask;
10111 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010112 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010113 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010114 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010115 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010116 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010117 &config,
10118 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10119 &deviceId,
10120 &portId);
10121 }
10122 // APM should not chose a different input or output stream for the same set of attributes
10123 // and audo configuration
10124 if (ret != NO_ERROR || io != mId) {
10125 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10126 __FUNCTION__, ret, io, mId);
10127 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128 }
10129
10130 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010131 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010132 } else {
jiabin09609032022-06-15 19:26:01 +000010133 {
10134 // Add the track record before starting input so that the silent status for the
10135 // client can be cached.
10136 Mutex::Autolock _l(mLock);
10137 setClientSilencedState_l(portId, false /*silenced*/);
10138 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010139 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010140 }
10141
Eric Laurent331679c2018-04-16 17:03:16 -070010142 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 // abort if start is rejected by audio policy manager
10144 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010145 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010146 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010147 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010148 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010149 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010151 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152 }
Eric Laurent331679c2018-04-16 17:03:16 -070010153 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010154 } else {
10155 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156 }
jiabin09609032022-06-15 19:26:01 +000010157 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010158 return PERMISSION_DENIED;
10159 }
10160
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010161 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010162 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10163 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010164 mChannelMask, mSessionId, isOutput(),
10165 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010166 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010167 if (!isOutput()) {
10168 track->setSilenced_l(isClientSilenced_l(portId));
10169 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010170
Eric Laurent4eb58f12018-12-07 16:41:02 -080010171 if (isOutput()) {
10172 // force volume update when a new track is added
10173 mHalVolFloat = -1.0f;
10174 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010175 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010176 if (t->isSilenced_l()
10177 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010178 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010179 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010180 }
10181 }
10182
Eric Laurent6acd1d42017-01-04 14:23:29 -080010183 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010184 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010185 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010186 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010187 chain->incTrackCnt();
10188 chain->incActiveTrackCnt();
10189 }
10190
Andy Hungc2b11cb2020-04-22 09:04:01 -070010191 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010192 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010193
10194 if (mActiveTracks.size() == 1) {
10195 ret = exitStandby_l();
10196 }
10197
Eric Laurent6acd1d42017-01-04 14:23:29 -080010198 broadcast_l();
10199
Eric Laurentdda206a2022-07-08 17:28:35 +020010200 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201
Eric Laurentdda206a2022-07-08 17:28:35 +020010202 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010203}
10204
Andy Hung4b17e882023-07-07 13:47:37 -070010205status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010206{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207 ALOGV("%s handle %d", __FUNCTION__, handle);
10208
10209 if (mHalStream == 0) {
10210 return NO_INIT;
10211 }
10212
Eric Laurenta54f1282017-07-01 19:39:32 -070010213 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010214 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010215 return NO_ERROR;
10216 }
10217
Eric Laurent331679c2018-04-16 17:03:16 -070010218 Mutex::Autolock _l(mLock);
10219
Andy Hung11e74242023-06-26 19:20:57 -070010220 sp<IAfMmapTrack> track;
10221 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010222 if (handle == t->portId()) {
10223 track = t;
10224 break;
10225 }
10226 }
10227 if (track == 0) {
10228 return BAD_VALUE;
10229 }
10230
10231 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010232 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010233
Eric Laurent331679c2018-04-16 17:03:16 -070010234 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010235 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010236 AudioSystem::stopOutput(track->portId());
10237 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010238 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010239 AudioSystem::stopInput(track->portId());
10240 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010241 }
Eric Laurent331679c2018-04-16 17:03:16 -070010242 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243
Andy Hung116bc262023-06-20 18:56:17 -070010244 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 if (chain != 0) {
10246 chain->decActiveTrackCnt();
10247 chain->decTrackCnt();
10248 }
10249
Eric Laurentdda206a2022-07-08 17:28:35 +020010250 if (mActiveTracks.isEmpty()) {
10251 mHalStream->stop();
10252 }
10253
Eric Laurent6acd1d42017-01-04 14:23:29 -080010254 broadcast_l();
10255
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256 return NO_ERROR;
10257}
10258
Andy Hung4b17e882023-07-07 13:47:37 -070010259status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010260{
10261 ALOGV("%s", __FUNCTION__);
10262
10263 if (mHalStream == 0) {
10264 return NO_INIT;
10265 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010266 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010267 return INVALID_OPERATION;
10268 }
10269 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010270 if (!mStandby) {
10271 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010272 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010273 mStandby = true;
10274 }
Eric Laurent18b57012017-02-13 16:23:52 -080010275 releaseWakeLock();
10276 return NO_ERROR;
10277}
10278
Andy Hung4b17e882023-07-07 13:47:37 -070010279status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010280 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10281 return INVALID_OPERATION;
10282}
10283
Andy Hung4b17e882023-07-07 13:47:37 -070010284void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285{
10286 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10287 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10288 mFormat = mHALFormat;
10289 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10290 result = mHalStream->getFrameSize(&mFrameSize);
10291 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010292 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10293 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294 result = mHalStream->getBufferSize(&mBufferSize);
10295 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10296 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010297
Andy Hungcf10d742020-04-28 15:38:24 -070010298 // TODO: make a readHalParameters call?
10299 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010300 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -070010301 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010302 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10303 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10304 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10305 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10306 /*
10307 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10308 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10309 (int32_t)mHapticChannelMask)
10310 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10311 (int32_t)mHapticChannelCount)
10312 */
10313 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -070010314 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010315 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10316 (int32_t)mFrameCount) // sic - added HAL
10317 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010318}
10319
Andy Hung4b17e882023-07-07 13:47:37 -070010320bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010321{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010322 checkSilentMode_l();
10323
10324 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10325
10326 while (!exitPending())
10327 {
Andy Hung116bc262023-06-20 18:56:17 -070010328 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329
Andy Hung13850be2019-03-14 11:33:09 -070010330 { // under Thread lock
10331 Mutex::Autolock _l(mLock);
10332
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333 if (mSignalPending) {
10334 // A signal was raised while we were unlocked
10335 mSignalPending = false;
10336 } else {
10337 if (mConfigEvents.isEmpty()) {
10338 // we're about to wait, flush the binder command buffer
10339 IPCThreadState::self()->flushCommands();
10340
10341 if (exitPending()) {
10342 break;
10343 }
10344
Eric Laurent6acd1d42017-01-04 14:23:29 -080010345 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010346 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010347 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010348 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349
10350 checkSilentMode_l();
10351
10352 continue;
10353 }
10354 }
10355
10356 processConfigEvents_l();
10357
10358 processVolume_l();
10359
10360 checkInvalidTracks_l();
10361
10362 mActiveTracks.updatePowerState(this);
10363
Kevin Rocard069c2712018-03-29 19:09:14 -070010364 updateMetadata_l();
10365
Eric Laurent6acd1d42017-01-04 14:23:29 -080010366 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010367 } // release Thread lock
10368
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010370 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010371 }
Andy Hung13850be2019-03-14 11:33:09 -070010372
10373 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374 unlockEffectChains(effectChains);
10375 // Effect chains will be actually deleted here if they were removed from
10376 // mEffectChains list during mixing or effects processing
10377 }
10378
10379 threadLoop_exit();
10380
10381 if (!mStandby) {
10382 threadLoop_standby();
10383 mStandby = true;
10384 }
10385
Eric Laurent6acd1d42017-01-04 14:23:29 -080010386 ALOGV("Thread %p type %d exiting", this, mType);
10387 return false;
10388}
10389
10390// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010391bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392 status_t& status)
10393{
10394 AudioParameter param = AudioParameter(keyValuePair);
10395 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010396 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010398 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010399 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010400 if (sendToHal) {
10401 status = mHalStream->setParameters(keyValuePair);
10402 } else {
10403 status = NO_ERROR;
10404 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010405
10406 return false;
10407}
10408
Andy Hung4b17e882023-07-07 13:47:37 -070010409String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010410{
10411 Mutex::Autolock _l(mLock);
10412 String8 out_s8;
10413 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10414 return out_s8;
10415 }
Andy Hung920f6572022-10-06 12:09:49 -070010416 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010417}
10418
Andy Hung4b17e882023-07-07 13:47:37 -070010419void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010420 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010421 sp<AudioIoDescriptor> desc;
10422 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010423 switch (event) {
10424 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010425 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010427 isInput = true;
10428 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010429 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010430 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010431 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010432 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10433 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010434 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010435 case AUDIO_INPUT_CLOSED:
10436 case AUDIO_OUTPUT_CLOSED:
10437 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010438 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439 break;
10440 }
Andy Hung7535ed92023-07-17 17:05:00 -070010441 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010442}
10443
Andy Hung4b17e882023-07-07 13:47:37 -070010444status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010445 audio_patch_handle_t *handle)
Andy Hung920f6572022-10-06 12:09:49 -070010446NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010447{
10448 status_t status = NO_ERROR;
10449
10450 // store new device and send to effects
10451 audio_devices_t type = AUDIO_DEVICE_NONE;
10452 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010453 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10454 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10455 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456 if (isOutput()) {
10457 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010458 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10459 && !mAudioHwDev->supportsAudioPatches(),
10460 "Enumerated device type(%#x) must not be used "
10461 "as it does not support audio patches",
10462 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010463 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010464 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10465 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010466 }
10467 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010468 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469 } else {
10470 type = patch->sources[0].ext.device.type;
10471 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010472 numDevices = mPatch.num_sources;
10473 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010474 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010475 }
10476
10477 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010478 if (isOutput()) {
10479 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10480 } else {
10481 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10482 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010483 }
10484
jiabinc52b1ff2019-10-31 17:20:42 -070010485 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486 // store new source and send to effects
10487 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10488 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10489 for (size_t i = 0; i < mEffectChains.size(); i++) {
10490 mEffectChains[i]->setAudioSource_l(mAudioSource);
10491 }
10492 }
10493 }
10494
10495 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010496 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10497 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010498 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010499 audio_port_config port;
10500 std::optional<audio_source_t> source;
10501 if (isOutput()) {
10502 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010503 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010504 port = patch->sources[0];
10505 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010506 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010507 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010508 *handle = AUDIO_PATCH_HANDLE_NONE;
10509 }
10510
jiabinc52b1ff2019-10-31 17:20:42 -070010511 if (numDevices == 0 || mDeviceId != deviceId) {
10512 if (isOutput()) {
10513 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10514 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010515 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010516 } else {
10517 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10518 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10519 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010520 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010521 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010522 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010523 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010524 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010525 }
jiabinc52b1ff2019-10-31 17:20:42 -070010526 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010527 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010528 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010529 // Force meteadata update after a route change
10530 mActiveTracks.setHasChanged();
10531
Eric Laurent6acd1d42017-01-04 14:23:29 -080010532 return status;
10533}
10534
Andy Hung4b17e882023-07-07 13:47:37 -070010535status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536{
10537 status_t status = NO_ERROR;
10538
jiabinc52b1ff2019-10-31 17:20:42 -070010539 mPatch = audio_patch{};
10540 mOutDeviceTypeAddrs.clear();
10541 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010542
10543 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10544 supportsAudioPatches : false;
10545
10546 if (supportsAudioPatches) {
10547 status = mHalDevice->releaseAudioPatch(handle);
10548 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010549 status = mHalStream->legacyReleaseAudioPatch();
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 Hung4b17e882023-07-07 13:47:37 -070010557void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010559 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560 if (isOutput()) {
10561 config->role = AUDIO_PORT_ROLE_SOURCE;
10562 config->ext.mix.hw_module = mAudioHwDev->handle();
10563 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10564 } else {
10565 config->role = AUDIO_PORT_ROLE_SINK;
10566 config->ext.mix.hw_module = mAudioHwDev->handle();
10567 config->ext.mix.usecase.source = mAudioSource;
10568 }
10569}
10570
Andy Hung4b17e882023-07-07 13:47:37 -070010571status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572{
10573 audio_session_t session = chain->sessionId();
10574
10575 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10576 // Attach all tracks with same session ID to this chain.
10577 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010578 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010579 if (session == track->sessionId()) {
10580 chain->incTrackCnt();
10581 chain->incActiveTrackCnt();
10582 }
10583 }
10584
10585 chain->setThread(this);
10586 chain->setInBuffer(nullptr);
10587 chain->setOutBuffer(nullptr);
10588 chain->syncHalEffectsState();
10589
10590 mEffectChains.add(chain);
10591 checkSuspendOnAddEffectChain_l(chain);
10592 return NO_ERROR;
10593}
10594
Andy Hung4b17e882023-07-07 13:47:37 -070010595size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010596{
10597 audio_session_t session = chain->sessionId();
10598
10599 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10600
10601 for (size_t i = 0; i < mEffectChains.size(); i++) {
10602 if (chain == mEffectChains[i]) {
10603 mEffectChains.removeAt(i);
10604 // detach all active tracks from the chain
10605 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010606 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 if (session == track->sessionId()) {
10608 chain->decActiveTrackCnt();
10609 chain->decTrackCnt();
10610 }
10611 }
10612 break;
10613 }
10614 }
10615 return mEffectChains.size();
10616}
10617
Andy Hung4b17e882023-07-07 13:47:37 -070010618void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010619{
10620 mHalStream->standby();
10621}
10622
Andy Hung4b17e882023-07-07 13:47:37 -070010623void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624{
Phil Burk7dce7282017-09-27 13:51:41 -070010625 // Do not call callback->onTearDown() because it is redundant for thread exit
10626 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627}
10628
Andy Hung4b17e882023-07-07 13:47:37 -070010629status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630{
10631 return BAD_VALUE;
10632}
10633
Andy Hung4b17e882023-07-07 13:47:37 -070010634bool MmapThread::isValidSyncEvent(
10635 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010636{
10637 return false;
10638}
10639
Andy Hung4b17e882023-07-07 13:47:37 -070010640status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010641 const effect_descriptor_t *desc, audio_session_t sessionId)
10642{
10643 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010644 if (audio_is_global_session(sessionId)) {
10645 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010646 desc->name, mThreadName);
10647 return BAD_VALUE;
10648 }
10649
10650 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10651 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10652 desc->name);
10653 return BAD_VALUE;
10654 }
10655 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010656 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10657 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010658 return BAD_VALUE;
10659 }
10660
10661 // Only allow effects without processing load or latency
10662 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10663 return BAD_VALUE;
10664 }
10665
Andy Hung116bc262023-06-20 18:56:17 -070010666 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010667 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10668 return BAD_VALUE;
10669 }
10670
Eric Laurent6acd1d42017-01-04 14:23:29 -080010671 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010672}
10673
Andy Hung4b17e882023-07-07 13:47:37 -070010674void MmapThread::checkInvalidTracks_l()
Andy Hung920f6572022-10-06 12:09:49 -070010675NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010676{
Eric Laurent039c24a2022-10-07 14:01:59 +020010677 sp<MmapStreamCallback> callback;
Andy Hung11e74242023-06-26 19:20:57 -070010678 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010679 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010680 callback = mCallback.promote();
10681 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10682 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10683 mNoCallbackWarningCount++;
10684 }
10685 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010686 }
10687 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010688 if (callback != 0) {
10689 mLock.unlock();
10690 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10691 mLock.lock();
jiabindfa32482022-10-06 19:45:50 +000010692 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010693}
10694
Andy Hung4b17e882023-07-07 13:47:37 -070010695void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10698 mAttr.content_type, mAttr.usage, mAttr.source);
10699 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010700 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010701 dprintf(fd, " No active clients\n");
10702 }
10703}
10704
Andy Hung4b17e882023-07-07 13:47:37 -070010705void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010709 dprintf(fd, " %zu Tracks\n", numtracks);
10710 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010711 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010712 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010713 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010714 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010715 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010716 result.append(prefix);
10717 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010718 }
10719 } else {
10720 dprintf(fd, "\n");
10721 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010722 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010723}
10724
Andy Hung4b17e882023-07-07 13:47:37 -070010725/* static */
10726sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010727 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010728 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010729 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010730}
10731
10732MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010733 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010734 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010735 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010737 mStreamVolume(1.0),
10738 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010739 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740{
10741 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10742 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070010743 mMasterVolume = afThreadCallback->masterVolume_l();
10744 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745 if (mAudioHwDev) {
10746 if (mAudioHwDev->canSetMasterVolume()) {
10747 mMasterVolume = 1.0;
10748 }
10749
10750 if (mAudioHwDev->canSetMasterMute()) {
10751 mMasterMute = false;
10752 }
10753 }
10754}
10755
Andy Hung4b17e882023-07-07 13:47:37 -070010756void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010757 audio_stream_type_t streamType,
10758 audio_session_t sessionId,
10759 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010760 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010761 audio_port_handle_t portId)
10762{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010763 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010764 mStreamType = streamType;
10765}
10766
Andy Hung4b17e882023-07-07 13:47:37 -070010767AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010768{
10769 Mutex::Autolock _l(mLock);
10770 AudioStreamOut *output = mOutput;
10771 mOutput = NULL;
10772 return output;
10773}
10774
Andy Hung4b17e882023-07-07 13:47:37 -070010775void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776{
10777 Mutex::Autolock _l(mLock);
10778 // Don't apply master volume in SW if our HAL can do it for us.
10779 if (mAudioHwDev &&
10780 mAudioHwDev->canSetMasterVolume()) {
10781 mMasterVolume = 1.0;
10782 } else {
10783 mMasterVolume = value;
10784 }
10785}
10786
Andy Hung4b17e882023-07-07 13:47:37 -070010787void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010788{
10789 Mutex::Autolock _l(mLock);
10790 // Don't apply master mute in SW if our HAL can do it for us.
10791 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10792 mMasterMute = false;
10793 } else {
10794 mMasterMute = muted;
10795 }
10796}
10797
Andy Hung4b17e882023-07-07 13:47:37 -070010798void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010799{
10800 Mutex::Autolock _l(mLock);
10801 if (stream == mStreamType) {
10802 mStreamVolume = value;
10803 broadcast_l();
10804 }
10805}
10806
Andy Hung4b17e882023-07-07 13:47:37 -070010807float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010808{
10809 Mutex::Autolock _l(mLock);
10810 if (stream == mStreamType) {
10811 return mStreamVolume;
10812 }
10813 return 0.0f;
10814}
10815
Andy Hung4b17e882023-07-07 13:47:37 -070010816void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010817{
10818 Mutex::Autolock _l(mLock);
10819 if (stream == mStreamType) {
10820 mStreamMute= muted;
10821 broadcast_l();
10822 }
10823}
10824
Andy Hung4b17e882023-07-07 13:47:37 -070010825void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010826{
10827 Mutex::Autolock _l(mLock);
10828 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070010829 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010830 track->invalidate();
10831 }
10832 broadcast_l();
10833 }
10834}
10835
Andy Hung4b17e882023-07-07 13:47:37 -070010836void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010837{
10838 Mutex::Autolock _l(mLock);
10839 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070010840 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010841 if (portIds.find(track->portId()) != portIds.end()) {
10842 track->invalidate();
10843 trackMatch = true;
10844 portIds.erase(track->portId());
10845 }
10846 if (portIds.empty()) {
10847 break;
10848 }
10849 }
10850 if (trackMatch) {
10851 broadcast_l();
10852 }
10853}
10854
Andy Hung4b17e882023-07-07 13:47:37 -070010855void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010856NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010857{
10858 float volume;
10859
10860 if (mMasterMute || mStreamMute) {
10861 volume = 0;
10862 } else {
10863 volume = mMasterVolume * mStreamVolume;
10864 }
10865
10866 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010867
10868 // Convert volumes from float to 8.24
10869 uint32_t vol = (uint32_t)(volume * (1 << 24));
10870
10871 // Delegate volume control to effect in track effect chain if needed
10872 // only one effect chain can be present on DirectOutputThread, so if
10873 // there is one, the track is connected to it
10874 if (!mEffectChains.isEmpty()) {
10875 mEffectChains[0]->setVolume_l(&vol, &vol);
10876 volume = (float)vol / (1 << 24);
10877 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010878 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010879 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10880 mHalVolFloat = volume; // HW volume control worked, so update value.
10881 mNoCallbackWarningCount = 0;
10882 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010883 sp<MmapStreamCallback> callback = mCallback.promote();
10884 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010885 mHalVolFloat = volume; // SW volume control worked, so update value.
10886 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010887 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010888 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010889 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010890 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010891 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10892 ALOGW("Could not set MMAP stream volume: no volume callback!");
10893 mNoCallbackWarningCount++;
10894 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010895 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010896 }
Andy Hung11e74242023-06-26 19:20:57 -070010897 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010898 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070010899 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010900 /*muteState=*/{mMasterMute,
10901 mStreamVolume == 0.f,
10902 mStreamMute,
10903 // TODO(b/241533526): adjust logic to include mute from AppOps
10904 false /*muteFromPlaybackRestricted*/,
10905 false /*muteFromClientVolume*/,
10906 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010907 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010908 }
10909}
10910
Andy Hung4b17e882023-07-07 13:47:37 -070010911ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010912{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010913 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010914 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010915 }
10916 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070010917 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010918 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010919 playback_track_metadata_v7_t trackMetadata;
10920 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010921 .usage = track->attributes().usage,
10922 .content_type = track->attributes().content_type,
10923 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010924 };
10925 trackMetadata.channel_mask = track->channelMask(),
10926 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10927 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010928 }
10929 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010930
10931 MetadataUpdate change;
10932 change.playbackMetadataUpdate = metadata.tracks;
10933 return change;
10934};
Kevin Rocard069c2712018-03-29 19:09:14 -070010935
Andy Hung4b17e882023-07-07 13:47:37 -070010936void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937{
10938 if (!mMasterMute) {
10939 char value[PROPERTY_VALUE_MAX];
10940 if (property_get("ro.audio.silent", value, "0") > 0) {
10941 char *endptr;
10942 unsigned long ul = strtoul(value, &endptr, 0);
10943 if (*endptr == '\0' && ul != 0) {
10944 ALOGD("Silence is golden");
10945 // The setprop command will not allow a property to be changed after
10946 // the first time it is set, so we don't have to worry about un-muting.
10947 setMasterMute_l(true);
10948 }
10949 }
10950 }
10951}
10952
Andy Hung4b17e882023-07-07 13:47:37 -070010953void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010954{
10955 MmapThread::toAudioPortConfig(config);
10956 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10957 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10958 config->flags.output = mOutput->flags;
10959 }
10960}
10961
Andy Hung4b17e882023-07-07 13:47:37 -070010962status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070010963 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010964{
10965 if (mOutput == nullptr) {
10966 return NO_INIT;
10967 }
10968 struct timespec timestamp;
10969 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10970 if (status == NO_ERROR) {
10971 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10972 }
10973 return status;
10974}
10975
Andy Hung4b17e882023-07-07 13:47:37 -070010976status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010977 // Send to MelProcessor for sound dose measurement.
10978 auto processor = mMelProcessor.load();
10979 if (processor) {
10980 processor->process(buffer, frameCount * mFrameSize);
10981 }
10982
jiabinfc791ee2023-02-15 19:43:40 +000010983 return NO_ERROR;
10984}
10985
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010986// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010987void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010988 const sp<audio_utils::MelProcessor>& processor)
10989{
10990 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010991 mMelProcessor.store(processor);
10992 if (processor) {
10993 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010994 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010995
10996 // no need to update output format for MMapPlaybackThread since it is
10997 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010998}
10999
11000// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070011001void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011002{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011003 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11004 auto melProcessor = mMelProcessor.load();
11005 if (melProcessor != nullptr) {
11006 melProcessor->pause();
11007 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011008}
11009
Andy Hung4b17e882023-07-07 13:47:37 -070011010void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011011{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011012 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011013
Glenn Kastend3bb6452016-12-05 18:14:37 -080011014 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
11015 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011016 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11017}
11018
Andy Hung4b17e882023-07-07 13:47:37 -070011019/* static */
11020sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070011021 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070011022 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011023 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011024}
11025
11026MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011027 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011028 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011029 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011030 mInput(input)
11031{
11032 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11033 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11034}
11035
Andy Hung4b17e882023-07-07 13:47:37 -070011036status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011037{
Phil Burkf054fc32018-12-06 09:45:59 -080011038 {
11039 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011040 if (mInput != nullptr && mInput->stream != nullptr) {
11041 mInput->stream->setGain(1.0f);
11042 }
11043 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011044 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011045}
11046
Andy Hung4b17e882023-07-07 13:47:37 -070011047AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011048{
11049 Mutex::Autolock _l(mLock);
11050 AudioStreamIn *input = mInput;
11051 mInput = NULL;
11052 return input;
11053}
Kevin Rocard069c2712018-03-29 19:09:14 -070011054
Andy Hung4b17e882023-07-07 13:47:37 -070011055void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011056{
11057 bool changed = false;
11058 bool silenced = false;
11059
11060 sp<MmapStreamCallback> callback = mCallback.promote();
11061 if (callback == 0) {
11062 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11063 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11064 mNoCallbackWarningCount++;
11065 }
11066 }
11067
11068 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11069 // track is silenced and unmute otherwise
11070 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11071 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11072 changed = true;
11073 silenced = mActiveTracks[i]->isSilenced_l();
11074 }
11075 }
11076
11077 if (changed) {
11078 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11079 }
11080}
11081
Andy Hung4b17e882023-07-07 13:47:37 -070011082ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011083{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011084 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011085 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011086 }
11087 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011088 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011089 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011090 record_track_metadata_v7_t trackMetadata;
11091 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011092 .source = track->attributes().source,
11093 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011094 };
11095 trackMetadata.channel_mask = track->channelMask(),
11096 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11097 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011098 }
11099 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011100 MetadataUpdate change;
11101 change.recordMetadataUpdate = metadata.tracks;
11102 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011103}
11104
Andy Hung4b17e882023-07-07 13:47:37 -070011105void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011106{
11107 Mutex::Autolock _l(mLock);
11108 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011109 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011110 mActiveTracks[i]->setSilenced_l(silenced);
11111 broadcast_l();
11112 }
11113 }
jiabin09609032022-06-15 19:26:01 +000011114 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011115}
11116
Andy Hung4b17e882023-07-07 13:47:37 -070011117void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011118{
11119 MmapThread::toAudioPortConfig(config);
11120 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11121 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11122 config->flags.input = mInput->flags;
11123 }
11124}
11125
Andy Hung4b17e882023-07-07 13:47:37 -070011126status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011127 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011128{
11129 if (mInput == nullptr) {
11130 return NO_INIT;
11131 }
11132 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11133}
11134
jiabinc658e452022-10-21 20:52:21 +000011135// ----------------------------------------------------------------------------
11136
Andy Hung4b17e882023-07-07 13:47:37 -070011137/* static */
11138sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011139 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011140 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011141 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011142}
11143
Andy Hung7535ed92023-07-17 17:05:00 -070011144BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011145 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011146 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011147
Andy Hung4b17e882023-07-07 13:47:37 -070011148PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011149 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011150 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11151 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011152 float volumeLeft = 1.0f;
11153 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011154 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11155 const int trackId = mActiveTracks[0]->id();
11156 mAudioMixer->setParameter(
11157 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11158 mAudioMixer->setParameter(
11159 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11160 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011161 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011162 mIsBitPerfect = true;
11163 } else {
11164 mIsBitPerfect = false;
11165 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11166 // active.
11167 for (const auto& track : mActiveTracks) {
11168 const int trackId = track->id();
11169 mAudioMixer->setParameter(
11170 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11171 }
11172 }
jiabin76d94692022-12-15 21:51:21 +000011173 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11174 mVolumeLeft = volumeLeft;
11175 mVolumeRight = volumeRight;
11176 setVolumeForOutput_l(volumeLeft, volumeRight);
11177 }
jiabinc658e452022-10-21 20:52:21 +000011178 return result;
11179}
11180
Andy Hung4b17e882023-07-07 13:47:37 -070011181void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011182 MixerThread::threadLoop_mix();
11183 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11184}
11185
Glenn Kasten63238ef2015-03-02 15:50:29 -080011186} // namespace android