blob: 0cfdb5672d0018bfe7608bb9f794004b07e41169 [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 // }
Andy Hungb17d24b2023-08-29 14:26:09 -0700688 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800689 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -0700690 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800691 }
692 // When Thread::requestExitAndWait is made virtual and this method is renamed to
693 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
694 requestExitAndWait();
695}
696
Andy 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());
Andy Hungf8635b62023-08-31 16:13:39 -0700700 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800701
Eric Laurent10351942014-05-08 18:49:52 -0700702 return sendSetParameterConfigEvent_l(keyValuePairs);
703}
704
705// sendConfigEvent_l() must be called with ThreadBase::mLock held
706// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy 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);
Andy Hungb17d24b2023-08-29 14:26:09 -0700719 mWaitWorkCV.notify_one();
720 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700721 {
Andy Hungb17d24b2023-08-29 14:26:09 -0700722 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700723 while (event->mWaitStatus) {
Andy Hungb17d24b2023-08-29 14:26:09 -0700724 if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
725 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700726 event->mStatus = TIMED_OUT;
727 event->mWaitStatus = false;
728 }
729 }
730 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800731 }
Andy Hungb17d24b2023-08-29 14:26:09 -0700732 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800733 return status;
734}
735
Andy Hung4b17e882023-07-07 13:47:37 -0700736void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700737 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800738{
Andy Hungf8635b62023-08-31 16:13:39 -0700739 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700740 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Andy Hungb17d24b2023-08-29 14:26:09 -0700743// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700744void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700745 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800746{
Andy Hungd0979812019-02-21 15:51:44 -0800747 // The audio statistics history is exponentially weighted to forget events
748 // about five or more seconds in the past. In order to have
749 // crisper statistics for mediametrics, we reset the statistics on
750 // an IoConfigEvent, to reflect different properties for a new device.
751 mIoJitterMs.reset();
752 mLatencyMs.reset();
753 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000754 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100755 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800756
Eric Laurent09f1ed22019-04-24 17:45:17 -0700757 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700758 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800759}
760
Andy Hung4b17e882023-07-07 13:47:37 -0700761void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700762{
Andy Hungf8635b62023-08-31 16:13:39 -0700763 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800764 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700765}
766
Andy Hungb17d24b2023-08-29 14:26:09 -0700767// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700768void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800769 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800770{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800771 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700772 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800773}
774
Andy Hungb17d24b2023-08-29 14:26:09 -0700775// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700776status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800777{
Andy Hung2ddee192015-12-18 17:34:44 -0800778 sp<ConfigEvent> configEvent;
779 AudioParameter param(keyValuePair);
780 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700781 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800782 setMasterMono_l(value != 0);
783 if (param.size() == 1) {
784 return NO_ERROR; // should be a solo parameter - we don't pass down
785 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700786 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800787 configEvent = new SetParameterConfigEvent(param.toString());
788 } else {
789 configEvent = new SetParameterConfigEvent(keyValuePair);
790 }
Eric Laurent10351942014-05-08 18:49:52 -0700791 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700792}
793
Andy Hung4b17e882023-07-07 13:47:37 -0700794status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700795 const struct audio_patch *patch,
796 audio_patch_handle_t *handle)
797{
Andy Hungf8635b62023-08-31 16:13:39 -0700798 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700799 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
800 status_t status = sendConfigEvent_l(configEvent);
801 if (status == NO_ERROR) {
802 CreateAudioPatchConfigEventData *data =
803 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
804 *handle = data->mHandle;
805 }
806 return status;
807}
808
Andy Hung4b17e882023-07-07 13:47:37 -0700809status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700810 const audio_patch_handle_t handle)
811{
Andy Hungf8635b62023-08-31 16:13:39 -0700812 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
814 return sendConfigEvent_l(configEvent);
815}
816
Andy Hung4b17e882023-07-07 13:47:37 -0700817status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700818 const DeviceDescriptorBaseVector& outDevices)
819{
820 if (type() != RECORD) {
821 // The update out device operation is only for record thread.
822 return INVALID_OPERATION;
823 }
Andy Hungf8635b62023-08-31 16:13:39 -0700824 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700825 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
826 return sendConfigEvent_l(configEvent);
827}
828
Andy Hung4b17e882023-07-07 13:47:37 -0700829void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200830{
831 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
832 sp<ConfigEvent> configEvent =
833 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
834 sendConfigEvent_l(configEvent);
835}
Eric Laurent1c333e22014-05-20 10:48:17 -0700836
Andy Hung4b17e882023-07-07 13:47:37 -0700837void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200838{
Andy Hungf8635b62023-08-31 16:13:39 -0700839 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200840 sendCheckOutputStageEffectsEvent_l();
841}
842
Andy Hung4b17e882023-07-07 13:47:37 -0700843void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200844{
845 sp<ConfigEvent> configEvent =
846 (ConfigEvent *)new CheckOutputStageEffectsEvent();
847 sendConfigEvent_l(configEvent);
848}
849
Andy Hung4b17e882023-07-07 13:47:37 -0700850void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200851{
852 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
853 sendConfigEvent_l(configEvent);
854}
855
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700856// post condition: mConfigEvents.isEmpty()
Andy Hung4b17e882023-07-07 13:47:37 -0700857void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700858{
Eric Laurent10351942014-05-08 18:49:52 -0700859 bool configChanged = false;
860
Eric Laurent81784c32012-11-19 14:55:58 -0800861 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700862 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700863 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800864 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700865 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700866 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700867 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
868 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800869 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700870 true /*asynchronous*/);
871 if (err != 0) {
872 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700873 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700874 }
875 } break;
876 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700877 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700878 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700879 } break;
880 case CFG_EVENT_SET_PARAMETER: {
881 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
882 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
883 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700884 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000885 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700886 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700887 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700888 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700889 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700890 CreateAudioPatchConfigEventData *data =
891 (CreateAudioPatchConfigEventData *)event->mData.get();
892 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700893 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200894 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700895 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
896 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
897 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700898 } break;
899 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700900 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700901 ReleaseAudioPatchConfigEventData *data =
902 (ReleaseAudioPatchConfigEventData *)event->mData.get();
903 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700904 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200905 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700906 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
907 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
908 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
909 } break;
910 case CFG_EVENT_UPDATE_OUT_DEVICE: {
911 UpdateOutDevicesConfigEventData *data =
912 (UpdateOutDevicesConfigEventData *)event->mData.get();
913 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700914 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200915 case CFG_EVENT_RESIZE_BUFFER: {
916 ResizeBufferConfigEventData *data =
917 (ResizeBufferConfigEventData *)event->mData.get();
918 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
919 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200920
921 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
922 setCheckOutputStageEffects();
923 } break;
924
Eric Laurent68a40a82022-05-03 18:15:04 +0200925 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
926 onHalLatencyModesChanged_l();
927 } break;
928
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700929 default:
Eric Laurent10351942014-05-08 18:49:52 -0700930 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700931 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
Eric Laurent10351942014-05-08 18:49:52 -0700933 {
Andy Hungf8635b62023-08-31 16:13:39 -0700934 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700935 if (event->mWaitStatus) {
936 event->mWaitStatus = false;
Andy Hungb17d24b2023-08-29 14:26:09 -0700937 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700938 }
939 }
940 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
941 }
942
943 if (configChanged) {
944 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
Eric Laurent81784c32012-11-19 14:55:58 -0800946}
947
Marco Nelissenb2208842014-02-07 14:00:50 -0800948String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
949 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700950 const audio_channel_representation_t representation =
951 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700952
953 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800954 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700955 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
956 if (output) {
957 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
958 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
959 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700960 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700961 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
962 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
963 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
964 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
965 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
966 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
967 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
968 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
969 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700973 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
977 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
978 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
979 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700980 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700981 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
982 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700983 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
984 } else {
985 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
986 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
987 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
988 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
989 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
990 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
991 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
992 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
993 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
994 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
995 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
996 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700997 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
998 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
999 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001000 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001001 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1002 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001003 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1004 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1005 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1006 }
1007 const int len = s.length();
1008 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001009 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001010 s.unlockBuffer(len - 2); // remove trailing ", "
1011 }
1012 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001013 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001014 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1015 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1016 return s;
1017 default:
1018 s.appendFormat("unknown mask, representation:%d bits:%#x",
1019 representation, audio_channel_mask_get_bits(mask));
1020 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001021 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001022}
1023
Andy Hung4b17e882023-07-07 13:47:37 -07001024void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001025NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001026{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001027 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1028 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1029
Andy Hungb17d24b2023-08-29 14:26:09 -07001030 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001031 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001032 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001033 }
1034
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001035 dumpBase_l(fd, args);
1036 dumpInternals_l(fd, args);
1037 dumpTracks_l(fd, args);
1038 dumpEffectChains_l(fd, args);
1039
1040 if (locked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001041 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001042 }
1043
1044 dprintf(fd, " Local log:\n");
1045 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001046
1047 // --all does the statistics
1048 bool dumpAll = false;
1049 for (const auto &arg : args) {
1050 if (arg == String16("--all")) {
1051 dumpAll = true;
1052 }
1053 }
1054 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001055 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001056 if (!sched.empty()) {
1057 (void)write(fd, sched.c_str(), sched.size());
1058 }
1059 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001060}
1061
Andy Hung4b17e882023-07-07 13:47:37 -07001062void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001063{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001064 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001065 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001066 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001067 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung409572b2023-07-19 12:47:35 -07001068 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1069 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001070 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001071 dprintf(fd, " Channel count: %u\n", mChannelCount);
1072 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001073 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung409572b2023-07-19 12:47:35 -07001074 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1075 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001076 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001077 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001078 size_t numConfig = mConfigEvents.size();
1079 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001080 const size_t SIZE = 256;
1081 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001082 for (size_t i = 0; i < numConfig; i++) {
1083 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001084 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001085 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001086 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001087 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001088 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001089 }
Andy Hung293558a2017-03-21 12:19:20 -07001090 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001091 dprintf(fd, " Output devices: %s (%s)\n",
1092 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1093 dprintf(fd, " Input device: %#x (%s)\n",
1094 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001095 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001096
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001097 // Dump timestamp statistics for the Thread types that support it.
1098 if (mType == RECORD
1099 || mType == MIXER
1100 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001101 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001102 || mType == OFFLOAD
1103 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001104 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001105 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001106 }
1107
Andy Hung446f4df2019-02-21 12:26:41 -08001108 if (mLastIoBeginNs > 0) { // MMAP may not set this
1109 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1110 isOutput() ? "write" : "read",
1111 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1112 }
1113
1114 if (mProcessTimeMs.getN() > 0) {
1115 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1116 }
1117
1118 if (mIoJitterMs.getN() > 0) {
1119 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1120 isOutput() ? "write" : "read",
1121 mIoJitterMs.toString().c_str());
1122 }
1123
Andy Hunge6c37112019-02-26 17:38:10 -08001124 if (mLatencyMs.getN() > 0) {
1125 dprintf(fd, " Threadloop %s latency stats: %s\n",
1126 isOutput() ? "write" : "read",
1127 mLatencyMs.toString().c_str());
1128 }
Robert Wu06db0a32021-08-10 19:05:34 +00001129
1130 if (mMonopipePipeDepthStats.getN() > 0) {
1131 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1132 isOutput() ? "write" : "read",
1133 mMonopipePipeDepthStats.toString().c_str());
1134 }
Eric Laurent81784c32012-11-19 14:55:58 -08001135}
1136
Andy Hung4b17e882023-07-07 13:47:37 -07001137void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001138{
1139 const size_t SIZE = 256;
1140 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001141
Marco Nelissenb2208842014-02-07 14:00:50 -08001142 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001143 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001144 write(fd, buffer, strlen(buffer));
1145
Marco Nelissenb2208842014-02-07 14:00:50 -08001146 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001147 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001148 if (chain != 0) {
1149 chain->dump(fd, args);
1150 }
1151 }
1152}
1153
Andy Hung4b17e882023-07-07 13:47:37 -07001154void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001155{
Andy Hungf8635b62023-08-31 16:13:39 -07001156 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001157 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001158}
1159
Andy Hung4b17e882023-07-07 13:47:37 -07001160String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001161{
1162 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001163 case MIXER:
1164 return String16("AudioMix");
1165 case DIRECT:
1166 return String16("AudioDirectOut");
1167 case DUPLICATING:
1168 return String16("AudioDup");
1169 case RECORD:
1170 return String16("AudioIn");
1171 case OFFLOAD:
1172 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001173 case MMAP_PLAYBACK:
1174 return String16("MmapPlayback");
1175 case MMAP_CAPTURE:
1176 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001177 case SPATIALIZER:
1178 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001179 default:
1180 ALOG_ASSERT(false);
1181 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001182 }
1183}
1184
Andy Hung4b17e882023-07-07 13:47:37 -07001185void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001186{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001187 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001188 if (mPowerManager != 0) {
1189 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001190 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001191 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1192 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001193 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001194 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001195 {} /* workSource */,
1196 {} /* historyTag */);
1197 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001198 mWakeLockToken = binder;
1199 }
Chris Ye6597d732020-02-28 22:38:25 -08001200 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001201 }
Wei Jia3f273d12015-11-24 09:06:49 -08001202
Andy Hung3f0c9022016-01-15 17:49:46 -08001203 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001204 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1205 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001206}
1207
Andy Hung4b17e882023-07-07 13:47:37 -07001208void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001209{
Andy Hungf8635b62023-08-31 16:13:39 -07001210 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001211 releaseWakeLock_l();
1212}
1213
Andy Hung4b17e882023-07-07 13:47:37 -07001214void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001215{
Andy Hung3f0c9022016-01-15 17:49:46 -08001216 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001217 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001218 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001219 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001220 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001221 }
1222 mWakeLockToken.clear();
1223 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001224}
1225
Andy Hung4b17e882023-07-07 13:47:37 -07001226void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001227 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001228 // use checkService() to avoid blocking if power service is not up yet
1229 sp<IBinder> binder =
1230 defaultServiceManager()->checkService(String16("power"));
1231 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001232 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001233 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001234 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001235 binder->linkToDeath(mDeathRecipient);
1236 }
1237 }
1238}
1239
Andy Hung4b17e882023-07-07 13:47:37 -07001240void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001241 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001242
1243#if !LOG_NDEBUG
1244 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001245 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001246 s << uid << " ";
1247 }
1248 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1249#endif
1250
Andy Hung438e7572015-12-14 15:51:17 -08001251 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1252 if (mSystemReady) {
1253 ALOGE("no wake lock to update, but system ready!");
1254 } else {
1255 ALOGW("no wake lock to update, system not ready yet");
1256 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001257 return;
1258 }
1259 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001260 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001261 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1262 mWakeLockToken, uidsAsInt);
1263 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001264 }
1265}
1266
Andy Hung4b17e882023-07-07 13:47:37 -07001267void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001268{
Andy Hungf8635b62023-08-31 16:13:39 -07001269 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001270 releaseWakeLock_l();
1271 mPowerManager.clear();
1272}
1273
Andy Hung4b17e882023-07-07 13:47:37 -07001274void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001275 const DeviceDescriptorBaseVector& outDevices __unused)
1276{
1277 ALOGE("%s should only be called in RecordThread", __func__);
1278}
1279
Andy Hung4b17e882023-07-07 13:47:37 -07001280void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001281{
1282 ALOGE("%s should only be called in RecordThread", __func__);
1283}
1284
Andy Hung4b17e882023-07-07 13:47:37 -07001285void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001286{
1287 sp<ThreadBase> thread = mThread.promote();
1288 if (thread != 0) {
1289 thread->clearPowerManager();
1290 }
1291 ALOGW("power manager service died !!!");
1292}
1293
Andy Hung4b17e882023-07-07 13:47:37 -07001294void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001295 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001296{
Andy Hung116bc262023-06-20 18:56:17 -07001297 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001298 if (chain != 0) {
1299 if (type != NULL) {
1300 chain->setEffectSuspended_l(type, suspend);
1301 } else {
1302 chain->setEffectSuspendedAll_l(suspend);
1303 }
1304 }
1305
1306 updateSuspendedSessions_l(type, suspend, sessionId);
1307}
1308
Andy Hung4b17e882023-07-07 13:47:37 -07001309void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001310{
1311 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1312 if (index < 0) {
1313 return;
1314 }
1315
1316 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1317 mSuspendedSessions.valueAt(index);
1318
1319 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001320 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001321 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001322 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001323 chain->setEffectSuspendedAll_l(true);
1324 } else {
1325 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1326 desc->mType.timeLow);
1327 chain->setEffectSuspended_l(&desc->mType, true);
1328 }
1329 }
1330 }
1331}
1332
Andy Hung4b17e882023-07-07 13:47:37 -07001333void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001334 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001335 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001336{
1337 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1338
1339 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1340
1341 if (suspend) {
1342 if (index >= 0) {
1343 sessionEffects = mSuspendedSessions.valueAt(index);
1344 } else {
1345 mSuspendedSessions.add(sessionId, sessionEffects);
1346 }
1347 } else {
1348 if (index < 0) {
1349 return;
1350 }
1351 sessionEffects = mSuspendedSessions.valueAt(index);
1352 }
1353
1354
Andy Hung116bc262023-06-20 18:56:17 -07001355 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001356 if (type != NULL) {
1357 key = type->timeLow;
1358 }
1359 index = sessionEffects.indexOfKey(key);
1360
1361 sp<SuspendedSessionDesc> desc;
1362 if (suspend) {
1363 if (index >= 0) {
1364 desc = sessionEffects.valueAt(index);
1365 } else {
1366 desc = new SuspendedSessionDesc();
1367 if (type != NULL) {
1368 desc->mType = *type;
1369 }
1370 sessionEffects.add(key, desc);
1371 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1372 }
1373 desc->mRefCount++;
1374 } else {
1375 if (index < 0) {
1376 return;
1377 }
1378 desc = sessionEffects.valueAt(index);
1379 if (--desc->mRefCount == 0) {
1380 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1381 sessionEffects.removeItemsAt(index);
1382 if (sessionEffects.isEmpty()) {
1383 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1384 sessionId);
1385 mSuspendedSessions.removeItem(sessionId);
1386 }
1387 }
1388 }
1389 if (!sessionEffects.isEmpty()) {
1390 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1391 }
1392}
1393
Andy Hung4b17e882023-07-07 13:47:37 -07001394void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001395 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001396 bool threadLocked)
1397NO_THREAD_SAFETY_ANALYSIS // manual locking
1398{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001399 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001400 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001401 }
Eric Laurent81784c32012-11-19 14:55:58 -08001402
Eric Laurent81784c32012-11-19 14:55:58 -08001403 if (mType != RECORD) {
1404 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1405 // another session. This gives the priority to well behaved effect control panels
1406 // and applications not using global effects.
1407 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1408 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001409 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001410 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1411 }
1412 }
1413
Eric Laurent6b446ce2019-12-13 10:56:31 -08001414 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001415 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001416 }
1417}
1418
Andy Hungb17d24b2023-08-29 14:26:09 -07001419// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001420status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001421 const effect_descriptor_t *desc, audio_session_t sessionId)
1422{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001423 // No global output effect sessions on record threads
1424 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1425 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001426 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1427 desc->name, mThreadName);
1428 return BAD_VALUE;
1429 }
1430 // only pre processing effects on record thread
1431 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1432 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1433 desc->name, mThreadName);
1434 return BAD_VALUE;
1435 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001436
1437 // always allow effects without processing load or latency
1438 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1439 return NO_ERROR;
1440 }
1441
Eric Laurent4c415062016-06-17 16:14:16 -07001442 audio_input_flags_t flags = mInput->flags;
1443 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1444 if (flags & AUDIO_INPUT_FLAG_RAW) {
1445 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1446 desc->name, mThreadName);
1447 return BAD_VALUE;
1448 }
1449 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1450 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1451 desc->name, mThreadName);
1452 return BAD_VALUE;
1453 }
1454 }
jiabineb3bda02020-06-30 14:07:03 -07001455
Andy Hung116bc262023-06-20 18:56:17 -07001456 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001457 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1458 return BAD_VALUE;
1459 }
Eric Laurent4c415062016-06-17 16:14:16 -07001460 return NO_ERROR;
1461}
1462
Andy Hungb17d24b2023-08-29 14:26:09 -07001463// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001464status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001465 const effect_descriptor_t *desc, audio_session_t sessionId)
1466{
1467 // no preprocessing on playback threads
1468 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001469 ALOGW("%s: pre processing effect %s created on playback"
1470 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001471 return BAD_VALUE;
1472 }
1473
Eric Laurent3e4de772017-07-16 16:55:08 -07001474 // always allow effects without processing load or latency
1475 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1476 return NO_ERROR;
1477 }
1478
Andy Hung116bc262023-06-20 18:56:17 -07001479 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001480 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1481 __func__);
1482 return BAD_VALUE;
1483 }
1484
Eric Laurentf690c462021-09-17 14:47:03 +02001485 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1486 && mType != SPATIALIZER) {
1487 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1488 __func__, mType);
1489 return BAD_VALUE;
1490 }
1491
Eric Laurent4c415062016-06-17 16:14:16 -07001492 switch (mType) {
1493 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001494 audio_output_flags_t flags = mOutput->flags;
1495 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1496 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1497 // global effects are applied only to non fast tracks if they are SW
1498 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1499 break;
1500 }
1501 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1502 // only post processing on output stage session
1503 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001504 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1505 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001506 return BAD_VALUE;
1507 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001508 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1509 // only post processing on output stage session
1510 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001511 ALOGW("%s: non post processing effect %s not allowed on device session",
1512 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001513 return BAD_VALUE;
1514 }
Eric Laurent4c415062016-06-17 16:14:16 -07001515 } else {
1516 // no restriction on effects applied on non fast tracks
1517 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1518 break;
1519 }
1520 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001521
Eric Laurent4c415062016-06-17 16:14:16 -07001522 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001523 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001524 return BAD_VALUE;
1525 }
1526 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001527 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1528 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001529 return BAD_VALUE;
1530 }
1531 }
1532 } break;
1533 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001534 // nothing actionable on offload threads, if the effect:
1535 // - is offloadable: the effect can be created
1536 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1537 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001538 break;
1539 case DIRECT:
1540 // Reject any effect on Direct output threads for now, since the format of
1541 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001542 ALOGW("%s: effect %s on DIRECT output thread %s",
1543 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001544 return BAD_VALUE;
1545 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001546 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001547 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1548 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001549 return BAD_VALUE;
1550 }
1551 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001552 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1553 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001554 return BAD_VALUE;
1555 }
1556 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001557 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1558 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001559 return BAD_VALUE;
1560 }
1561 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001562 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001563 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1564 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1565 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1566 // are supported and added after the spatializer.
1567 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1568 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1569 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001570 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001571 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1572 // only post processing , downmixer or spatializer effects on output stage session
1573 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1574 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1575 break;
1576 }
1577 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1578 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1579 __func__, desc->name);
1580 return BAD_VALUE;
1581 }
1582 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1583 // only post processing on output stage session
1584 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1585 ALOGW("%s: non post processing effect %s not allowed on device session",
1586 __func__, desc->name);
1587 return BAD_VALUE;
1588 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001589 }
1590 break;
jiabinc658e452022-10-21 20:52:21 +00001591 case BIT_PERFECT:
1592 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1593 // Allow HW accelerated effects of tunnel type
1594 break;
1595 }
1596 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1597 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1598 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1599 // 3) there is any bit-perfect track with the given session id.
1600 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1601 sessionId == AUDIO_SESSION_DEVICE) {
1602 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1603 __func__, desc->name, mThreadName);
1604 return BAD_VALUE;
1605 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1606 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1607 __func__, desc->name, sessionId);
1608 return BAD_VALUE;
1609 }
1610 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001611 default:
1612 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1613 }
1614
1615 return NO_ERROR;
1616}
1617
Andy Hungb17d24b2023-08-29 14:26:09 -07001618// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001619sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001620 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001621 const sp<IEffectClient>& effectClient,
1622 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001623 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001624 effect_descriptor_t *desc,
1625 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001626 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001627 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001628 bool probe,
1629 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001630{
Andy Hung116bc262023-06-20 18:56:17 -07001631 sp<IAfEffectModule> effect;
1632 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001633 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001634 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 bool chainCreated = false;
1636 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001637 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001638
1639 lStatus = initCheck();
1640 if (lStatus != NO_ERROR) {
1641 ALOGW("createEffect_l() Audio driver not initialized.");
1642 goto Exit;
1643 }
1644
Eric Laurent81784c32012-11-19 14:55:58 -08001645 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1646
Andy Hungb17d24b2023-08-29 14:26:09 -07001647 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07001648 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001649
Eric Laurent4c415062016-06-17 16:14:16 -07001650 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001651 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001652 goto Exit;
1653 }
1654
Eric Laurent81784c32012-11-19 14:55:58 -08001655 // check for existing effect chain with the requested audio session
1656 chain = getEffectChain_l(sessionId);
1657 if (chain == 0) {
1658 // create a new chain for this session
1659 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001660 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001661 addEffectChain_l(chain);
1662 chain->setStrategy(getStrategyForSession_l(sessionId));
1663 chainCreated = true;
1664 } else {
1665 effect = chain->getEffectFromDesc_l(desc);
1666 }
1667
1668 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1669
1670 if (effect == 0) {
Andy Hung7535ed92023-07-17 17:05:00 -07001671 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001672 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001673 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 if (lStatus != NO_ERROR) {
1675 goto Exit;
1676 }
1677 effectCreated = true;
1678
jiabinc52b1ff2019-10-31 17:20:42 -07001679 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001680 effect->setDevices(outDeviceTypeAddrs());
1681 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001682 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001683 effect->setAudioSource(mAudioSource);
1684 }
jiabin1319f5a2021-03-30 22:21:24 +00001685 if (effect->isHapticGenerator()) {
1686 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1687 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001688 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung7535ed92023-07-17 17:05:00 -07001689 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001690 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001691 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001692 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001693 }
1694 }
Eric Laurent81784c32012-11-19 14:55:58 -08001695 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001696 handle = IAfEffectHandle::create(
1697 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001698 lStatus = handle->initCheck();
1699 if (lStatus == OK) {
1700 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001701 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001702 }
Eric Laurent81784c32012-11-19 14:55:58 -08001703 if (enabled != NULL) {
1704 *enabled = (int)effect->isEnabled();
1705 }
1706 }
1707
1708Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001709 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hungf8635b62023-08-31 16:13:39 -07001710 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001711 if (effectCreated) {
1712 chain->removeEffect_l(effect);
1713 }
Eric Laurent81784c32012-11-19 14:55:58 -08001714 if (chainCreated) {
1715 removeEffectChain_l(chain);
1716 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001717 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001718 }
1719
Glenn Kasten9156ef32013-08-06 15:39:08 -07001720 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001721 return handle;
1722}
1723
Andy Hung4b17e882023-07-07 13:47:37 -07001724void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001725 bool unpinIfLast)
1726{
1727 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001728 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001729 {
Andy Hungf8635b62023-08-31 16:13:39 -07001730 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001731 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001732 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001733 return;
1734 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001735 effect = effectBase->asEffectModule();
1736 if (effect == nullptr) {
1737 return;
1738 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001739 // restore suspended effects if the disconnected handle was enabled and the last one.
1740 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1741 if (remove) {
1742 removeEffect_l(effect, true);
1743 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001744 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001745 }
1746 if (remove) {
Andy Hung7535ed92023-07-17 17:05:00 -07001747 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001748 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001749 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750 }
1751 }
1752}
1753
Andy Hung4b17e882023-07-07 13:47:37 -07001754void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001755 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001756 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001757 broadcast_l();
1758 }
1759 if (!effect->isOffloadable()) {
1760 if (mType == ThreadBase::OFFLOAD) {
1761 PlaybackThread *t = (PlaybackThread *)this;
1762 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1763 }
1764 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung7535ed92023-07-17 17:05:00 -07001765 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001766 }
1767 }
1768}
1769
Andy Hung4b17e882023-07-07 13:47:37 -07001770void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001771 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001772 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001773 broadcast_l();
1774 }
1775}
1776
Andy Hung4b17e882023-07-07 13:47:37 -07001777sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001778 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001779{
Andy Hungf8635b62023-08-31 16:13:39 -07001780 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001781 return getEffect_l(sessionId, effectId);
1782}
1783
Andy Hung4b17e882023-07-07 13:47:37 -07001784sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001785 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001786{
Andy Hung116bc262023-06-20 18:56:17 -07001787 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001788 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1789}
1790
Andy Hung4b17e882023-07-07 13:47:37 -07001791std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001792{
Andy Hung116bc262023-06-20 18:56:17 -07001793 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001794 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1795}
1796
Andy Hungf8635b62023-08-31 16:13:39 -07001797// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1798// ThreadBase::mutex() held
1799status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001800{
1801 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001802 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001803 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001804 bool chainCreated = false;
1805
Eric Laurent5baf2af2013-09-12 17:37:00 -07001806 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hungf8635b62023-08-31 16:13:39 -07001807 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1808 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001809
Eric Laurent81784c32012-11-19 14:55:58 -08001810 if (chain == 0) {
1811 // create a new chain for this session
Andy Hungf8635b62023-08-31 16:13:39 -07001812 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001813 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001814 addEffectChain_l(chain);
1815 chain->setStrategy(getStrategyForSession_l(sessionId));
1816 chainCreated = true;
1817 }
Andy Hungf8635b62023-08-31 16:13:39 -07001818 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001819
1820 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hungf8635b62023-08-31 16:13:39 -07001821 ALOGW("%s: %p effect %s already present in chain %p",
1822 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001823 return BAD_VALUE;
1824 }
1825
Eric Laurent5baf2af2013-09-12 17:37:00 -07001826 effect->setOffloaded(mType == OFFLOAD, mId);
1827
Eric Laurent81784c32012-11-19 14:55:58 -08001828 status_t status = chain->addEffect_l(effect);
1829 if (status != NO_ERROR) {
1830 if (chainCreated) {
1831 removeEffectChain_l(chain);
1832 }
1833 return status;
1834 }
1835
jiabin8f278ee2019-11-11 12:16:27 -08001836 effect->setDevices(outDeviceTypeAddrs());
1837 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001838 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001839 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001840
Eric Laurent81784c32012-11-19 14:55:58 -08001841 return NO_ERROR;
1842}
1843
Andy Hung4b17e882023-07-07 13:47:37 -07001844void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001845
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001846 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001847 effect_descriptor_t desc = effect->desc();
1848 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1849 detachAuxEffect_l(effect->id());
1850 }
1851
Andy Hung116bc262023-06-20 18:56:17 -07001852 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001853 if (chain != 0) {
1854 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001855 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001856 removeEffectChain_l(chain);
1857 }
1858 } else {
1859 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1860 }
1861}
1862
Andy Hung4b17e882023-07-07 13:47:37 -07001863void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001864 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001865NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001866{
1867 effectChains = mEffectChains;
1868 for (size_t i = 0; i < mEffectChains.size(); i++) {
Andy Hung1f6d4cd2023-08-29 12:19:17 -07001869 mEffectChains[i]->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001870 }
1871}
1872
Andy Hung4b17e882023-07-07 13:47:37 -07001873void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001874 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001875NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001876{
1877 for (size_t i = 0; i < effectChains.size(); i++) {
Andy Hung1f6d4cd2023-08-29 12:19:17 -07001878 effectChains[i]->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001879 }
1880}
1881
Andy Hung4b17e882023-07-07 13:47:37 -07001882sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001883{
Andy Hungf8635b62023-08-31 16:13:39 -07001884 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001885 return getEffectChain_l(sessionId);
1886}
1887
Andy Hung4b17e882023-07-07 13:47:37 -07001888sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001889 const
Eric Laurent81784c32012-11-19 14:55:58 -08001890{
1891 size_t size = mEffectChains.size();
1892 for (size_t i = 0; i < size; i++) {
1893 if (mEffectChains[i]->sessionId() == sessionId) {
1894 return mEffectChains[i];
1895 }
1896 }
1897 return 0;
1898}
1899
Andy Hung4b17e882023-07-07 13:47:37 -07001900void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001901{
Andy Hungf8635b62023-08-31 16:13:39 -07001902 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001903 size_t size = mEffectChains.size();
1904 for (size_t i = 0; i < size; i++) {
1905 mEffectChains[i]->setMode_l(mode);
1906 }
1907}
1908
Andy Hung4b17e882023-07-07 13:47:37 -07001909void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001910{
1911 config->type = AUDIO_PORT_TYPE_MIX;
1912 config->ext.mix.handle = mId;
1913 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001914 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001915 config->channel_mask = mChannelMask;
1916 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1917 AUDIO_PORT_CONFIG_FORMAT;
1918}
1919
Andy Hung4b17e882023-07-07 13:47:37 -07001920void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001921{
Andy Hungf8635b62023-08-31 16:13:39 -07001922 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001923 if (mSystemReady) {
1924 return;
1925 }
1926 mSystemReady = true;
1927
1928 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1929 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1930 }
1931 mPendingConfigEvents.clear();
1932}
1933
Andy Hungdae27702016-10-31 14:01:16 -07001934template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001935ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001936 ssize_t index = mActiveTracks.indexOf(track);
1937 if (index >= 0) {
1938 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1939 return index;
1940 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001941 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001942 mActiveTracksGeneration++;
1943 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001944 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001945 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001946 return mActiveTracks.add(track);
1947}
1948
1949template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001950ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001951 ssize_t index = mActiveTracks.remove(track);
1952 if (index < 0) {
1953 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1954 return index;
1955 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001956 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001957 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001958 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001959 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001960 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001961#ifdef TEE_SINK
1962 track->dumpTee(-1 /* fd */, "_REMOVE");
1963#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001964 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001965 return index;
1966}
1967
1968template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001969void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001970 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001971 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001972 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001973 }
1974 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001975 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001976 mActiveTracks.clear();
1977 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001978}
1979
1980template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001981void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001982 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001983 // Updates ActiveTracks client uids to the thread wakelock.
1984 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1985 thread->updateWakeLockUids_l(getWakeLockUids());
1986 mLastActiveTracksGeneration = mActiveTracksGeneration;
1987 }
Andy Hungdae27702016-10-31 14:01:16 -07001988}
Eric Laurent83b88082014-06-20 18:31:16 -07001989
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001990template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001991bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001992 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001993 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001994
1995 for (const sp<T> &track : mActiveTracks) {
1996 // Do not short-circuit as all hasChanged states must be reset
1997 // as all the metadata are going to be sent
1998 hasChanged |= track->readAndClearHasChanged();
1999 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002000 return hasChanged;
2001}
2002
2003template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002004void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002005 const char *funcName, const sp<T> &track) const {
2006 if (mLocalLog != nullptr) {
2007 String8 result;
2008 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002009 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002010 }
2011}
2012
Andy Hung4b17e882023-07-07 13:47:37 -07002013void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002014{
2015 // Thread could be blocked waiting for async
2016 // so signal it to handle state changes immediately
2017 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2018 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2019 mSignalPending = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07002020 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002021}
2022
Andy Hungd0979812019-02-21 15:51:44 -08002023// Call only from threadLoop() or when it is idle.
2024// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07002025void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08002026{
2027 // Do not log if we have no stats.
2028 // We choose the timestamp verifier because it is the most likely item to be present.
2029 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2030 if (nstats == 0) {
2031 return;
2032 }
2033
2034 // Don't log more frequently than once per 12 hours.
2035 // We use BOOTTIME to include suspend time.
2036 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2037 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2038 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2039 return;
2040 }
2041
2042 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2043 mLastRecordedTimeNs = timeNs;
2044
Ray Essickf27e9872019-12-07 06:28:46 -08002045 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002046
2047#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2048
2049 // thread configuration
2050 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2051 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2052 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2053 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2054 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2055 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2056 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002057 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2058 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002059
2060 // thread statistics
2061 if (mIoJitterMs.getN() > 0) {
2062 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2063 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2064 }
2065 if (mProcessTimeMs.getN() > 0) {
2066 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2067 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2068 }
2069 const auto tsjitter = mTimestampVerifier.getJitterMs();
2070 if (tsjitter.getN() > 0) {
2071 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2072 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2073 }
2074 if (mLatencyMs.getN() > 0) {
2075 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2076 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2077 }
Robert Wu06db0a32021-08-10 19:05:34 +00002078 if (mMonopipePipeDepthStats.getN() > 0) {
2079 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2080 mMonopipePipeDepthStats.getMean());
2081 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2082 mMonopipePipeDepthStats.getStdDev());
2083 }
Andy Hungd0979812019-02-21 15:51:44 -08002084
2085 item->selfrecord();
2086}
2087
Andy Hung4b17e882023-07-07 13:47:37 -07002088product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002089{
Andy Hung7535ed92023-07-17 17:05:00 -07002090 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002091 return PRODUCT_STRATEGY_NONE;
2092 }
2093 return AudioSystem::getStrategyForStream(stream);
2094}
2095
Andy Hungb17d24b2023-08-29 14:26:09 -07002096// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002097void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002098 const sp<audio_utils::MelProcessor>& /*processor*/)
2099{
2100 // Do nothing
2101 ALOGW("%s: ThreadBase does not support CSD", __func__);
2102}
2103
Andy Hungb17d24b2023-08-29 14:26:09 -07002104// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002105void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002106{
2107 // Do nothing
2108 ALOGW("%s: ThreadBase does not support CSD", __func__);
2109}
2110
Eric Laurent81784c32012-11-19 14:55:58 -08002111// ----------------------------------------------------------------------------
2112// Playback
2113// ----------------------------------------------------------------------------
2114
Andy Hung7535ed92023-07-17 17:05:00 -07002115PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002116 AudioStreamOut* output,
2117 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002118 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002119 bool systemReady,
2120 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002121 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002122 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002123 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002124 mMixerBuffer(NULL),
2125 mMixerBufferSize(0),
2126 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2127 mMixerBufferValid(false),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002128 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002129 mEffectBuffer(NULL),
2130 mEffectBufferSize(0),
2131 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2132 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002133 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002134 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002135 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002136 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002137 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002138 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002139 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002140 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002141 mMixerStatus(MIXER_IDLE),
2142 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hungd58c4732023-07-20 21:31:38 -07002143 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002144 mBytesRemaining(0),
2145 mCurrentWriteLength(0),
2146 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002147 mWriteAckSequence(0),
2148 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002149 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002150 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002151 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002152 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002153 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002154 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002155 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002156{
Glenn Kastend7dca052015-03-05 16:05:54 -08002157 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002158 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002159
Andy Hungb17d24b2023-08-29 14:26:09 -07002160 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002161 // it would be safer to explicitly pass initial masterVolume/masterMute as
2162 // parameter.
2163 //
2164 // If the HAL we are using has support for master volume or master mute,
2165 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2166 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002167 mMasterVolume = afThreadCallback->masterVolume_l();
2168 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002169 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002170 if (mOutput->audioHwDev->canSetMasterVolume()) {
2171 mMasterVolume = 1.0;
2172 }
2173
2174 if (mOutput->audioHwDev->canSetMasterMute()) {
2175 mMasterMute = false;
2176 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002177 mIsMsdDevice = strcmp(
2178 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002179 }
2180
Eric Laurentf1f22e72021-07-13 14:04:14 +02002181 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2182 mMixerChannelMask = mixerConfig->channel_mask;
2183 }
2184
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002185 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002186
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002187 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002188 && mMixerChannelMask != mChannelMask) {
2189 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2190 mChannelMask, mMixerChannelMask);
2191 }
2192
Andy Hungc8fddf32018-08-08 18:32:37 -07002193 // TODO: We may also match on address as well as device type for
2194 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002195 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002196 // TODO: This property should be ensure that only contains one single device type.
2197 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2198 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002199 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2200 : AUDIO_DEVICE_NONE));
2201 }
2202
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002203 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2204 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002205 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002206 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002207 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002208 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002209 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2210 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002211 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2212 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002213}
2214
Andy Hung4b17e882023-07-07 13:47:37 -07002215PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002216{
Andy Hung7535ed92023-07-17 17:05:00 -07002217 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002218 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002219 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002220 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002221 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002222}
2223
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002224// Thread virtuals
2225
Andy Hung4b17e882023-07-07 13:47:37 -07002226void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002227{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002228 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002229 ALOGE("The stream is not open yet"); // This should not happen.
2230 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002231 // Callbacks take strong or weak pointers as a parameter.
2232 // Since PlaybackThread passes itself as a callback handler, it can only
2233 // be done outside of the constructor. Creating weak and especially strong
2234 // pointers to a refcounted object in its own constructor is strongly
2235 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2236 // Even if a function takes a weak pointer, it is possible that it will
2237 // need to convert it to a strong pointer down the line.
2238 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2239 mOutput->stream->setCallback(this) == OK) {
2240 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002241 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002242 }
2243
jiabinf6eb4c32020-02-25 14:06:25 -08002244 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002245 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002246 }
2247 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002248 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002249 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002250}
2251
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002252// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002253void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002254{
2255 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002256 status_t result = mOutput->stream->exit();
2257 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002258}
2259
Andy Hung4b17e882023-07-07 13:47:37 -07002260void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002261{
Eric Laurent81784c32012-11-19 14:55:58 -08002262 String8 result;
2263
Marco Nelissenb2208842014-02-07 14:00:50 -08002264 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002265 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2266 const stream_type_t *st = &mStreamTypes[i];
2267 if (i > 0) {
2268 result.appendFormat(", ");
2269 }
2270 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2271 if (st->mute) {
2272 result.append("M");
2273 }
2274 }
2275 result.append("\n");
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002276 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002277 result.clear();
2278
Eric Laurent81784c32012-11-19 14:55:58 -08002279 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2280 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002281 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002282 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002283
2284 size_t numtracks = mTracks.size();
2285 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002286 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002287 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002288 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002289 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002290 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002291 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002292 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002293 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002294 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002295 if (track != 0) {
2296 bool active = mActiveTracks.indexOf(track) >= 0;
2297 if (active) {
2298 numactiveseen++;
2299 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002300 result.append(prefix);
2301 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002302 }
2303 }
2304 } else {
2305 result.append("\n");
2306 }
2307 if (numactiveseen != numactive) {
2308 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002309 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002310 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002311 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002312 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002313 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002314 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002315 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002316 result.append(prefix);
2317 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002318 }
2319 }
2320 }
2321
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002322 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002323}
2324
Andy Hung4b17e882023-07-07 13:47:37 -07002325void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002326{
Andy Hung04cb8f72020-03-20 13:44:33 -07002327 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002328 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002329 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2330 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002331 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2332 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2333 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2334 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002335 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002336 dprintf(fd, " Total writes: %d\n", mNumWrites);
2337 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2338 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2339 dprintf(fd, " Suspend count: %d\n", mSuspended);
2340 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2341 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2342 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2343 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002344 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002345 AudioStreamOut *output = mOutput;
2346 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002347 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002348 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002349 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2350 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2351 if (mPipeSink.get() != nullptr) {
2352 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2353 }
2354 if (output != nullptr) {
2355 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002356 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358}
2359
Andy Hungb17d24b2023-08-29 14:26:09 -07002360// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002361sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002362 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002363 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002364 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002365 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002366 audio_format_t format,
2367 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002368 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002369 size_t *pNotificationFrameCount,
2370 uint32_t notificationsPerBuffer,
2371 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002372 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002373 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002374 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002375 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002376 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002377 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002378 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002379 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002380 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002381 bool isSpatialized,
2382 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002383{
Glenn Kasten74935e42013-12-19 08:56:45 -08002384 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002385 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002386 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002387 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002388 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002389 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002390 uint32_t sampleRate;
2391
2392 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2393 lStatus = BAD_VALUE;
2394 goto Exit;
2395 }
Eric Laurent21da6472017-11-09 16:29:26 -08002396
2397 if (*pSampleRate == 0) {
2398 *pSampleRate = mSampleRate;
2399 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002400 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002401
2402 // special case for FAST flag considered OK if fast mixer is present
2403 if (hasFastMixer()) {
2404 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2405 }
2406
2407 // Check if requested flags are compatible with output stream flags
2408 if ((*flags & outputFlags) != *flags) {
2409 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2410 *flags, outputFlags);
2411 *flags = (audio_output_flags_t)(*flags & outputFlags);
2412 }
Eric Laurent81784c32012-11-19 14:55:58 -08002413
jiabinc658e452022-10-21 20:52:21 +00002414 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002415 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002416 if (chain.get() != nullptr) {
2417 // Bit-perfect is required according to the configuration and preferred mixer
2418 // attributes, but it is not in the output flag from the client's request. Explicitly
2419 // adding bit-perfect flag to check the compatibility
2420 audio_output_flags_t flagsToCheck =
2421 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2422 chain->checkOutputFlagCompatibility(&flagsToCheck);
2423 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2424 ALOGE("%s cannot create track as there is data-processing effect attached to "
2425 "given session id(%d)", __func__, sessionId);
2426 lStatus = BAD_VALUE;
2427 goto Exit;
2428 }
2429 *flags = flagsToCheck;
2430 }
2431 }
2432
Eric Laurent81784c32012-11-19 14:55:58 -08002433 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002434 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002435 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002436 // PCM data
2437 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002438 // TODO: extract as a data library function that checks that a computationally
2439 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002440 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002441 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2442 (channelMask == AUDIO_CHANNEL_OUT_MONO
2443 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002444 // hardware sample rate
2445 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002446 // normal mixer has an associated fast mixer
2447 hasFastMixer() &&
2448 // there are sufficient fast track slots available
2449 (mFastTrackAvailMask != 0)
2450 // FIXME test that MixerThread for this fast track has a capable output HAL
2451 // FIXME add a permission test also?
2452 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002453 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2454 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002455 // read the fast track multiplier property the first time it is needed
2456 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2457 if (ok != 0) {
2458 ALOGE("%s pthread_once failed: %d", __func__, ok);
2459 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002460 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002461 }
Eric Laurent4c415062016-06-17 16:14:16 -07002462
2463 // check compatibility with audio effects.
Andy Hungb17d24b2023-08-29 14:26:09 -07002464 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002465 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002466 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002467 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002468 AUDIO_SESSION_OUTPUT_STAGE,
2469 AUDIO_SESSION_OUTPUT_MIX,
2470 sessionId,
2471 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002472 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002473 if (chain.get() != nullptr) {
2474 audio_output_flags_t old = *flags;
2475 chain->checkOutputFlagCompatibility(flags);
2476 if (old != *flags) {
2477 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2478 (int)session, (int)old, (int)*flags);
2479 }
Eric Laurent4c415062016-06-17 16:14:16 -07002480 }
2481 }
2482 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002483 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002484 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2485 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002486 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002487 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002488 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002489 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002490 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002491 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002492 audio_is_linear_pcm(format), channelMask, sampleRate,
2493 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002494 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002495 }
2496 }
Eric Laurent21da6472017-11-09 16:29:26 -08002497
2498 if (!audio_has_proportional_frames(format)) {
2499 if (sharedBuffer != 0) {
2500 // Same comment as below about ignoring frameCount parameter for set()
2501 frameCount = sharedBuffer->size();
2502 } else if (frameCount == 0) {
2503 frameCount = mNormalFrameCount;
2504 }
2505 if (notificationFrameCount != frameCount) {
2506 notificationFrameCount = frameCount;
2507 }
2508 } else if (sharedBuffer != 0) {
2509 // FIXME: Ensure client side memory buffers need
2510 // not have additional alignment beyond sample
2511 // (e.g. 16 bit stereo accessed as 32 bit frame).
2512 size_t alignment = audio_bytes_per_sample(format);
2513 if (alignment & 1) {
2514 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2515 alignment = 1;
2516 }
2517 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2518 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2519 if (channelCount > 1) {
2520 // More than 2 channels does not require stronger alignment than stereo
2521 alignment <<= 1;
2522 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002523 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002524 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002525 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002526 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002527 goto Exit;
2528 }
Eric Laurent21da6472017-11-09 16:29:26 -08002529
2530 // When initializing a shared buffer AudioTrack via constructors,
2531 // there's no frameCount parameter.
2532 // But when initializing a shared buffer AudioTrack via set(),
2533 // there _is_ a frameCount parameter. We silently ignore it.
2534 frameCount = sharedBuffer->size() / frameSize;
2535 } else {
2536 size_t minFrameCount = 0;
2537 // For fast tracks we try to respect the application's request for notifications per buffer.
2538 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2539 if (notificationsPerBuffer > 0) {
2540 // Avoid possible arithmetic overflow during multiplication.
2541 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2542 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2543 notificationsPerBuffer, mFrameCount);
2544 } else {
2545 minFrameCount = mFrameCount * notificationsPerBuffer;
2546 }
2547 }
2548 } else {
2549 // For normal PCM streaming tracks, update minimum frame count.
2550 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2551 // cover audio hardware latency.
2552 // This is probably too conservative, but legacy application code may depend on it.
2553 // If you change this calculation, also review the start threshold which is related.
2554 uint32_t latencyMs = latency_l();
2555 if (latencyMs == 0) {
2556 ALOGE("Error when retrieving output stream latency");
2557 lStatus = UNKNOWN_ERROR;
2558 goto Exit;
2559 }
2560
2561 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2562 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2563
Eric Laurent81784c32012-11-19 14:55:58 -08002564 }
Eric Laurent21da6472017-11-09 16:29:26 -08002565 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002566 frameCount = minFrameCount;
2567 }
Eric Laurent81784c32012-11-19 14:55:58 -08002568 }
Eric Laurent21da6472017-11-09 16:29:26 -08002569
2570 // Make sure that application is notified with sufficient margin before underrun.
2571 // The client can divide the AudioTrack buffer into sub-buffers,
2572 // and expresses its desire to server as the notification frame count.
2573 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2574 size_t maxNotificationFrames;
2575 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2576 // notify every HAL buffer, regardless of the size of the track buffer
2577 maxNotificationFrames = mFrameCount;
2578 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002579 // Triple buffer the notification period for a triple buffered mixer period;
2580 // otherwise, double buffering for the notification period is fine.
2581 //
2582 // TODO: This should be moved to AudioTrack to modify the notification period
2583 // on AudioTrack::setBufferSizeInFrames() changes.
2584 const int nBuffering =
2585 (uint64_t{frameCount} * mSampleRate)
2586 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2587
Eric Laurent21da6472017-11-09 16:29:26 -08002588 maxNotificationFrames = frameCount / nBuffering;
2589 // If client requested a fast track but this was denied, then use the smaller maximum.
2590 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2591 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2592 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2593 maxNotificationFrames = maxNotificationFramesFastDenied;
2594 }
2595 }
2596 }
2597 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2598 if (notificationFrameCount == 0) {
2599 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2600 maxNotificationFrames, frameCount);
2601 } else {
2602 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2603 notificationFrameCount, maxNotificationFrames, frameCount);
2604 }
2605 notificationFrameCount = maxNotificationFrames;
2606 }
2607 }
2608
Glenn Kasten74935e42013-12-19 08:56:45 -08002609 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002610 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002611
Glenn Kastenc3df8382014-03-13 15:05:25 -07002612 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002613 case BIT_PERFECT:
2614 if (isBitPerfect) {
2615 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2616 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2617 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2618 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2619 mChannelMask);
2620 lStatus = BAD_VALUE;
2621 goto Exit;
2622 }
2623 }
2624 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002625
2626 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002627 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002628 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002629 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2630 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002631 sampleRate, format, channelMask, mOutput, mFormat);
2632 lStatus = BAD_VALUE;
2633 goto Exit;
2634 }
2635 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002636 break;
2637
2638 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002640 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2641 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 sampleRate, format, channelMask, mOutput, mFormat);
2643 lStatus = BAD_VALUE;
2644 goto Exit;
2645 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002646 break;
2647
2648 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002649 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002650 ALOGE("createTrack_l() Bad parameter: format %#x \""
2651 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002652 format, mOutput, mFormat);
2653 lStatus = BAD_VALUE;
2654 goto Exit;
2655 }
Andy Hungcd044842014-08-07 11:04:34 -07002656 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002657 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2658 lStatus = BAD_VALUE;
2659 goto Exit;
2660 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002661 break;
2662
Eric Laurent81784c32012-11-19 14:55:58 -08002663 }
2664
2665 lStatus = initCheck();
2666 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002667 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002668 goto Exit;
2669 }
2670
Andy Hungb17d24b2023-08-29 14:26:09 -07002671 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002672 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002673
2674 // all tracks in same audio session must share the same routing strategy otherwise
2675 // conflicts will happen when tracks are moved from one output to another by audio policy
2676 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002677 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002678 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002679 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002680 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002681 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002682 if (sessionId == t->sessionId() && strategy != actual) {
2683 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2684 strategy, actual);
2685 lStatus = BAD_VALUE;
2686 goto Exit;
2687 }
2688 }
2689 }
2690
yucliuc9c49cd2020-07-13 16:25:21 -07002691 // Set DIRECT flag if current thread is DirectOutputThread. This can
2692 // happen when the playback is rerouted to direct output thread by
2693 // dynamic audio policy.
2694 // Do NOT report the flag changes back to client, since the client
2695 // doesn't explicitly request a direct flag.
2696 audio_output_flags_t trackFlags = *flags;
2697 if (mType == DIRECT) {
2698 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2699 }
2700
Andy Hung11e74242023-06-26 19:20:57 -07002701 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002702 channelMask, frameCount,
2703 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002704 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002705 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002706 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002707
Glenn Kasten03003332013-08-06 15:40:54 -07002708 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2709 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002710 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002711 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002712 goto Exit;
2713 }
2714 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002715 {
Andy Hungf8635b62023-08-31 16:13:39 -07002716 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002717 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002718 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002719 }
2720 }
Eric Laurent81784c32012-11-19 14:55:58 -08002721
Andy Hung116bc262023-06-20 18:56:17 -07002722 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002723 if (chain != 0) {
2724 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2725 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002726 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002727 chain->incTrackCnt();
2728 }
2729
Eric Laurent05067782016-06-01 18:27:28 -07002730 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002731 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2732 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2733 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002734 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002735 }
2736 }
2737
2738 lStatus = NO_ERROR;
2739
2740Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002741 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002742 return track;
2743}
2744
Andy Hung1bc088a2018-02-09 15:57:31 -08002745template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002746ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002747{
Andy Hungc0691382018-09-12 18:01:57 -07002748 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002749 const ssize_t index = mTracks.remove(track);
2750 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002751 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002752 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002753 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002754 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002755 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002756 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002757 }
2758 return index;
2759}
2760
Andy Hung4b17e882023-07-07 13:47:37 -07002761uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002762{
2763 return latency;
2764}
2765
Andy Hung4b17e882023-07-07 13:47:37 -07002766uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002767{
Andy Hungf8635b62023-08-31 16:13:39 -07002768 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002769 return latency_l();
2770}
Andy Hung4b17e882023-07-07 13:47:37 -07002771uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002772{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002773 uint32_t latency;
2774 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2775 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002776 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002777 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002778}
2779
Andy Hung4b17e882023-07-07 13:47:37 -07002780void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002781{
Andy Hungf8635b62023-08-31 16:13:39 -07002782 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002783 // Don't apply master volume in SW if our HAL can do it for us.
2784 if (mOutput && mOutput->audioHwDev &&
2785 mOutput->audioHwDev->canSetMasterVolume()) {
2786 mMasterVolume = 1.0;
2787 } else {
2788 mMasterVolume = value;
2789 }
2790}
2791
Andy Hung4b17e882023-07-07 13:47:37 -07002792void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002793{
2794 mMasterBalance.store(balance);
2795}
2796
Andy Hung4b17e882023-07-07 13:47:37 -07002797void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002798{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002799 if (isDuplicating()) {
2800 return;
2801 }
Andy Hungf8635b62023-08-31 16:13:39 -07002802 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002803 // Don't apply master mute in SW if our HAL can do it for us.
2804 if (mOutput && mOutput->audioHwDev &&
2805 mOutput->audioHwDev->canSetMasterMute()) {
2806 mMasterMute = false;
2807 } else {
2808 mMasterMute = muted;
2809 }
2810}
2811
Andy Hung4b17e882023-07-07 13:47:37 -07002812void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002813{
Andy Hungf8635b62023-08-31 16:13:39 -07002814 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002815 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002816 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002817}
2818
Andy Hung4b17e882023-07-07 13:47:37 -07002819void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002820{
Andy Hungf8635b62023-08-31 16:13:39 -07002821 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002822 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002823 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002824}
2825
Andy Hung4b17e882023-07-07 13:47:37 -07002826float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002827{
Andy Hungf8635b62023-08-31 16:13:39 -07002828 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002829 return mStreamTypes[stream].volume;
2830}
2831
Andy Hung4b17e882023-07-07 13:47:37 -07002832void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002833{
2834 mOutput->stream->setVolume(left, right);
2835}
2836
Andy Hungb17d24b2023-08-29 14:26:09 -07002837// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002838status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hungb17d24b2023-08-29 14:26:09 -07002839NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08002840{
2841 status_t status = ALREADY_EXISTS;
2842
Eric Laurent81784c32012-11-19 14:55:58 -08002843 if (mActiveTracks.indexOf(track) < 0) {
2844 // the track is newly added, make sure it fills up all its
2845 // buffers before playing. This is to ensure the client will
2846 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002847 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002848 IAfTrackBase::track_state state = track->state();
Andy Hungb17d24b2023-08-29 14:26:09 -07002849 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002850 status = AudioSystem::startOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002851 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002852 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002853 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002854 if (status == NO_ERROR) {
Andy Hungb17d24b2023-08-29 14:26:09 -07002855 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002856 AudioSystem::stopOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002857 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 }
2859 return INVALID_OPERATION;
2860 }
2861 // abort if start is rejected by audio policy manager
2862 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002863 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2864 // current playback thread is reopened, which may happen when clients set preferred
2865 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2866 // immediately.
2867 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 }
2869#ifdef ADD_BATTERY_DATA
2870 // to track the speaker usage
2871 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2872#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002873 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 }
2875
Eric Laurent51716182016-02-29 18:00:56 -08002876 // set retry count for buffer fill
2877 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002878 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002879 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002880 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002881 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002882 }
Andy Hung11e74242023-06-26 19:20:57 -07002883 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002884 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002885 track->retryCount() = kMaxTrackStartupRetries;
2886 track->fillingStatus() =
2887 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002888 }
2889
Andy Hung116bc262023-06-20 18:56:17 -07002890 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002891 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2892 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2893 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002894 // Unlock due to VibratorService will lock for this call and will
2895 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungb17d24b2023-08-29 14:26:09 -07002896 mutex().unlock();
Andy Hung76cb9152023-07-20 21:23:42 -07002897 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002898 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002899 std::optional<media::AudioVibratorInfo> vibratorInfo;
2900 {
2901 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2902 // used to play this track.
Andy Hungf8635b62023-08-31 16:13:39 -07002903 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung7535ed92023-07-17 17:05:00 -07002904 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002905 }
Andy Hungb17d24b2023-08-29 14:26:09 -07002906 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002907 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002908 if (vibratorInfo) {
2909 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2910 }
2911
jiabin57303cc2018-12-18 15:45:57 -08002912 // Haptic playback should be enabled by vibrator service.
2913 if (track->getHapticPlaybackEnabled()) {
2914 // Disable haptic playback of all active track to ensure only
2915 // one track playing haptic if current track should play haptic.
2916 for (const auto &t : mActiveTracks) {
2917 t->setHapticPlaybackEnabled(false);
2918 }
jiabin245cdd92018-12-07 17:55:15 -08002919 }
jiabine70bc7f2020-06-30 22:07:55 -07002920
2921 // Set haptic intensity for effect
2922 if (chain != nullptr) {
2923 chain->setHapticIntensity_l(track->id(), intensity);
2924 }
jiabin245cdd92018-12-07 17:55:15 -08002925 }
2926
Andy Hung11e74242023-06-26 19:20:57 -07002927 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002928 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002929 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002930 if (chain != 0) {
2931 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2932 track->sessionId());
2933 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002934 }
2935
Andy Hungc2b11cb2020-04-22 09:04:01 -07002936 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002937 status = NO_ERROR;
2938 }
2939
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002940 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002941 return status;
2942}
2943
Andy Hung4b17e882023-07-07 13:47:37 -07002944bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002945{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002946 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002947 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002948 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002949 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002951 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002952 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002953 if (track->isPausePending()) {
2954 track->pauseAck();
2955 }
Andy Hung11e74242023-06-26 19:20:57 -07002956 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002957 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958
2959 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002960}
2961
Andy Hung4b17e882023-07-07 13:47:37 -07002962void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002963{
2964 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002965
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002966 String8 result;
2967 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002968 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002969
Eric Laurent81784c32012-11-19 14:55:58 -08002970 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002971 {
Andy Hungf8635b62023-08-31 16:13:39 -07002972 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002973 mAudioTrackCallbacks.erase(track);
2974 }
Eric Laurent81784c32012-11-19 14:55:58 -08002975 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002976 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002977 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002978 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2979 mFastTrackAvailMask |= 1 << index;
2980 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07002981 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002982 }
Andy Hung116bc262023-06-20 18:56:17 -07002983 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002984 if (chain != 0) {
2985 chain->decTrackCnt();
2986 }
2987}
2988
Andy Hung4b17e882023-07-07 13:47:37 -07002989String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002990{
Andy Hungf8635b62023-08-31 16:13:39 -07002991 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002992 String8 out_s8;
2993 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2994 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002995 }
Andy Hung920f6572022-10-06 12:09:49 -07002996 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002997}
2998
Andy Hung4b17e882023-07-07 13:47:37 -07002999status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hungf8635b62023-08-31 16:13:39 -07003000 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003001 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003002 return NO_INIT;
3003 }
3004 return mOutput->stream->selectPresentation(presentationId, programId);
3005}
3006
Andy Hung4b17e882023-07-07 13:47:37 -07003007void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003008 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003009 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003010 sp<AudioIoDescriptor> desc;
3011 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003012 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003013 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003014 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003015 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003016 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3017 mSampleRate, mFormat, mChannelMask,
3018 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3019 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003020 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003021 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003022 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003023 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003024 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003025 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003026 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003027 break;
3028 }
Andy Hung7535ed92023-07-17 17:05:00 -07003029 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003030}
3031
Andy Hung4b17e882023-07-07 13:47:37 -07003032void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003033{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003034 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003035}
3036
Andy Hung4b17e882023-07-07 13:47:37 -07003037void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003038{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003039 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040}
3041
Andy Hung4b17e882023-07-07 13:47:37 -07003042void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003043{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003044 mCallbackThread->setAsyncError();
3045}
3046
Andy Hung4b17e882023-07-07 13:47:37 -07003047void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003048 const std::basic_string<uint8_t>& metadataBs)
3049{
Andy Hung4b17e882023-07-07 13:47:37 -07003050 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003051 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07003052 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003053 if (playbackThread == nullptr) {
3054 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3055 return;
3056 }
3057
jiabinf6eb4c32020-02-25 14:06:25 -08003058 audio_utils::metadata::Data metadata =
3059 audio_utils::metadata::dataFromByteString(metadataBs);
3060 if (metadata.empty()) {
3061 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3062 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3063 (int)metadataBs.size());
3064 return;
3065 }
3066
3067 audio_utils::metadata::ByteString metaDataStr =
3068 audio_utils::metadata::byteStringFromData(metadata);
3069 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hungf8635b62023-08-31 16:13:39 -07003070 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003071 for (const auto& callbackPair : mAudioTrackCallbacks) {
3072 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003073 }
3074 }).detach();
3075}
3076
Andy Hung4b17e882023-07-07 13:47:37 -07003077void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003078{
Andy Hungf8635b62023-08-31 16:13:39 -07003079 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003080 // reject out of sequence requests
3081 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3082 mWriteAckSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003083 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003084 }
3085}
3086
Andy Hung4b17e882023-07-07 13:47:37 -07003087void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088{
Andy Hungf8635b62023-08-31 16:13:39 -07003089 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003090 // reject out of sequence requests
3091 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003092 // Register discontinuity when HW drain is completed because that can cause
3093 // the timestamp frame position to reset to 0 for direct and offload threads.
3094 // (Out of sequence requests are ignored, since the discontinuity would be handled
3095 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003096 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003097 mDrainSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003098 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099 }
3100}
3101
Andy Hung4b17e882023-07-07 13:47:37 -07003102void PlaybackThread::readOutputParameters_l()
Andy Hungf8635b62023-08-31 16:13:39 -07003103NO_THREAD_SAFETY_ANALYSIS
3104// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003105{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003106 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003107 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3108 mSampleRate = audioConfig.sample_rate;
3109 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003110 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003111 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003112 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003113 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003114 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3115 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003116 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003117
3118 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3119 mMixerChannelMask = mChannelMask;
3120 }
3121
Andy Hunge5412692014-05-16 11:25:07 -07003122 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003123 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003124
Eric Laurentf1f22e72021-07-13 14:04:14 +02003125 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3126
Phil Burkca5e6142015-07-14 09:42:29 -07003127 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003128 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003129 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003130 // Get format from the shim, which will be different than the HAL format
3131 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003132 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003133 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003134 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003135 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003136 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003137 LOG_FATAL("HAL format %#x not supported for mixed output",
3138 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003139 }
Phil Burk062e67a2015-02-11 13:40:50 -08003140 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003141 result = mOutput->stream->getBufferSize(&mBufferSize);
3142 LOG_ALWAYS_FATAL_IF(result != OK,
3143 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003144 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003145 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003146 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003147 mFrameCount);
3148 }
3149
Eric Laurentd1f69b02014-12-15 14:33:13 -08003150 mHwSupportsPause = false;
3151 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003152 bool supportsPause = false, supportsResume = false;
3153 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3154 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003155 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003156 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003157 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003158 } else if (supportsResume) {
3159 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003160 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003161 }
3162 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003163 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3164 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3165 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003166
Andy Hungfbfc3952015-01-15 13:33:51 -08003167 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3168 // For best precision, we use float instead of the associated output
3169 // device format (typically PCM 16 bit).
3170
3171 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3172 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3173 mBufferSize = mFrameSize * mFrameCount;
3174
3175 // TODO: We currently use the associated output device channel mask and sample rate.
3176 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3177 // (if a valid mask) to avoid premature downmix.
3178 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3179 // instead of the output device sample rate to avoid loss of high frequency information.
3180 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3181 }
3182
Andy Hung09a50072014-02-27 14:30:47 -08003183 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003184 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003185 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003186 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3187 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003188 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3189 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003190
Eric Laurent81784c32012-11-19 14:55:58 -08003191 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3192 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3193 maxNormalFrameCount = maxNormalFrameCount & ~15;
3194 if (maxNormalFrameCount < minNormalFrameCount) {
3195 maxNormalFrameCount = minNormalFrameCount;
3196 }
3197 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3198 if (multiplier <= 1.0) {
3199 multiplier = 1.0;
3200 } else if (multiplier <= 2.0) {
3201 if (2 * mFrameCount <= maxNormalFrameCount) {
3202 multiplier = 2.0;
3203 } else {
3204 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3205 }
3206 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003207 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003208 }
3209 }
3210 mNormalFrameCount = multiplier * mFrameCount;
3211 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003212 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003213 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3214 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003215 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003216 mNormalFrameCount);
3217
Andy Hung08fb1742015-05-31 23:22:10 -07003218 // Check if we want to throttle the processing to no more than 2x normal rate
3219 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003220 mThreadThrottleTimeMs = 0;
3221 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003222 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3223
Andy Hung010a1a12014-03-13 13:57:33 -07003224 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3225 // Originally this was int16_t[] array, need to remove legacy implications.
3226 free(mSinkBuffer);
3227 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003228
Andy Hung5b10a202014-03-13 13:59:29 -07003229 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3230 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3231 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003232 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003233
Andy Hung69aed5f2014-02-25 17:24:40 -08003234 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3235 // drives the output.
3236 free(mMixerBuffer);
3237 mMixerBuffer = NULL;
3238 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003239 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003240 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003241 * audio_bytes_per_sample(mMixerBufferFormat);
3242 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3243 }
Andy Hung98ef9782014-03-04 14:46:50 -08003244 free(mEffectBuffer);
3245 mEffectBuffer = NULL;
3246 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003247 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003248 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003249 * audio_bytes_per_sample(mEffectBufferFormat);
3250 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3251 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003252
Eric Laurentb62d0362021-10-26 17:40:18 +02003253 if (mType == SPATIALIZER) {
3254 free(mPostSpatializerBuffer);
3255 mPostSpatializerBuffer = nullptr;
3256 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3257 * audio_bytes_per_sample(mEffectBufferFormat);
3258 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3259 }
3260
Mikhail Naganov55773032020-10-01 15:08:13 -07003261 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3262 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003263 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3264 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003265 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003266
Eric Laurent81784c32012-11-19 14:55:58 -08003267 // force reconfiguration of effect chains and engines to take new buffer size and audio
3268 // parameters into account
Andy Hungb17d24b2023-08-29 14:26:09 -07003269 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003270 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3271 // matter.
Andy Hungf8635b62023-08-31 16:13:39 -07003272 // create a copy of mEffectChains as calling moveEffectChain_ll()
3273 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003274 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003275 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hungf8635b62023-08-31 16:13:39 -07003276 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003277 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003278 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003279
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003280 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003281 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003282 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07003283 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003284 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3285 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3286 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3287 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3288 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3289 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3290 (int32_t)mHapticChannelMask)
3291 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3292 (int32_t)mHapticChannelCount)
3293 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -07003294 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003295 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3296 (int32_t)mFrameCount) // sic - added HAL
3297 ;
3298 uint32_t latencyMs;
3299 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3300 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3301 }
3302 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003303}
3304
Andy Hung4b17e882023-07-07 13:47:37 -07003305ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003306{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003307 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003308 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003309 }
3310 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003311 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07003312 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003313 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003314 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003315 }
Kevin Rocard12381092018-04-11 09:19:59 -07003316 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003317 MetadataUpdate change;
3318 change.playbackMetadataUpdate = metadata.tracks;
3319 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003320}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003321
Andy Hung4b17e882023-07-07 13:47:37 -07003322void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003323 const StreamOutHalInterface::SourceMetadata& metadata)
3324{
3325 mOutput->stream->updateSourceMetadata(metadata);
3326};
3327
Andy Hung4b17e882023-07-07 13:47:37 -07003328status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003329 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003330{
3331 if (halFrames == NULL || dspFrames == NULL) {
3332 return BAD_VALUE;
3333 }
Andy Hungf8635b62023-08-31 16:13:39 -07003334 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003335 if (initCheck() != NO_ERROR) {
3336 return INVALID_OPERATION;
3337 }
Andy Hung818e7a32016-02-16 18:08:07 -08003338 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003339 *halFrames = framesWritten;
3340
3341 if (isSuspended()) {
3342 // return an estimation of rendered frames when the output is suspended
3343 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003344 *dspFrames = (uint32_t)
3345 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003346 return NO_ERROR;
3347 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003348 status_t status;
3349 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003350 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003351 *dspFrames = (size_t)frames;
3352 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003353 }
3354}
3355
Andy Hung4b17e882023-07-07 13:47:37 -07003356product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003357{
3358 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3359 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3360 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003361 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003362 }
3363 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003364 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003365 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003366 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003367 }
3368 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003369 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003370}
3371
3372
Andy Hung4b17e882023-07-07 13:47:37 -07003373AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003374{
Andy Hungf8635b62023-08-31 16:13:39 -07003375 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003376 return mOutput;
3377}
3378
Andy Hung4b17e882023-07-07 13:47:37 -07003379AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003380{
Andy Hungf8635b62023-08-31 16:13:39 -07003381 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003382 AudioStreamOut *output = mOutput;
3383 mOutput = NULL;
3384 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3385 // must push a NULL and wait for ack
3386 mOutputSink.clear();
3387 mPipeSink.clear();
3388 mNormalSink.clear();
3389 return output;
3390}
3391
Andy Hungb17d24b2023-08-29 14:26:09 -07003392// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003393sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003394{
3395 if (mOutput == NULL) {
3396 return NULL;
3397 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003398 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003399}
3400
Andy Hung4b17e882023-07-07 13:47:37 -07003401uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003402{
3403 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3404}
3405
Andy Hung4b17e882023-07-07 13:47:37 -07003406status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003407{
3408 if (!isValidSyncEvent(event)) {
3409 return BAD_VALUE;
3410 }
3411
Andy Hungf8635b62023-08-31 16:13:39 -07003412 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003413
3414 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003415 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003416 if (event->triggerSession() == track->sessionId()) {
3417 (void) track->setSyncEvent(event);
3418 return NO_ERROR;
3419 }
3420 }
3421
3422 return NAME_NOT_FOUND;
3423}
3424
Andy Hung4b17e882023-07-07 13:47:37 -07003425bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003426{
3427 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3428}
3429
Andy Hung4b17e882023-07-07 13:47:37 -07003430void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003431 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003432{
Andy Hungfe726a62018-09-27 15:17:25 -07003433 // Miscellaneous track cleanup when removed from the active list,
3434 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003435#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003436 for (const auto& track : tracksToRemove) {
3437 if (track->isExternalTrack()) {
3438 // to track the speaker usage
3439 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003440 }
3441 }
Andy Hungfe726a62018-09-27 15:17:25 -07003442#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003443}
3444
Andy Hung4b17e882023-07-07 13:47:37 -07003445void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003446{
3447 if (!mMasterMute) {
3448 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003449 if (mOutDeviceTypeAddrs.empty()) {
3450 ALOGD("ro.audio.silent is ignored since no output device is set");
3451 return;
3452 }
jiabinc52b1ff2019-10-31 17:20:42 -07003453 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003454 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3455 return;
3456 }
Eric Laurent81784c32012-11-19 14:55:58 -08003457 if (property_get("ro.audio.silent", value, "0") > 0) {
3458 char *endptr;
3459 unsigned long ul = strtoul(value, &endptr, 0);
3460 if (*endptr == '\0' && ul != 0) {
3461 ALOGD("Silence is golden");
3462 // The setprop command will not allow a property to be changed after
3463 // the first time it is set, so we don't have to worry about un-muting.
3464 setMasterMute_l(true);
3465 }
3466 }
3467 }
3468}
3469
3470// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003471ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003472{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003473 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003474 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003475 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003476 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003477
3478 // If an NBAIO sink is present, use it to write the normal mixer's submix
3479 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003480
Andy Hung010a1a12014-03-13 13:57:33 -07003481 const size_t count = mBytesRemaining / mFrameSize;
3482
Simon Wilson2d590962012-11-29 15:18:50 -08003483 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003484 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003485 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003486 if (screenState != mScreenState) {
3487 mScreenState = screenState;
3488 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3489 if (pipe != NULL) {
3490 pipe->setAvgFrames((mScreenState & 1) ?
3491 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3492 }
3493 }
Andy Hung010a1a12014-03-13 13:57:33 -07003494 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003495 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003496
Eric Laurent81784c32012-11-19 14:55:58 -08003497 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003498 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003499
Andy Hung8946a282018-04-19 20:04:56 -07003500#ifdef TEE_SINK
3501 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3502#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003503 } else {
3504 bytesWritten = framesWritten;
3505 }
3506 // otherwise use the HAL / AudioStreamOut directly
3507 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003508 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003509
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003511 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3512 mWriteAckSequence += 2;
3513 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003515 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003517 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003518 // FIXME We should have an implementation of timestamps for direct output threads.
3519 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003520 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003521 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003522
Eric Laurentbfb1b832013-01-07 09:53:42 -08003523 if (mUseAsyncWrite &&
3524 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3525 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003526 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003527 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003528 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529 }
Eric Laurent81784c32012-11-19 14:55:58 -08003530 }
3531
Eric Laurent81784c32012-11-19 14:55:58 -08003532 mNumWrites++;
3533 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003534 if (mStandby) {
3535 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003536 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003537 mStandby = false;
3538 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003539 return bytesWritten;
3540}
3541
Andy Hungb17d24b2023-08-29 14:26:09 -07003542// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003543void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003544 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003545{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003546 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003547 if (outputSink != nullptr) {
3548 outputSink->startMelComputation(processor);
3549 }
Vlad Popab042ee62022-10-20 18:05:00 +02003550}
3551
Andy Hungb17d24b2023-08-29 14:26:09 -07003552// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003553void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003554{
3555 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003556 if (outputSink != nullptr) {
3557 outputSink->stopMelComputation();
3558 }
Vlad Popab042ee62022-10-20 18:05:00 +02003559}
3560
Andy Hung4b17e882023-07-07 13:47:37 -07003561void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003562{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003563 bool supportsDrain = false;
3564 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003565 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3566 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003567 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3568 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003569 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003570 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003572 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003573 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 }
3575}
3576
Andy Hung4b17e882023-07-07 13:47:37 -07003577void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003578{
Eric Laurent275e8e92014-11-30 15:14:47 -08003579 {
Andy Hungf8635b62023-08-31 16:13:39 -07003580 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003581 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003582 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003583 track->invalidate();
3584 }
Andy Hungdae27702016-10-31 14:01:16 -07003585 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3586 // After we exit there are no more track changes sent to BatteryNotifier
3587 // because that requires an active threadLoop.
3588 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3589 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003590 }
Eric Laurent81784c32012-11-19 14:55:58 -08003591}
3592
3593/*
3594The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003595 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003596 - mActiveSleepTimeUs from activeSleepTimeUs()
3597 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003598 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3599 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003600 - maxPeriod from frame count and sample rate (MIXER only)
3601
3602The parameters that affect these derived values are:
3603 - frame count
3604 - frame size
3605 - sample rate
3606 - device type: A2DP or not
3607 - device latency
3608 - format: PCM or not
3609 - active sleep time
3610 - idle sleep time
3611*/
3612
Andy Hung4b17e882023-07-07 13:47:37 -07003613void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003614{
Andy Hung25c2dac2014-02-27 14:56:00 -08003615 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003616 mActiveSleepTimeUs = activeSleepTimeUs();
3617 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003618
Andy Hungd58c4732023-07-20 21:31:38 -07003619 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003620
Eric Laurent42537be2016-01-08 17:16:42 -08003621 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3622 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003623 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003624 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3625 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3626 }
3627 }
Eric Laurent81784c32012-11-19 14:55:58 -08003628}
3629
Andy Hung4b17e882023-07-07 13:47:37 -07003630bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003631{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003632 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003633 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003634 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003635 size_t size = mTracks.size();
3636 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003637 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003638 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003639 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003640 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003641 }
3642 }
Eric Laurent13084622016-05-17 10:51:49 -07003643 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003644}
3645
Andy Hung4b17e882023-07-07 13:47:37 -07003646void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003647{
Andy Hungf8635b62023-08-31 16:13:39 -07003648 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003649 invalidateTracks_l(streamType);
3650}
3651
Andy Hung4b17e882023-07-07 13:47:37 -07003652void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07003653 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003654 invalidateTracks_l(portIds);
3655}
3656
Andy Hung4b17e882023-07-07 13:47:37 -07003657bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003658 bool trackMatch = false;
3659 const size_t size = mTracks.size();
3660 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003661 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003662 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3663 t->invalidate();
3664 portIds.erase(t->portId());
3665 trackMatch = true;
3666 }
3667 if (portIds.empty()) {
3668 break;
3669 }
3670 }
3671 return trackMatch;
3672}
3673
jiabinf042b9b2021-05-07 23:46:28 +00003674// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003675IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003676 audio_port_handle_t trackPortId) {
3677 for (size_t i = 0; i < mTracks.size(); i++) {
3678 if (mTracks[i]->portId() == trackPortId) {
3679 return mTracks[i].get();
3680 }
3681 }
3682 return nullptr;
3683}
3684
Andy Hung4b17e882023-07-07 13:47:37 -07003685status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003686{
Glenn Kastend848eb42016-03-08 13:42:11 -08003687 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003688 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003689 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003690
Andy Hungd3639922022-04-28 18:00:49 -07003691 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003692 if (!audio_is_global_session(session)) {
3693 // player sessions on a spatializer output will use a dedicated input buffer and
3694 // will either output multi channel to mEffectBuffer if the track is spatilaized
3695 // or stereo to mPostSpatializerBuffer if not spatialized.
3696 uint32_t channelMask;
3697 bool isSessionSpatialized =
3698 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3699 if (isSessionSpatialized) {
3700 channelMask = mMixerChannelMask;
3701 } else {
3702 channelMask = mChannelMask;
3703 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003704 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003705 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003706 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003707 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003708 &halInBuffer);
3709 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003710
Andy Hung7535ed92023-07-17 17:05:00 -07003711 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003712 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3713 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3714 &halOutBuffer);
3715 if (result != OK) return result;
3716
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003717 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003718
Mikhail Naganov022b9952017-01-04 16:36:51 -08003719 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3720 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003721 } else {
3722 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3723 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3724 // mPostSpatializerBuffer as output buffer
3725 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003726 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003727 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3728 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003729 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003730 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3731 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003732
Eric Laurentb62d0362021-10-26 17:40:18 +02003733 if (session == AUDIO_SESSION_DEVICE) {
3734 halInBuffer = halOutBuffer;
3735 }
3736 }
3737 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003738 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003739 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3740 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3741 &halInBuffer);
3742 if (result != OK) return result;
3743 halOutBuffer = halInBuffer;
3744 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3745 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003746 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003747 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003748 // Only one effect chain can be present in direct output thread and it uses
3749 // the sink buffer as input
3750 if (mType != DIRECT) {
3751 size_t numSamples = mNormalFrameCount
3752 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3753 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003754 const status_t allocateStatus =
3755 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003756 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003757 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003758 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003759
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003760 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003761 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3762 buffer, session);
3763 }
3764 }
3765 }
3766
3767 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003768 // Attach all tracks with same session ID to this chain.
3769 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003770 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003771 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003772 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3773 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003774 track->setMainBuffer(buffer);
3775 chain->incTrackCnt();
3776 }
3777 }
3778
3779 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003780 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003781 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003782 ALOGV("addEffectChain_l() activating track %p on session %d",
3783 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003784 chain->incActiveTrackCnt();
3785 }
3786 }
3787 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003788
Eric Laurentaaa44472014-09-12 17:41:50 -07003789 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003790 chain->setInBuffer(halInBuffer);
3791 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003792 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3793 // chains list in order to be processed last as it contains output device effects.
3794 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3795 // processing effects specific to an output stream before effects applied to all streams
3796 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003797 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3798 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003799 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003800 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003801 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003802 // Effect chain for other sessions are inserted at beginning of effect
3803 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003804 // sessions is not important.
3805 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003806 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3807 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003808 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003809 size_t size = mEffectChains.size();
3810 size_t i = 0;
3811 for (i = 0; i < size; i++) {
3812 if (mEffectChains[i]->sessionId() < session) {
3813 break;
3814 }
3815 }
3816 mEffectChains.insertAt(chain, i);
3817 checkSuspendOnAddEffectChain_l(chain);
3818
3819 return NO_ERROR;
3820}
3821
Andy Hung4b17e882023-07-07 13:47:37 -07003822size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003823{
Glenn Kastend848eb42016-03-08 13:42:11 -08003824 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003825
3826 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3827
3828 for (size_t i = 0; i < mEffectChains.size(); i++) {
3829 if (chain == mEffectChains[i]) {
3830 mEffectChains.removeAt(i);
3831 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003832 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003833 if (session == track->sessionId()) {
3834 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3835 chain.get(), session);
3836 chain->decActiveTrackCnt();
3837 }
3838 }
3839
3840 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003841 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003842 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003843 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003844 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003845 chain->decTrackCnt();
3846 }
3847 }
3848 break;
3849 }
3850 }
3851 return mEffectChains.size();
3852}
3853
Andy Hung4b17e882023-07-07 13:47:37 -07003854status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003855 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003856{
Andy Hungf8635b62023-08-31 16:13:39 -07003857 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003858 return attachAuxEffect_l(track, EffectId);
3859}
3860
Andy Hung4b17e882023-07-07 13:47:37 -07003861status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003862 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003863{
3864 status_t status = NO_ERROR;
3865
3866 if (EffectId == 0) {
3867 track->setAuxBuffer(0, NULL);
3868 } else {
3869 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003870 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003871 if (effect != 0) {
3872 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3873 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3874 } else {
3875 status = INVALID_OPERATION;
3876 }
3877 } else {
3878 status = BAD_VALUE;
3879 }
3880 }
3881 return status;
3882}
3883
Andy Hung4b17e882023-07-07 13:47:37 -07003884void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003885{
3886 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003887 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003888 if (track->auxEffectId() == effectId) {
3889 attachAuxEffect_l(track, 0);
3890 }
3891 }
3892}
3893
Andy Hung4b17e882023-07-07 13:47:37 -07003894bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003895NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003896{
Andy Hung78d8d952023-05-30 18:10:23 -07003897 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003898
Andy Hung45a38f22023-10-03 10:49:34 -07003899 if (mType == SPATIALIZER) {
3900 const pid_t tid = getTid();
3901 if (tid == -1) { // odd: we are here, we must be a running thread.
3902 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3903 } else {
3904 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3905 if (priorityBoost > 0) {
3906 stream()->setHalThreadPriority(priorityBoost);
3907 }
3908 }
3909 }
3910
Andy Hung11e74242023-06-26 19:20:57 -07003911 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003912
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003913 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003914 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003915
3916 // MIXER
3917 nsecs_t lastWarning = 0;
3918
3919 // DUPLICATING
3920 // FIXME could this be made local to while loop?
3921 writeFrames = 0;
3922
3923 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003924 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003925
Andy Hungd3639922022-04-28 18:00:49 -07003926 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003927 sleepTimeShift = 0;
3928 }
3929
3930 CpuStats cpuStats;
3931 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3932
3933 acquireWakeLock();
3934
Glenn Kasteneef598c2017-04-03 14:41:13 -07003935 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3936 // thread associated with this PlaybackThread.
3937 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3938 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003939 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3940 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003941 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003942 const char *logString = NULL;
3943
rago1bb90822017-05-02 18:31:48 -07003944 // Estimated time for next buffer to be written to hal. This is used only on
3945 // suspended mode (for now) to help schedule the wait time until next iteration.
3946 nsecs_t timeLoopNextNs = 0;
3947
Eric Laurent664539d2013-09-23 18:24:31 -07003948 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003949
Andy Hung2dbffc22018-08-08 18:50:41 -07003950 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003951
Eric Laurentb3f315a2021-07-13 15:09:05 +02003952 sendCheckOutputStageEffectsEvent();
3953
Andy Hung446f4df2019-02-21 12:26:41 -08003954 // loopCount is used for statistics and diagnostics.
3955 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003956 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003957 // Log merge requests are performed during AudioFlinger binder transactions, but
3958 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07003959 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003960
Eric Laurent81784c32012-11-19 14:55:58 -08003961 cpuStats.sample(myName);
3962
Andy Hung116bc262023-06-20 18:56:17 -07003963 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003964 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003965 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07003966 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003967
Andy Hung2dbffc22018-08-08 18:50:41 -07003968 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3969 //
Andy Hungb17d24b2023-08-29 14:26:09 -07003970 // Note: we access outDeviceTypes() outside of mutex().
jiabinc52b1ff2019-10-31 17:20:42 -07003971 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003972 // Here, we try for the AF lock, but do not block on it as the latency
3973 // is more informational.
Andy Hung85a07452023-08-28 18:36:53 -07003974 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd25fe392023-07-13 16:52:46 -07003975 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003976 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003977 status_t status = INVALID_OPERATION;
3978 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07003979 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07003980 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003981 && swPatches.size() > 0) {
3982 status = swPatches[0].getLatencyMs_l(&latencyMs);
3983 downstreamPatchHandle = swPatches[0].getPatchHandle();
3984 }
3985 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003986 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003987 lastDownstreamPatchHandle = downstreamPatchHandle;
3988 }
3989 if (status == OK) {
3990 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003991 // latency of 5 seconds).
3992 const double minLatency = 0., maxLatency = 5000.;
3993 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003994 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003995 } else {
3996 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003997 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003998 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003999 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004000 }
Andy Hung7535ed92023-07-17 17:05:00 -07004001 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004002 }
4003 } else {
4004 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4005 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004006 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004007 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4008 }
4009 }
4010
Eric Laurentb3f315a2021-07-13 15:09:05 +02004011 if (mCheckOutputStageEffects.exchange(false)) {
4012 checkOutputStageEffects();
4013 }
4014
Vlad Popa7e81cea2023-01-19 16:34:16 +01004015 MetadataUpdate metadataUpdate;
Andy Hungb17d24b2023-08-29 14:26:09 -07004016 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004017
Andy Hungb17d24b2023-08-29 14:26:09 -07004018 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004019
Eric Laurent021cf962014-05-13 10:18:14 -07004020 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004021 if (mCheckOutputStageEffects.load()) {
4022 continue;
4023 }
Eric Laurent10351942014-05-08 18:49:52 -07004024
Andy Hungb17d24b2023-08-29 14:26:09 -07004025 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004026 if (logString != NULL) {
4027 mNBLogWriter->logTimestamp();
4028 mNBLogWriter->log(logString);
4029 logString = NULL;
4030 }
4031
Dean Wheatley12473e92021-03-18 23:00:55 +11004032 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004033
Eric Laurent81784c32012-11-19 14:55:58 -08004034 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004035 if (mSignalPending) {
4036 // A signal was raised while we were unlocked
4037 mSignalPending = false;
4038 } else if (waitingAsyncCallback_l()) {
4039 if (exitPending()) {
4040 break;
4041 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004042 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004043 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004044 releaseWakeLock_l();
4045 released = true;
4046 }
Andy Hung10cbff12017-02-21 17:30:14 -08004047
4048 const int64_t waitNs = computeWaitTimeNs_l();
4049 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungb17d24b2023-08-29 14:26:09 -07004050 std::cv_status cvstatus =
4051 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4052 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004053 mSignalPending = true; // if timeout recheck everything
4054 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004055 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004056 if (released) {
4057 acquireWakeLock_l();
4058 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004059 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4060 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004061
4062 continue;
4063 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004064 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065 isSuspended()) {
4066 // put audio hardware into standby after short delay
4067 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004068
4069 threadLoop_standby();
4070
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004071 // This is where we go into standby
4072 if (!mStandby) {
4073 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004074 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004075 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004076 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004077 }
Andy Hungd0979812019-02-21 15:51:44 -08004078 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004079 }
4080
Eric Tan39ec8d62018-07-24 09:49:29 -07004081 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004082 // we're about to wait, flush the binder command buffer
4083 IPCThreadState::self()->flushCommands();
4084
4085 clearOutputTracks();
4086
4087 if (exitPending()) {
4088 break;
4089 }
4090
4091 releaseWakeLock_l();
4092 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004093 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -07004094 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004095 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004096 acquireWakeLock_l();
4097
4098 mMixerStatus = MIXER_IDLE;
4099 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4100 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004101 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004102 checkSilentMode_l();
4103
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004104 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4105 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004106 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004107 sleepTimeShift = 0;
4108 }
4109
4110 continue;
4111 }
4112 }
Eric Laurent81784c32012-11-19 14:55:58 -08004113 // mMixerStatusIgnoringFastTracks is also updated internally
4114 mMixerStatus = prepareTracks_l(&tracksToRemove);
4115
Andy Hungdae27702016-10-31 14:01:16 -07004116 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004117
Vlad Popa7e81cea2023-01-19 16:34:16 +01004118 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004119
Eric Laurent81784c32012-11-19 14:55:58 -08004120 // prevent any changes in effect chain list and in each effect chain
4121 // during mixing and effect process as the audio buffers could be deleted
4122 // or modified if an effect is created or deleted
4123 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004124
4125 // Determine which session to pick up haptic data.
4126 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004127 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004128 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004129 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004130 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004131 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004132 if (effectChain != nullptr
4133 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004134 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004135 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004136 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004137 break;
4138 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004139 if (activeHapticSessionId == AUDIO_SESSION_NONE
4140 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004141 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004142 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004143 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004144 }
4145 }
4146 }
4147
Andy Hungc1646382019-04-30 16:12:10 -07004148 // Acquire a local copy of active tracks with lock (release w/o lock).
4149 //
4150 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4151 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4152 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4153 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004154
4155 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004156
Jiabin Huangfb476842022-12-06 03:18:10 +00004157 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004158 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004159 }
4160
Eric Laurent19952e12023-04-20 10:08:29 +02004161 // signal actual start of output stream when the render position reported by the kernel
4162 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004163 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4164 && (mKernelPositionOnStandby
4165 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004166 mHalStarted = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07004167 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004168 }
Andy Hungb17d24b2023-08-29 14:26:09 -07004169 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004170
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 if (mBytesRemaining == 0) {
4172 mCurrentWriteLength = 0;
4173 if (mMixerStatus == MIXER_TRACKS_READY) {
4174 // threadLoop_mix() sets mCurrentWriteLength
4175 threadLoop_mix();
4176 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4177 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004178 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004179 // must be written to HAL
4180 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004181 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004182 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004183
4184 // Tally underrun frames as we are inserting 0s here.
4185 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004186 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004187 && !track->isStopped()
4188 && !track->isPaused()
4189 && !track->isTerminated()) {
4190 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4191 __func__, track->id(), track->getTrackStateAsString(),
4192 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004193 track->audioTrackServerProxy()->tallyUnderrunFrames(
4194 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004195 }
4196 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004197 }
4198 }
Andy Hung98ef9782014-03-04 14:46:50 -08004199 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004200 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004201 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004202 // or mSinkBuffer (if there are no effects and there is no data already copied to
4203 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004204 //
4205 // This is done pre-effects computation; if effects change to
4206 // support higher precision, this needs to move.
4207 //
4208 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004209 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004210 uint32_t mixerChannelCount = mEffectBufferValid ?
4211 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004212 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004213 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4214 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4215
David Li88ee0902022-06-22 10:01:21 +08004216 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4217 // do these processes after effects are applied.
4218 if (!mEffectBufferValid) {
4219 // mono blend occurs for mixer threads only (not direct or offloaded)
4220 // and is handled here if we're going directly to the sink.
4221 if (requireMonoBlend()) {
4222 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4223 mNormalFrameCount, true /*limit*/);
4224 }
Andy Hung2ddee192015-12-18 17:34:44 -08004225
David Li88ee0902022-06-22 10:01:21 +08004226 if (!hasFastMixer()) {
4227 // Balance must take effect after mono conversion.
4228 // We do it here if there is no FastMixer.
4229 // mBalance detects zero balance within the class for speed
4230 // (not needed here).
4231 mBalance.setBalance(mMasterBalance.load());
4232 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4233 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004234 }
4235
Andy Hung98ef9782014-03-04 14:46:50 -08004236 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004237 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004238
4239 // If we're going directly to the sink and there are haptic channels,
4240 // we should adjust channels as the sample data is partially interleaved
4241 // in this case.
4242 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4243 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4244 mChannelCount + mHapticChannelCount,
4245 audio_bytes_per_sample(format),
4246 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4247 }
Andy Hung98ef9782014-03-04 14:46:50 -08004248 }
4249
Eric Laurentbfb1b832013-01-07 09:53:42 -08004250 mBytesRemaining = mCurrentWriteLength;
4251 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004252 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4253 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4254 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4255 mBytesWritten += mBytesRemaining;
4256 mFramesWritten += framesRemaining;
4257 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004258 mBytesRemaining = 0;
4259 }
Eric Laurent81784c32012-11-19 14:55:58 -08004260
Eric Laurentbfb1b832013-01-07 09:53:42 -08004261 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004262 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004263 for (size_t i = 0; i < effectChains.size(); i ++) {
4264 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004265 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004266 if (activeHapticSessionId != AUDIO_SESSION_NONE
4267 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004268 // Haptic data is active in this case, copy it directly from
4269 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004270 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4271 audio_channel_count_from_out_mask(mMixerChannelMask) :
4272 mChannelCount;
4273 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4274 hapticSessionChannelCount = mChannelCount;
4275 }
4276
jiabin47affe52019-04-04 18:02:07 -07004277 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004278 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004279 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004280 memcpy_by_audio_format(
4281 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004282 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004283 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004284 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004286 }
Eric Laurent81784c32012-11-19 14:55:58 -08004287 }
4288 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004289 // Process effect chains for offloaded thread even if no audio
4290 // was read from audio track: process only updates effect state
4291 // and thus does have to be synchronized with audio writes but may have
4292 // to be called while waiting for async write callback
4293 if (mType == OFFLOAD) {
4294 for (size_t i = 0; i < effectChains.size(); i ++) {
4295 effectChains[i]->process_l();
4296 }
4297 }
Eric Laurent81784c32012-11-19 14:55:58 -08004298
Andy Hung98ef9782014-03-04 14:46:50 -08004299 // Only if the Effects buffer is enabled and there is data in the
4300 // Effects buffer (buffer valid), we need to
4301 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004302 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004303 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004304 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004305 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004306 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004307 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004308 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004309 }
4310
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004311 if (!hasFastMixer()) {
4312 // Balance must take effect after mono conversion.
4313 // We do it here if there is no FastMixer.
4314 // mBalance detects zero balance within the class for speed (not needed here).
4315 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004316 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004317 }
4318
Eric Laurentb62d0362021-10-26 17:40:18 +02004319 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4320 // mPostSpatializerBuffer if the haptics track is spatialized.
4321 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4322 // For other thread types, the haptics channels are already in mEffectBuffer.
4323 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4324 const size_t srcBufferSize = mNormalFrameCount *
4325 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4326 mEffectBufferFormat);
4327 const size_t dstBufferSize = mNormalFrameCount
4328 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4329
4330 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4331 mEffectBufferFormat,
4332 (uint8_t*)mEffectBuffer + srcBufferSize,
4333 mEffectBufferFormat,
4334 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004335 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004336 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4337 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4338 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4339 // Clamp PCM float values more than this distance from 0 to insulate
4340 // a HAL which doesn't handle NaN correctly.
4341 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4342 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4343 static_cast<const float*>(effectBuffer),
4344 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4345 } else {
4346 memcpy_by_audio_format(mSinkBuffer, mFormat,
4347 effectBuffer, mEffectBufferFormat, framesToCopy);
4348 }
jiabin245cdd92018-12-07 17:55:15 -08004349 // The sample data is partially interleaved when haptic channels exist,
4350 // we need to adjust channels here.
4351 if (mHapticChannelCount > 0) {
4352 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4353 mChannelCount + mHapticChannelCount,
4354 audio_bytes_per_sample(mFormat),
4355 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4356 }
Andy Hung98ef9782014-03-04 14:46:50 -08004357 }
4358
Eric Laurent81784c32012-11-19 14:55:58 -08004359 // enable changes in effect chain
4360 unlockEffectChains(effectChains);
4361
Vlad Popafce10862023-02-03 10:37:07 +01004362 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004363 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004364 metadataUpdate.playbackMetadataUpdate);
4365 }
4366
Eric Laurentbfb1b832013-01-07 09:53:42 -08004367 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004368 // mSleepTimeUs == 0 means we must write to audio hardware
4369 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004370 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004371 // writePeriodNs is updated >= 0 when ret > 0.
4372 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004373 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004374 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004375 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004376 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004377 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004378 if (ret < 0) {
4379 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004380 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004381 mBytesWritten += ret;
4382 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004383 const int64_t frames = ret / mFrameSize;
4384 mFramesWritten += frames;
4385
4386 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4387 // process information relating to write time.
4388 if (audio_has_proportional_frames(mFormat)) {
4389 // we are in a continuous mixing cycle
4390 if (mMixerStatus == MIXER_TRACKS_READY &&
4391 loopCount == lastLoopCountWritten + 1) {
4392
4393 const double jitterMs =
4394 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4395 {frames, writePeriodNs},
4396 {0, 0} /* lastTimestamp */, mSampleRate);
4397 const double processMs =
4398 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4399
Andy Hungf8635b62023-08-31 16:13:39 -07004400 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004401 mIoJitterMs.add(jitterMs);
4402 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004403
4404 if (mPipeSink.get() != nullptr) {
4405 // Using the Monopipe availableToWrite, we estimate the current
4406 // buffer size.
4407 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4408 const ssize_t
4409 availableToWrite = mPipeSink->availableToWrite();
4410 const size_t pipeFrames = monoPipe->maxFrames();
4411 const size_t
4412 remainingFrames = pipeFrames - max(availableToWrite, 0);
4413 mMonopipePipeDepthStats.add(remainingFrames);
4414 }
Andy Hung446f4df2019-02-21 12:26:41 -08004415 }
4416
4417 // write blocked detection
4418 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004419 if ((mType == MIXER || mType == SPATIALIZER)
4420 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004421 mNumDelayedWrites++;
4422 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4423 ATRACE_NAME("underrun");
4424 ALOGW("write blocked for %lld msecs, "
4425 "%d delayed writes, thread %d",
4426 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4427 mNumDelayedWrites, mId);
4428 lastWarning = lastIoEndNs;
4429 }
4430 }
4431 }
4432 // update timing info.
4433 mLastIoBeginNs = lastIoBeginNs;
4434 mLastIoEndNs = lastIoEndNs;
4435 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004436 }
4437 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4438 (mMixerStatus == MIXER_DRAIN_ALL)) {
4439 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004440 }
Andy Hungd3639922022-04-28 18:00:49 -07004441 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004442
4443 if (mThreadThrottle
4444 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004445 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004446 // Limit MixerThread data processing to no more than twice the
4447 // expected processing rate.
4448 //
4449 // This helps prevent underruns with NuPlayer and other applications
4450 // which may set up buffers that are close to the minimum size, or use
4451 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4452 //
4453 // The throttle smooths out sudden large data drains from the device,
4454 // e.g. when it comes out of standby, which often causes problems with
4455 // (1) mixer threads without a fast mixer (which has its own warm-up)
4456 // (2) minimum buffer sized tracks (even if the track is full,
4457 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004458 //
4459 // Total time spent in last processing cycle equals time spent in
4460 // 1. threadLoop_write, as well as time spent in
4461 // 2. threadLoop_mix (significant for heavy mixing, especially
4462 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004463
Andy Hung446f4df2019-02-21 12:26:41 -08004464 // it's OK if deltaMs is an overestimate.
4465
4466 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004467
Ivan Lozanoea04d392017-11-07 14:37:07 -08004468 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004469 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004470 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004471
Andy Hung08fb1742015-05-31 23:22:10 -07004472 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004473 // notify of throttle start on verbose log
4474 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4475 "mixer(%p) throttle begin:"
4476 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004477 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004478 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004479 // Throttle must be attributed to the previous mixer loop's write time
4480 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004481 // This also ensures proper timing statistics.
4482 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004483 } else {
4484 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4485 if (diff > 0) {
4486 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004487 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004488 ALOGD_IF(!isSingleDeviceType(
4489 outDeviceTypes(), audio_is_a2dp_out_device) &&
4490 !isSingleDeviceType(
4491 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004492 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004493 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4494 }
Andy Hung08fb1742015-05-31 23:22:10 -07004495 }
4496 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004497 }
Eric Laurent81784c32012-11-19 14:55:58 -08004498
Eric Laurentbfb1b832013-01-07 09:53:42 -08004499 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004500 ATRACE_BEGIN("sleep");
Andy Hungb17d24b2023-08-29 14:26:09 -07004501 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004502 // suspended requires accurate metering of sleep time.
4503 if (isSuspended()) {
4504 // advance by expected sleepTime
4505 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4506 const nsecs_t nowNs = systemTime();
4507
4508 // compute expected next time vs current time.
4509 // (negative deltas are treated as delays).
4510 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4511 if (deltaNs < -kMaxNextBufferDelayNs) {
4512 // Delays longer than the max allowed trigger a reset.
4513 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4514 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4515 timeLoopNextNs = nowNs + deltaNs;
4516 } else if (deltaNs < 0) {
4517 // Delays within the max delay allowed: zero the delta/sleepTime
4518 // to help the system catch up in the next iteration(s)
4519 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4520 deltaNs = 0;
4521 }
4522 // update sleep time (which is >= 0)
4523 mSleepTimeUs = deltaNs / 1000;
4524 }
Eric Laurente93cc032016-05-05 10:15:10 -07004525 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004526 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004527 }
Glenn Kastene7754022014-10-31 12:11:26 -07004528 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004529 }
Eric Laurent81784c32012-11-19 14:55:58 -08004530 }
4531
4532 // Finally let go of removed track(s), without the lock held
4533 // since we can't guarantee the destructors won't acquire that
4534 // same lock. This will also mutate and push a new fast mixer state.
4535 threadLoop_removeTracks(tracksToRemove);
4536 tracksToRemove.clear();
4537
4538 // FIXME I don't understand the need for this here;
4539 // it was in the original code but maybe the
4540 // assignment in saveOutputTracks() makes this unnecessary?
4541 clearOutputTracks();
4542
4543 // Effect chains will be actually deleted here if they were removed from
4544 // mEffectChains list during mixing or effects processing
4545 effectChains.clear();
4546
4547 // FIXME Note that the above .clear() is no longer necessary since effectChains
4548 // is now local to this block, but will keep it for now (at least until merge done).
4549 }
4550
Eric Laurentbfb1b832013-01-07 09:53:42 -08004551 threadLoop_exit();
4552
Eric Laurentcf817a22014-08-04 20:36:31 -07004553 if (!mStandby) {
4554 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004555 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004556 }
4557
4558 releaseWakeLock();
4559
4560 ALOGV("Thread %p type %d exiting", this, mType);
4561 return false;
4562}
4563
Andy Hung4b17e882023-07-07 13:47:37 -07004564void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004565{
Dean Wheatley12473e92021-03-18 23:00:55 +11004566 if (mStandby) {
4567 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4568 return;
4569 } else if (mHwPaused) {
4570 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4571 return;
4572 }
4573
4574 // Gather the framesReleased counters for all active tracks,
4575 // and associate with the sink frames written out. We need
4576 // this to convert the sink timestamp to the track timestamp.
4577 bool kernelLocationUpdate = false;
4578 ExtendedTimestamp timestamp; // use private copy to fetch
4579
4580 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4581 // HAL may be draining some small duration buffered data for fade out.
4582 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4583 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4584 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4585 mSampleRate);
4586
4587 if (isTimestampCorrectionEnabled()) {
4588 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4589 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4590 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4591 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4592 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4593 = correctedTimestamp.mFrames;
4594 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4595 = correctedTimestamp.mTimeNs;
4596 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4597 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4598 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4599
4600 // Note: Downstream latency only added if timestamp correction enabled.
4601 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4602 const int64_t newPosition =
4603 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4604 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4605 // prevent retrograde
4606 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4607 newPosition,
4608 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4609 - mSuspendedFrames));
4610 }
4611 }
4612
4613 // We always fetch the timestamp here because often the downstream
4614 // sink will block while writing.
4615
4616 // We keep track of the last valid kernel position in case we are in underrun
4617 // and the normal mixer period is the same as the fast mixer period, or there
4618 // is some error from the HAL.
4619 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4620 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4621 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4622 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4623 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4624
4625 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4626 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4627 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4628 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4629 }
4630
4631 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4632 kernelLocationUpdate = true;
4633 } else {
4634 ALOGVV("getTimestamp error - no valid kernel position");
4635 }
4636
4637 // copy over kernel info
4638 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4639 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4640 + mSuspendedFrames; // add frames discarded when suspended
4641 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4642 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4643 } else {
4644 mTimestampVerifier.error();
4645 }
4646
4647 // mFramesWritten for non-offloaded tracks are contiguous
4648 // even after standby() is called. This is useful for the track frame
4649 // to sink frame mapping.
4650 bool serverLocationUpdate = false;
4651 if (mFramesWritten != mLastFramesWritten) {
4652 serverLocationUpdate = true;
4653 mLastFramesWritten = mFramesWritten;
4654 }
4655 // Only update timestamps if there is a meaningful change.
4656 // Either the kernel timestamp must be valid or we have written something.
4657 if (kernelLocationUpdate || serverLocationUpdate) {
4658 if (serverLocationUpdate) {
4659 // use the time before we called the HAL write - it is a bit more accurate
4660 // to when the server last read data than the current time here.
4661 //
4662 // If we haven't written anything, mLastIoBeginNs will be -1
4663 // and we use systemTime().
4664 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4665 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4666 ? systemTime() : mLastIoBeginNs;
4667 }
4668
Andy Hung11e74242023-06-26 19:20:57 -07004669 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004670 if (!t->isFastTrack()) {
4671 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004672 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004673 mFramesWritten,
4674 mSampleRate,
4675 mTimestamp);
4676 }
4677 }
4678 }
4679
4680 if (audio_has_proportional_frames(mFormat)) {
4681 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4682 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4683 mLatencyMs.add(latencyMs);
4684 }
4685 }
4686#if 0
4687 // logFormat example
4688 if (z % 100 == 0) {
4689 timespec ts;
4690 clock_gettime(CLOCK_MONOTONIC, &ts);
4691 LOGT("This is an integer %d, this is a float %f, this is my "
4692 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4693 LOGT("A deceptive null-terminated string %\0");
4694 }
4695 ++z;
4696#endif
4697}
4698
Andy Hungb17d24b2023-08-29 14:26:09 -07004699// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07004700void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungb17d24b2023-08-29 14:26:09 -07004701NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004702{
Andy Hungfe726a62018-09-27 15:17:25 -07004703 for (const auto& track : tracksToRemove) {
4704 mActiveTracks.remove(track);
4705 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004706 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004707 if (chain != 0) {
4708 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4709 __func__, track->id(), chain.get(), track->sessionId());
4710 chain->decActiveTrackCnt();
4711 }
4712 // If an external client track, inform APM we're no longer active, and remove if needed.
4713 // We do this under lock so that the state is consistent if the Track is destroyed.
4714 if (track->isExternalTrack()) {
4715 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004716 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004717 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004718 }
4719 }
Andy Hungfe726a62018-09-27 15:17:25 -07004720 if (track->isTerminated()) {
4721 // remove from our tracks vector
4722 removeTrack_l(track);
4723 }
jiabineb3bda02020-06-30 14:07:03 -07004724 if (mHapticChannelCount > 0 &&
4725 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4726 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004727 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004728 // Unlock due to VibratorService will lock for this call and will
4729 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004730 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungb17d24b2023-08-29 14:26:09 -07004731 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004732
4733 // When the track is stop, set the haptic intensity as MUTE
4734 // for the HapticGenerator effect.
4735 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004736 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004737 }
jiabin245cdd92018-12-07 17:55:15 -08004738 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004739 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004740}
Eric Laurent81784c32012-11-19 14:55:58 -08004741
Andy Hung4b17e882023-07-07 13:47:37 -07004742status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004743{
4744 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004745 ExtendedTimestamp ets;
4746 status_t status = mNormalSink->getTimestamp(ets);
4747 if (status == NO_ERROR) {
4748 status = ets.getBestTimestamp(&timestamp);
4749 }
4750 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004751 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004752 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004753 collectTimestamps_l();
4754 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4755 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004756 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004757 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4758 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4759 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4760 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4761 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004762 }
4763 return INVALID_OPERATION;
4764}
Eric Laurent1c333e22014-05-20 10:48:17 -07004765
Eric Laurenteab90452019-06-24 15:17:46 -07004766// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4767// still applied by the mixer.
4768// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4769// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4770// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004771status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004772{
4773 status_t result = NO_ERROR;
4774 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4775 if (*volume != mLeftVolFloat) {
4776 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004777 // HAL can return INVALID_OPERATION if operation is not supported.
4778 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004779 "Error when setting output stream volume: %d", result);
4780 if (result == NO_ERROR) {
4781 mLeftVolFloat = *volume;
4782 }
4783 }
4784 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4785 // remove stream volume contribution from software volume.
4786 if (mLeftVolFloat == *volume) {
4787 *volume = 1.0f;
4788 }
4789 }
4790 return result;
4791}
4792
Andy Hung4b17e882023-07-07 13:47:37 -07004793status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004794 audio_patch_handle_t *handle)
4795{
Andy Hungf60abce2016-08-26 11:37:54 -07004796 status_t status;
4797 if (property_get_bool("af.patch_park", false /* default_value */)) {
4798 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4799 // or if HAL does not properly lock against access.
4800 AutoPark<FastMixer> park(mFastMixer);
4801 status = PlaybackThread::createAudioPatch_l(patch, handle);
4802 } else {
4803 status = PlaybackThread::createAudioPatch_l(patch, handle);
4804 }
Eric Laurentb0463942022-12-20 16:31:10 +01004805
4806 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004807 return status;
4808}
4809
Andy Hung4b17e882023-07-07 13:47:37 -07004810status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004811 audio_patch_handle_t *handle)
4812{
4813 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004814
4815 // store new device and send to effects
4816 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004817 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004818 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004819 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4820 && !mOutput->audioHwDev->supportsAudioPatches(),
4821 "Enumerated device type(%#x) must not be used "
4822 "as it does not support audio patches",
4823 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004824 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004825 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4826 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004827 }
4828
François Gaffie0c280aa2018-07-25 10:02:15 +02004829 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004830#ifdef ADD_BATTERY_DATA
4831 // when changing the audio output device, call addBatteryData to notify
4832 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004833 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004834 uint32_t params = 0;
4835 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004836 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004837 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004838 }
4839
Eric Laurent054d9d32015-04-24 08:48:48 -07004840 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004841 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004842 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4843 }
4844
4845 if (params != 0) {
4846 addBatteryData(params);
4847 }
4848 }
4849#endif
4850
4851 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004852 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004853 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004854
jiabinc52b1ff2019-10-31 17:20:42 -07004855 // mPatch.num_sinks is not set when the thread is created so that
4856 // the first patch creation triggers an ioConfigChanged callback
4857 bool configChanged = (mPatch.num_sinks == 0) ||
4858 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004859 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004860 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004861 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004862
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004863 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004864 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4865 status = hwDevice->createAudioPatch(patch->num_sources,
4866 patch->sources,
4867 patch->num_sinks,
4868 patch->sinks,
4869 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004870 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004871 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004872 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004873 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004874 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004875
4876 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004877 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004878 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004879 // also dispatch to active AudioTracks for MediaMetrics
4880 for (const auto &track : mActiveTracks) {
4881 track->logEndInterval();
4882 track->logBeginInterval(patchSinksAsString);
4883 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004884
Eric Laurente8726fe2015-06-26 09:39:24 -07004885 if (configChanged) {
4886 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4887 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004888 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004889 mActiveTracks.setHasChanged();
4890
Eric Laurent1c333e22014-05-20 10:48:17 -07004891 return status;
4892}
4893
Andy Hung4b17e882023-07-07 13:47:37 -07004894status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004895{
Andy Hungf60abce2016-08-26 11:37:54 -07004896 status_t status;
4897 if (property_get_bool("af.patch_park", false /* default_value */)) {
4898 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4899 // or if HAL does not properly lock against access.
4900 AutoPark<FastMixer> park(mFastMixer);
4901 status = PlaybackThread::releaseAudioPatch_l(handle);
4902 } else {
4903 status = PlaybackThread::releaseAudioPatch_l(handle);
4904 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004905 return status;
4906}
4907
Andy Hung4b17e882023-07-07 13:47:37 -07004908status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004909{
4910 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004911
jiabinc52b1ff2019-10-31 17:20:42 -07004912 mPatch = audio_patch{};
4913 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004914
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004915 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004916 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4917 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004918 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004919 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004920 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004921 // Force meteadata update after a route change
4922 mActiveTracks.setHasChanged();
4923
Eric Laurent1c333e22014-05-20 10:48:17 -07004924 return status;
4925}
4926
Andy Hung4b17e882023-07-07 13:47:37 -07004927void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004928{
Andy Hungf8635b62023-08-31 16:13:39 -07004929 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004930 mTracks.add(track);
4931}
4932
Andy Hung4b17e882023-07-07 13:47:37 -07004933void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004934{
Andy Hungf8635b62023-08-31 16:13:39 -07004935 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004936 destroyTrack_l(track);
4937}
4938
Andy Hung4b17e882023-07-07 13:47:37 -07004939void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004940{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004941 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004942 config->role = AUDIO_PORT_ROLE_SOURCE;
4943 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4944 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004945 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4946 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4947 config->flags.output = mOutput->flags;
4948 }
Eric Laurent83b88082014-06-20 18:31:16 -07004949}
4950
Eric Laurent81784c32012-11-19 14:55:58 -08004951// ----------------------------------------------------------------------------
4952
Andy Hung4b17e882023-07-07 13:47:37 -07004953/* static */
4954sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07004955 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07004956 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07004957 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07004958}
4959
Andy Hung7535ed92023-07-17 17:05:00 -07004960MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004961 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07004962 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004963 // mAudioMixer below
4964 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004965 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004966 mFastMixerFutex(0),
4967 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004968 // mOutputSink below
4969 // mPipeSink below
4970 // mNormalSink below
4971{
Andy Hung7535ed92023-07-17 17:05:00 -07004972 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004973 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004974 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004975 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004976 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4977 mNormalFrameCount);
4978 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4979
Andy Hungfbfc3952015-01-15 13:33:51 -08004980 if (type == DUPLICATING) {
4981 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4982 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4983 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4984 return;
4985 }
Eric Laurent81784c32012-11-19 14:55:58 -08004986 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004987 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004988 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004989 const NBAIO_Format offers[1] = {Format_from_SR_C(
4990 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004991#if !LOG_NDEBUG
4992 ssize_t index =
4993#else
4994 (void)
4995#endif
4996 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004997 ALOG_ASSERT(index == 0);
4998
4999 // initialize fast mixer depending on configuration
5000 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005001 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005002 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005003 } else {
5004 switch (kUseFastMixer) {
5005 case FastMixer_Never:
5006 initFastMixer = false;
5007 break;
5008 case FastMixer_Always:
5009 initFastMixer = true;
5010 break;
5011 case FastMixer_Static:
5012 case FastMixer_Dynamic:
5013 initFastMixer = mFrameCount < mNormalFrameCount;
5014 break;
5015 }
5016 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5017 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5018 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
5020 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005021 audio_format_t fastMixerFormat;
5022 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5023 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5024 } else {
5025 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5026 }
5027 if (mFormat != fastMixerFormat) {
5028 // change our Sink format to accept our intermediate precision
5029 mFormat = fastMixerFormat;
5030 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005031 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005032 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5033 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5034 }
Eric Laurent81784c32012-11-19 14:55:58 -08005035
5036 // create a MonoPipe to connect our submix to FastMixer
5037 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005038
Andy Hung1258c1a2014-05-23 21:22:17 -07005039 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005040 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005041 format.mFormat = fastMixerFormat;
5042 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5043
Eric Laurent81784c32012-11-19 14:55:58 -08005044 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5045 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5046 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5047 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005048 const NBAIO_Format offersFast[1] = {format};
5049 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005050#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005051 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005052#else
5053 (void)
5054#endif
Andy Hung920f6572022-10-06 12:09:49 -07005055 monoPipe->negotiate(offersFast, std::size(offersFast),
5056 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005057 ALOG_ASSERT(index == 0);
5058 monoPipe->setAvgFrames((mScreenState & 1) ?
5059 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5060 mPipeSink = monoPipe;
5061
Eric Laurent81784c32012-11-19 14:55:58 -08005062 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005063 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005064 FastMixerStateQueue *sq = mFastMixer->sq();
5065#ifdef STATE_QUEUE_DUMP
5066 sq->setObserverDump(&mStateQueueObserverDump);
5067 sq->setMutatorDump(&mStateQueueMutatorDump);
5068#endif
5069 FastMixerState *state = sq->begin();
5070 FastTrack *fastTrack = &state->mFastTracks[0];
5071 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5072 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5073 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005074 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5075 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5076 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005077 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005078 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005079 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005080 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005081 fastTrack->mGeneration++;
5082 state->mFastTracksGen++;
5083 state->mTrackMask = 1;
5084 // fast mixer will use the HAL output sink
5085 state->mOutputSink = mOutputSink.get();
5086 state->mOutputSinkGen++;
5087 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005088 // specify sink channel mask when haptic channel mask present as it can not
5089 // be calculated directly from channel count
5090 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005091 ? AUDIO_CHANNEL_NONE
5092 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005093 state->mCommand = FastMixerState::COLD_IDLE;
5094 // already done in constructor initialization list
5095 //mFastMixerFutex = 0;
5096 state->mColdFutexAddr = &mFastMixerFutex;
5097 state->mColdGen++;
5098 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005099 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005100 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005101 sq->end();
5102 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5103
Eric Tan0513b5d2018-09-17 10:32:48 -07005104 NBLog::thread_info_t info;
5105 info.id = mId;
5106 info.type = NBLog::FASTMIXER;
5107 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5108
Eric Laurent81784c32012-11-19 14:55:58 -08005109 // start the fast mixer
5110 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5111 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005112 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005113 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005114
5115#ifdef AUDIO_WATCHDOG
5116 // create and start the watchdog
5117 mAudioWatchdog = new AudioWatchdog();
5118 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5119 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5120 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005121 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005122#endif
Andy Hung8946a282018-04-19 20:04:56 -07005123 } else {
5124#ifdef TEE_SINK
5125 // Only use the MixerThread tee if there is no FastMixer.
5126 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5127 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5128#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005129 }
5130
5131 switch (kUseFastMixer) {
5132 case FastMixer_Never:
5133 case FastMixer_Dynamic:
5134 mNormalSink = mOutputSink;
5135 break;
5136 case FastMixer_Always:
5137 mNormalSink = mPipeSink;
5138 break;
5139 case FastMixer_Static:
5140 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5141 break;
5142 }
5143}
5144
Andy Hung4b17e882023-07-07 13:47:37 -07005145MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005146{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005147 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005148 FastMixerStateQueue *sq = mFastMixer->sq();
5149 FastMixerState *state = sq->begin();
5150 if (state->mCommand == FastMixerState::COLD_IDLE) {
5151 int32_t old = android_atomic_inc(&mFastMixerFutex);
5152 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005153 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005154 }
5155 }
5156 state->mCommand = FastMixerState::EXIT;
5157 sq->end();
5158 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5159 mFastMixer->join();
5160 // Though the fast mixer thread has exited, it's state queue is still valid.
5161 // We'll use that extract the final state which contains one remaining fast track
5162 // corresponding to our sub-mix.
5163 state = sq->begin();
5164 ALOG_ASSERT(state->mTrackMask == 1);
5165 FastTrack *fastTrack = &state->mFastTracks[0];
5166 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5167 delete fastTrack->mBufferProvider;
5168 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005169 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005170#ifdef AUDIO_WATCHDOG
5171 if (mAudioWatchdog != 0) {
5172 mAudioWatchdog->requestExit();
5173 mAudioWatchdog->requestExitAndWait();
5174 mAudioWatchdog.clear();
5175 }
5176#endif
5177 }
Andy Hung7535ed92023-07-17 17:05:00 -07005178 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005179 delete mAudioMixer;
5180}
5181
Andy Hung4b17e882023-07-07 13:47:37 -07005182void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005183 PlaybackThread::onFirstRef();
5184
Andy Hungf8635b62023-08-31 16:13:39 -07005185 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005186 if (mOutput != nullptr && mOutput->stream != nullptr) {
5187 status_t status = mOutput->stream->setLatencyModeCallback(this);
5188 if (status != INVALID_OPERATION) {
5189 updateHalSupportedLatencyModes_l();
5190 }
5191 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5192 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5193 mBluetoothLatencyModesEnabled.store(
5194 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5195 }
5196}
Eric Laurent81784c32012-11-19 14:55:58 -08005197
Andy Hung4b17e882023-07-07 13:47:37 -07005198uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005199{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005200 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005201 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5202 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5203 }
5204 return latency;
5205}
5206
Andy Hung4b17e882023-07-07 13:47:37 -07005207ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005208{
5209 // FIXME we should only do one push per cycle; confirm this is true
5210 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005211 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005212 FastMixerStateQueue *sq = mFastMixer->sq();
5213 FastMixerState *state = sq->begin();
5214 if (state->mCommand != FastMixerState::MIX_WRITE &&
5215 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5216 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005217
5218 // FIXME workaround for first HAL write being CPU bound on some devices
5219 ATRACE_BEGIN("write");
5220 mOutput->write((char *)mSinkBuffer, 0);
5221 ATRACE_END();
5222
Eric Laurent81784c32012-11-19 14:55:58 -08005223 int32_t old = android_atomic_inc(&mFastMixerFutex);
5224 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005225 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005226 }
5227#ifdef AUDIO_WATCHDOG
5228 if (mAudioWatchdog != 0) {
5229 mAudioWatchdog->resume();
5230 }
5231#endif
5232 }
5233 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005234#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005235 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005236 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005237#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005238 sq->end();
5239 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5240 if (kUseFastMixer == FastMixer_Dynamic) {
5241 mNormalSink = mPipeSink;
5242 }
5243 } else {
5244 sq->end(false /*didModify*/);
5245 }
5246 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005247 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005248}
5249
Andy Hung4b17e882023-07-07 13:47:37 -07005250void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005251{
5252 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005253 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005254 FastMixerStateQueue *sq = mFastMixer->sq();
5255 FastMixerState *state = sq->begin();
5256 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005257 // Report any frames trapped in the Monopipe
5258 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5259 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5260 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5261 "monoPipeWritten:%lld monoPipeLeft:%lld",
5262 (long long)mFramesWritten, (long long)mSuspendedFrames,
5263 (long long)mPipeSink->framesWritten(), pipeFrames);
5264 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5265
Eric Laurent81784c32012-11-19 14:55:58 -08005266 state->mCommand = FastMixerState::COLD_IDLE;
5267 state->mColdFutexAddr = &mFastMixerFutex;
5268 state->mColdGen++;
5269 mFastMixerFutex = 0;
5270 sq->end();
5271 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5272 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5273 if (kUseFastMixer == FastMixer_Dynamic) {
5274 mNormalSink = mOutputSink;
5275 }
5276#ifdef AUDIO_WATCHDOG
5277 if (mAudioWatchdog != 0) {
5278 mAudioWatchdog->pause();
5279 }
5280#endif
5281 } else {
5282 sq->end(false /*didModify*/);
5283 }
5284 }
5285 PlaybackThread::threadLoop_standby();
5286}
5287
Andy Hung4b17e882023-07-07 13:47:37 -07005288bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005289{
5290 return false;
5291}
5292
Andy Hung4b17e882023-07-07 13:47:37 -07005293bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005294{
5295 return !mStandby;
5296}
5297
Andy Hung4b17e882023-07-07 13:47:37 -07005298bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299{
Andy Hungf8635b62023-08-31 16:13:39 -07005300 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005301 return waitingAsyncCallback_l();
5302}
5303
Eric Laurent81784c32012-11-19 14:55:58 -08005304// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005305void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005306{
5307 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005308 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005310 // discard any pending drain or write ack by incrementing sequence
5311 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5312 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005313 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005314 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5315 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005317 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005318 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005319}
5320
Andy Hung4b17e882023-07-07 13:47:37 -07005321void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005322{
5323 ALOGV("signal playback thread");
5324 broadcast_l();
5325}
5326
Andy Hung4b17e882023-07-07 13:47:37 -07005327void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005328{
5329 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5330 invalidateTracks((audio_stream_type_t)i);
5331 }
5332}
5333
Andy Hung4b17e882023-07-07 13:47:37 -07005334void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005335{
Eric Laurent81784c32012-11-19 14:55:58 -08005336 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005337 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005338 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005339 // increase sleep time progressively when application underrun condition clears.
5340 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5341 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5342 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005343 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005344 sleepTimeShift--;
5345 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005346 mSleepTimeUs = 0;
5347 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005348 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005349
Eric Laurent81784c32012-11-19 14:55:58 -08005350}
5351
Andy Hung4b17e882023-07-07 13:47:37 -07005352void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005353{
5354 // If no tracks are ready, sleep once for the duration of an output
5355 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005356 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005357 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005358 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5359 // Using the Monopipe availableToWrite, we estimate the
5360 // sleep time to retry for more data (before we underrun).
5361 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5362 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5363 const size_t pipeFrames = monoPipe->maxFrames();
5364 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5365 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5366 const size_t framesDelay = std::min(
5367 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5368 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5369 pipeFrames, framesLeft, framesDelay);
5370 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5371 } else {
5372 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5373 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5374 mSleepTimeUs = kMinThreadSleepTimeUs;
5375 }
5376 // reduce sleep time in case of consecutive application underruns to avoid
5377 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5378 // duration we would end up writing less data than needed by the audio HAL if
5379 // the condition persists.
5380 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5381 sleepTimeShift++;
5382 }
Eric Laurent81784c32012-11-19 14:55:58 -08005383 }
5384 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005385 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005386 }
5387 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005388 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5389 // before effects processing or output.
5390 if (mMixerBufferValid) {
5391 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005392 if (mType == SPATIALIZER) {
5393 memset(mSinkBuffer, 0, mSinkBufferSize);
5394 }
Andy Hung98ef9782014-03-04 14:46:50 -08005395 } else {
5396 memset(mSinkBuffer, 0, mSinkBufferSize);
5397 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005398 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005399 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5400 "anticipated start");
5401 }
5402 // TODO add standby time extension fct of effect tail
5403}
5404
Andy Hungb17d24b2023-08-29 14:26:09 -07005405// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07005406PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005407 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005408{
Andy Hungc0691382018-09-12 18:01:57 -07005409 // clean up deleted track ids in AudioMixer before allocating new tracks
5410 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5411 // for each trackId, destroy it in the AudioMixer
5412 if (mAudioMixer->exists(trackId)) {
5413 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005414 }
5415 });
Andy Hungc0691382018-09-12 18:01:57 -07005416 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005417
5418 mixer_state mixerStatus = MIXER_IDLE;
5419 // find out which tracks need to be processed
5420 size_t count = mActiveTracks.size();
5421 size_t mixedTracks = 0;
5422 size_t tracksWithEffect = 0;
5423 // counts only _active_ fast tracks
5424 size_t fastTracks = 0;
5425 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5426
5427 float masterVolume = mMasterVolume;
5428 bool masterMute = mMasterMute;
5429
5430 if (masterMute) {
5431 masterVolume = 0;
5432 }
5433 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005434 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005435 if (chain != 0) {
5436 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5437 chain->setVolume_l(&v, &v);
5438 masterVolume = (float)((v + (1 << 23)) >> 24);
5439 chain.clear();
5440 }
5441
5442 // prepare a new state to push
5443 FastMixerStateQueue *sq = NULL;
5444 FastMixerState *state = NULL;
5445 bool didModify = false;
5446 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005447 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005448 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005449 sq = mFastMixer->sq();
5450 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005451 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005452 }
5453
Andy Hung69aed5f2014-02-25 17:24:40 -08005454 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005455 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005456
Andy Hungbd3b2b02018-05-21 10:53:11 -07005457 // DeferredOperations handles statistics after setting mixerStatus.
5458 class DeferredOperations {
5459 public:
Andy Hungea840382020-05-05 21:50:17 -07005460 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5461 : mMixerStatus(mixerStatus)
5462 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005463
5464 // when leaving scope, tally frames properly.
5465 ~DeferredOperations() {
5466 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5467 // because that is when the underrun occurs.
5468 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005469 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005470 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005471 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005472 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005473 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005474 }
5475 }
Andy Hungea840382020-05-05 21:50:17 -07005476 // send the max underrun frames for this mixer period
5477 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005478 }
5479
5480 // tallyUnderrunFrames() is called to update the track counters
5481 // with the number of underrun frames for a particular mixer period.
5482 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005483 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005484 mUnderrunFrames.emplace_back(track, underrunFrames);
5485 }
5486
5487 private:
5488 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005489 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005490 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005491 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005492 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005493
jiabin245cdd92018-12-07 17:55:15 -08005494 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005495 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005496 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005497
5498 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005499 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005500
5501 // process fast tracks
5502 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005503 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5504 "%s(%d): FastTrack(%d) present without FastMixer",
5505 __func__, id(), track->id());
5506
jiabin245cdd92018-12-07 17:55:15 -08005507 if (track->getHapticPlaybackEnabled()) {
5508 noFastHapticTrack = false;
5509 }
Eric Laurent81784c32012-11-19 14:55:58 -08005510
5511 // It's theoretically possible (though unlikely) for a fast track to be created
5512 // and then removed within the same normal mix cycle. This is not a problem, as
5513 // the track never becomes active so it's fast mixer slot is never touched.
5514 // The converse, of removing an (active) track and then creating a new track
5515 // at the identical fast mixer slot within the same normal mix cycle,
5516 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005517 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005518 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005519 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5520 FastTrack *fastTrack = &state->mFastTracks[j];
5521
5522 // Determine whether the track is currently in underrun condition,
5523 // and whether it had a recent underrun.
5524 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5525 FastTrackUnderruns underruns = ftDump->mUnderruns;
5526 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005527 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005528 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005529 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005530 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005531 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005532 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005533 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005534 // don't count underruns that occur while stopping or pausing
5535 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005536 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005537 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5538 recentUnderruns > 0) {
5539 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005540 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005541 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005542 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005543 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005544
5545 // This is similar to the state machine for normal tracks,
5546 // with a few modifications for fast tracks.
5547 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005548 switch (track->state()) {
5549 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005550 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005551 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005552 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005553 }
5554 break;
Andy Hung11e74242023-06-26 19:20:57 -07005555 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005556 // ramp down is not yet implemented
5557 track->setPaused();
5558 break;
Andy Hung11e74242023-06-26 19:20:57 -07005559 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005560 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005561 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005562 break;
Andy Hung11e74242023-06-26 19:20:57 -07005563 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005564 if (recentFull > 0 || recentPartial > 0) {
5565 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005566 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005567 }
5568 if (recentUnderruns == 0) {
5569 // no recent underruns: stay active
5570 break;
5571 }
5572 // there has recently been an underrun of some kind
5573 if (track->sharedBuffer() == 0) {
5574 // were any of the recent underruns "empty" (no frames available)?
5575 if (recentEmpty == 0) {
5576 // no, then ignore the partial underruns as they are allowed indefinitely
5577 break;
5578 }
5579 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005580 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005581 break;
5582 }
5583 // indicate to client process that the track was disabled because of underrun;
5584 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005585 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005586 // remove from active list, but state remains ACTIVE [confusing but true]
5587 isActive = false;
5588 break;
5589 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005590 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005591 case IAfTrackBase::STOPPING_2:
5592 case IAfTrackBase::PAUSED:
5593 case IAfTrackBase::STOPPED:
5594 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005595 // Check for presentation complete if track is inactive
5596 // We have consumed all the buffers of this track.
5597 // This would be incomplete if we auto-paused on underrun
5598 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005599 uint32_t latency = 0;
5600 status_t result = mOutput->stream->getLatency(&latency);
5601 ALOGE_IF(result != OK,
5602 "Error when retrieving output stream latency: %d", result);
5603 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005604 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005605 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5606 // track stays in active list until presentation is complete
5607 break;
5608 }
5609 }
5610 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005611 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005612 }
5613 if (track->isStopped()) {
5614 // Can't reset directly, as fast mixer is still polling this track
5615 // track->reset();
5616 // So instead mark this track as needing to be reset after push with ack
5617 resetMask |= 1 << i;
5618 }
5619 isActive = false;
5620 break;
Andy Hung11e74242023-06-26 19:20:57 -07005621 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005622 default:
Andy Hung11e74242023-06-26 19:20:57 -07005623 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005624 }
5625
5626 if (isActive) {
5627 // was it previously inactive?
5628 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005629 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5630 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005631 fastTrack->mBufferProvider = eabp;
5632 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005633 fastTrack->mChannelMask = track->channelMask();
5634 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005635 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005636 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005637 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005638 fastTrack->mGeneration++;
5639 state->mTrackMask |= 1 << j;
5640 didModify = true;
5641 // no acknowledgement required for newly active tracks
5642 }
Andy Hung11e74242023-06-26 19:20:57 -07005643 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005644 float volume;
5645 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5646 volume = 0.f;
5647 } else {
5648 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5649 }
5650
5651 handleVoipVolume_l(&volume);
5652
Eric Laurent81784c32012-11-19 14:55:58 -08005653 // cache the combined master volume and stream type volume for fast mixer; this
5654 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005655 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005656 proxy->framesReleased()).first;
5657 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005658 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005659 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005660 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5661 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5662
Andy Hung7535ed92023-07-17 17:05:00 -07005663 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005664 /*muteState=*/{masterVolume == 0.f,
5665 mStreamTypes[track->streamType()].volume == 0.f,
5666 mStreamTypes[track->streamType()].mute,
5667 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005668 vlf == 0.f && vrf == 0.f,
5669 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005670
5671 vlf *= volume;
5672 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005673
jiabin76d94692022-12-15 21:51:21 +00005674 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005675 ++fastTracks;
5676 } else {
5677 // was it previously active?
5678 if (state->mTrackMask & (1 << j)) {
5679 fastTrack->mBufferProvider = NULL;
5680 fastTrack->mGeneration++;
5681 state->mTrackMask &= ~(1 << j);
5682 didModify = true;
5683 // If any fast tracks were removed, we must wait for acknowledgement
5684 // because we're about to decrement the last sp<> on those tracks.
5685 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5686 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005687 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5688 // AudioTrack may start (which may not be with a start() but with a write()
5689 // after underrun) and immediately paused or released. In that case the
5690 // FastTrack state hasn't had time to update.
5691 // TODO Remove the ALOGW when this theory is confirmed.
5692 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005693 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005694 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005695 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005696 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005697 }
5698 tracksToRemove->add(track);
5699 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005700 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005701 }
jiabin245cdd92018-12-07 17:55:15 -08005702 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5703 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5704 didModify = true;
5705 }
Eric Laurent81784c32012-11-19 14:55:58 -08005706 continue;
5707 }
5708
5709 { // local variable scope to avoid goto warning
5710
5711 audio_track_cblk_t* cblk = track->cblk();
5712
5713 // The first time a track is added we wait
5714 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005715 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005716
5717 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005718 // use the trackId as the AudioMixer name.
5719 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005720 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005721 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005722 track->channelMask(),
5723 track->format(),
5724 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005725 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005726 ALOGW("%s(): AudioMixer cannot create track(%d)"
5727 " mask %#x, format %#x, sessionId %d",
5728 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005729 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005730 tracksToRemove->add(track);
5731 track->invalidate(); // consider it dead.
5732 continue;
5733 }
5734 }
5735
Eric Laurent81784c32012-11-19 14:55:58 -08005736 // make sure that we have enough frames to mix one full buffer.
5737 // enforce this condition only once to enable draining the buffer in case the client
5738 // app does not call stop() and relies on underrun to stop:
5739 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5740 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005741 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005742 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5743 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005744
5745 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005746 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005747 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5748 // add frames already consumed but not yet released by the resampler
5749 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005750 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005751
Eric Laurent81784c32012-11-19 14:55:58 -08005752 uint32_t minFrames = 1;
5753 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5754 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005755 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005756 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005757
5758 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005759 if (ATRACE_ENABLED()) {
5760 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005761 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005762 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005763 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005764 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005765 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005766 !track->isPaused() && !track->isTerminated())
5767 {
Andy Hungc0691382018-09-12 18:01:57 -07005768 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005769
5770 mixedTracks++;
5771
Andy Hung69aed5f2014-02-25 17:24:40 -08005772 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5773 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005774 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005775 if (track->mainBuffer() != mSinkBuffer &&
5776 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005777 if (mEffectBufferEnabled) {
5778 mEffectBufferValid = true; // Later can set directly.
5779 }
Eric Laurent81784c32012-11-19 14:55:58 -08005780 chain = getEffectChain_l(track->sessionId());
5781 // Delegate volume control to effect in track effect chain if needed
5782 if (chain != 0) {
5783 tracksWithEffect++;
5784 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005785 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005786 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005787 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005788 }
5789 }
5790
5791
5792 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005793 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005794 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005795 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5796 if (track->state() == IAfTrackBase::RESUMING) {
5797 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005798 // If a new track is paused immediately after start, do not ramp on resume.
5799 if (cblk->mServer != 0) {
5800 param = AudioMixer::RAMP_VOLUME;
5801 }
Eric Laurent81784c32012-11-19 14:55:58 -08005802 }
Andy Hungc0691382018-09-12 18:01:57 -07005803 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005804 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005805 // FIXME should not make a decision based on mServer
5806 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005807 // If the track is stopped before the first frame was mixed,
5808 // do not apply ramp
5809 param = AudioMixer::RAMP_VOLUME;
5810 }
5811
5812 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005813 uint32_t vl, vr; // in U8.24 integer format
5814 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005815 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005816 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005817 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005818 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005819 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005820 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005821
Eric Laurenteab90452019-06-24 15:17:46 -07005822 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5823 v = 0;
5824 }
5825
5826 handleVoipVolume_l(&v);
5827
5828 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005829 vl = vr = 0;
5830 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005831 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005832 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005833 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005834 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5835 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005836 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005837 if (vlf > GAIN_FLOAT_UNITY) {
5838 ALOGV("Track left volume out of range: %.3g", vlf);
5839 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005840 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005841 if (vrf > GAIN_FLOAT_UNITY) {
5842 ALOGV("Track right volume out of range: %.3g", vrf);
5843 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005844 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005845
Andy Hung7535ed92023-07-17 17:05:00 -07005846 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005847 /*muteState=*/{masterVolume == 0.f,
5848 mStreamTypes[track->streamType()].volume == 0.f,
5849 mStreamTypes[track->streamType()].mute,
5850 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005851 vlf == 0.f && vrf == 0.f,
5852 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005853
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005854 // now apply the master volume and stream type volume and shaper volume
5855 vlf *= v * vh;
5856 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005857 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005858 // then derive vl and vr as U8.24 versions for the effect chain
5859 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5860 vl = (uint32_t) (scaleto8_24 * vlf);
5861 vr = (uint32_t) (scaleto8_24 * vrf);
5862 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005863 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005864 // send level comes from shared memory and so may be corrupt
5865 if (sendLevel > MAX_GAIN_INT) {
5866 ALOGV("Track send level out of range: %04X", sendLevel);
5867 sendLevel = MAX_GAIN_INT;
5868 }
Andy Hung6be49402014-05-30 10:42:03 -07005869 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5870 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005871 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005872
jiabin76d94692022-12-15 21:51:21 +00005873 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005874
Eric Laurent81784c32012-11-19 14:55:58 -08005875 // Delegate volume control to effect in track effect chain if needed
5876 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5877 // Do not ramp volume if volume is controlled by effect
5878 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005879 // Update remaining floating point volume levels
5880 vlf = (float)vl / (1 << 24);
5881 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07005882 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005883 } else {
5884 // force no volume ramp when volume controller was just disabled or removed
5885 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07005886 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005887 param = AudioMixer::VOLUME;
5888 }
Andy Hung11e74242023-06-26 19:20:57 -07005889 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005890 }
5891
Eric Laurent81784c32012-11-19 14:55:58 -08005892 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07005893 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005894 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005895
Andy Hungc0691382018-09-12 18:01:57 -07005896 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5897 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5898 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005899 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005900 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005901 AudioMixer::TRACK,
5902 AudioMixer::FORMAT, (void *)track->format());
5903 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005904 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005905 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005906 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005907
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005908 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005909 mAudioMixer->setParameter(
5910 trackId,
5911 AudioMixer::TRACK,
5912 AudioMixer::MIXER_CHANNEL_MASK,
5913 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5914 } else {
5915 mAudioMixer->setParameter(
5916 trackId,
5917 AudioMixer::TRACK,
5918 AudioMixer::MIXER_CHANNEL_MASK,
5919 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5920 }
5921
Glenn Kastene3aa6592012-12-04 12:22:46 -08005922 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005923 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005924 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005925 if (reqSampleRate == 0) {
5926 reqSampleRate = mSampleRate;
5927 } else if (reqSampleRate > maxSampleRate) {
5928 reqSampleRate = maxSampleRate;
5929 }
Eric Laurent81784c32012-11-19 14:55:58 -08005930 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005931 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005932 AudioMixer::RESAMPLE,
5933 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005934 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005935
Andy Hung8edb8dc2015-03-26 19:13:55 -07005936 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005937 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005938 AudioMixer::TIMESTRETCH,
5939 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005940 // cast away constness for this generic API.
5941 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005942
Andy Hung69aed5f2014-02-25 17:24:40 -08005943 /*
5944 * Select the appropriate output buffer for the track.
5945 *
Andy Hung98ef9782014-03-04 14:46:50 -08005946 * Tracks with effects go into their own effects chain buffer
5947 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005948 *
5949 * Other tracks can use mMixerBuffer for higher precision
5950 * channel accumulation. If this buffer is enabled
5951 * (mMixerBufferEnabled true), then selected tracks will accumulate
5952 * into it.
5953 *
5954 */
5955 if (mMixerBufferEnabled
5956 && (track->mainBuffer() == mSinkBuffer
5957 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005958 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005959 mAudioMixer->setParameter(
5960 trackId,
5961 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005962 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005963 mAudioMixer->setParameter(
5964 trackId,
5965 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005966 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005967 } else {
5968 mAudioMixer->setParameter(
5969 trackId,
5970 AudioMixer::TRACK,
5971 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5972 mAudioMixer->setParameter(
5973 trackId,
5974 AudioMixer::TRACK,
5975 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5976 // TODO: override track->mainBuffer()?
5977 mMixerBufferValid = true;
5978 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005979 } else {
5980 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005981 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005982 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005983 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005984 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005985 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005986 AudioMixer::TRACK,
5987 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5988 }
Eric Laurent81784c32012-11-19 14:55:58 -08005989 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005990 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005991 AudioMixer::TRACK,
5992 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005993 mAudioMixer->setParameter(
5994 trackId,
5995 AudioMixer::TRACK,
5996 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005997 mAudioMixer->setParameter(
5998 trackId,
5999 AudioMixer::TRACK,
6000 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung11e74242023-06-26 19:20:57 -07006001 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006002 mAudioMixer->setParameter(
6003 trackId,
6004 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07006005 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006006
6007 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006008 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006009
6010 // If one track is ready, set the mixer ready if:
6011 // - the mixer was not ready during previous round OR
6012 // - no other track is not ready
6013 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6014 mixerStatus != MIXER_TRACKS_ENABLED) {
6015 mixerStatus = MIXER_TRACKS_READY;
6016 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006017
6018 // Enable the next few lines to instrument a test for underrun log handling.
6019 // TODO: Remove when we have a better way of testing the underrun log.
6020#if 0
6021 static int i;
6022 if ((++i & 0xf) == 0) {
6023 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6024 }
6025#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006026 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006027 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006028 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006029 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6030 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006031 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006032 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006033 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006034
Eric Laurent81784c32012-11-19 14:55:58 -08006035 // clear effect chain input buffer if an active track underruns to avoid sending
6036 // previous audio buffer again to effects
6037 chain = getEffectChain_l(track->sessionId());
6038 if (chain != 0) {
6039 chain->clearInputBuffer();
6040 }
6041
Andy Hungc0691382018-09-12 18:01:57 -07006042 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006043 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6044 track->isStopped() || track->isPaused()) {
6045 // We have consumed all the buffers of this track.
6046 // Remove it from the list of active tracks.
6047 // TODO: use actual buffer filling status instead of latency when available from
6048 // audio HAL
6049 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006050 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006051 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6052 if (track->isStopped()) {
6053 track->reset();
6054 }
6055 tracksToRemove->add(track);
6056 }
6057 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006058 // No buffers for this track. Give it a few chances to
6059 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07006060 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006061 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6062 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006063 tracksToRemove->add(track);
6064 // indicate to client process that the track was disabled because of underrun;
6065 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006066 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006067 // If one track is not ready, mark the mixer also not ready if:
6068 // - the mixer was ready during previous round OR
6069 // - no other track is ready
6070 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6071 mixerStatus != MIXER_TRACKS_READY) {
6072 mixerStatus = MIXER_TRACKS_ENABLED;
6073 }
6074 }
Andy Hungc0691382018-09-12 18:01:57 -07006075 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006076 }
6077
6078 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006079
6080 }
6081
jiabin245cdd92018-12-07 17:55:15 -08006082 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6083 // When there is no fast track playing haptic and FastMixer exists,
6084 // enabling the first FastTrack, which provides mixed data from normal
6085 // tracks, to play haptic data.
6086 FastTrack *fastTrack = &state->mFastTracks[0];
6087 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6088 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6089 didModify = true;
6090 }
6091 }
6092
Eric Laurent81784c32012-11-19 14:55:58 -08006093 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006094 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006095 if (didModify) {
6096 state->mFastTracksGen++;
6097 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6098 if (kUseFastMixer == FastMixer_Dynamic &&
6099 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6100 state->mCommand = FastMixerState::COLD_IDLE;
6101 state->mColdFutexAddr = &mFastMixerFutex;
6102 state->mColdGen++;
6103 mFastMixerFutex = 0;
6104 if (kUseFastMixer == FastMixer_Dynamic) {
6105 mNormalSink = mOutputSink;
6106 }
6107 // If we go into cold idle, need to wait for acknowledgement
6108 // so that fast mixer stops doing I/O.
6109 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6110 pauseAudioWatchdog = true;
6111 }
Eric Laurent81784c32012-11-19 14:55:58 -08006112 }
6113 if (sq != NULL) {
6114 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006115 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6116 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6117 // when bringing the output sink into standby.)
6118 //
6119 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6120 //
6121 // This occurs with BT suspend when we idle the FastMixer with
6122 // active tracks, which may be added or removed.
6123 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006124 }
6125#ifdef AUDIO_WATCHDOG
6126 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6127 mAudioWatchdog->pause();
6128 }
6129#endif
6130
6131 // Now perform the deferred reset on fast tracks that have stopped
6132 while (resetMask != 0) {
6133 size_t i = __builtin_ctz(resetMask);
6134 ALOG_ASSERT(i < count);
6135 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006136 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006137 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6138 track->reset();
6139 }
6140
Andy Hung80d03d22018-04-10 10:32:11 -07006141 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6142 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6143 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6144 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6145 // See also the implementation of destroyTrack_l().
6146 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006147 const int trackId = track->id();
6148 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6149 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006150 }
6151 }
6152
Eric Laurent81784c32012-11-19 14:55:58 -08006153 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006154 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006155
Eric Laurentb3f315a2021-07-13 15:09:05 +02006156 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6157 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006158 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006159 }
6160
6161 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006162 // as long as there are effects we should clear the effects buffer, to avoid
6163 // passing a non-clean buffer to the effect chain
6164 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006165 if (mType == SPATIALIZER) {
6166 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6167 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006168 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006169 // sink or mix buffer must be cleared if all tracks are connected to an
6170 // effect chain as in this case the mixer will not write to the sink or mix buffer
6171 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006172 // always clear sink buffer for spatializer output as the output of the spatializer
6173 // effect will be accumulated into it
6174 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6175 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006176 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006177 if (mMixerBufferValid) {
6178 memset(mMixerBuffer, 0, mMixerBufferSize);
6179 // TODO: In testing, mSinkBuffer below need not be cleared because
6180 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6181 // after mixing.
6182 //
6183 // To enforce this guarantee:
6184 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6185 // (mixedTracks == 0 && fastTracks > 0))
6186 // must imply MIXER_TRACKS_READY.
6187 // Later, we may clear buffers regardless, and skip much of this logic.
6188 }
Andy Hung98ef9782014-03-04 14:46:50 -08006189 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006190 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006191 }
6192
6193 // if any fast tracks, then status is ready
6194 mMixerStatusIgnoringFastTracks = mixerStatus;
6195 if (fastTracks > 0) {
6196 mixerStatus = MIXER_TRACKS_READY;
6197 }
6198 return mixerStatus;
6199}
6200
Andy Hungb17d24b2023-08-29 14:26:09 -07006201// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006202uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006203{
6204 uint32_t trackCount = 0;
6205 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006206 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006207 trackCount++;
6208 }
6209 }
6210 return trackCount;
6211}
6212
Andy Hung4b17e882023-07-07 13:47:37 -07006213bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006214{
Brian Lindahl65e90012022-07-27 18:01:07 +02006215 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6216 // could falsely detect that the frame position has stalled due to underrun because we haven't
6217 // given the Audio HAL enough time to update.
6218 const nsecs_t nowNs = systemTime();
6219 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6220 return mLatchedValue;
6221 }
6222 mPreviousNs = nowNs;
6223 mLatchedValue = false;
6224 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006225 uint64_t position = 0;
6226 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006227 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006228 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006229 if (position != mPreviousPosition) {
6230 mPreviousPosition = position;
6231 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006232 }
6233 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006234 return mLatchedValue;
6235}
6236
Andy Hung4b17e882023-07-07 13:47:37 -07006237void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006238{
6239 mLatchedValue = true;
6240 mPreviousPosition = 0;
6241 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006242}
6243
Andy Hungb17d24b2023-08-29 14:26:09 -07006244// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006245bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006246 audio_channel_mask_t channelMask, audio_format_t format,
6247 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006248{
Andy Hung1bc088a2018-02-09 15:57:31 -08006249 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6250 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006251 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006252 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006253 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006254 ALOGW("%s: invalid format: %#x", __func__, format);
6255 return false;
6256 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006257 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006258 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6259 return false;
6260 }
6261 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006262}
6263
Andy Hungb17d24b2023-08-29 14:26:09 -07006264// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006265bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006266 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006267{
Eric Laurent81784c32012-11-19 14:55:58 -08006268 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006269 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006270
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006271 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006272
Eric Laurent10351942014-05-08 18:49:52 -07006273 AudioParameter param = AudioParameter(keyValuePair);
6274 int value;
6275 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6276 reconfig = true;
6277 }
6278 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006279 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006280 status = BAD_VALUE;
6281 } else {
6282 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006283 reconfig = true;
6284 }
Eric Laurent10351942014-05-08 18:49:52 -07006285 }
6286 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006287 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006288 status = BAD_VALUE;
6289 } else {
6290 // no need to save value, since it's constant
6291 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006292 }
Eric Laurent10351942014-05-08 18:49:52 -07006293 }
6294 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6295 // do not accept frame count changes if tracks are open as the track buffer
6296 // size depends on frame count and correct behavior would not be guaranteed
6297 // if frame count is changed after track creation
6298 if (!mTracks.isEmpty()) {
6299 status = INVALID_OPERATION;
6300 } else {
6301 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006302 }
Eric Laurent10351942014-05-08 18:49:52 -07006303 }
6304 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006305 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006306 }
Eric Laurent81784c32012-11-19 14:55:58 -08006307
Eric Laurent10351942014-05-08 18:49:52 -07006308 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006309 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006310 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006311 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6312 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006313 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006314 mThreadMetrics.logEndInterval();
6315 mThreadSnapshot.onEnd();
6316 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006317 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006318 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006319 }
Eric Laurent10351942014-05-08 18:49:52 -07006320 if (status == NO_ERROR && reconfig) {
6321 readOutputParameters_l();
6322 delete mAudioMixer;
6323 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006324 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006325 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006326 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006327 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006328 track->channelMask(),
6329 track->format(),
6330 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006331 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006332 "%s(): AudioMixer cannot create track(%d)"
6333 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006334 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006335 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006336 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006337 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006338 }
Eric Laurent81784c32012-11-19 14:55:58 -08006339 }
6340
Dean Wheatley68918102021-03-19 22:09:19 +11006341 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006342}
6343
6344
Andy Hung4b17e882023-07-07 13:47:37 -07006345void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006346{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006347 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006348 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006349 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006350 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006351 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6352 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6353 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006354 if (hasFastMixer()) {
6355 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6356
6357 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6358 // while we are dumping it. It may be inconsistent, but it won't mutate!
6359 // This is a large object so we place it on the heap.
6360 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006361 const std::unique_ptr<FastMixerDumpState> copy =
6362 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006363 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006364
6365#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006366 // Similar for state queue
6367 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6368 observerCopy.dump(fd);
6369 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6370 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006371#endif
6372
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006373#ifdef AUDIO_WATCHDOG
6374 if (mAudioWatchdog != 0) {
6375 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6376 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6377 wdCopy.dump(fd);
6378 }
6379#endif
6380
6381 } else {
6382 dprintf(fd, " No FastMixer\n");
6383 }
Eric Laurent90cea102023-05-15 15:08:27 +02006384
6385 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6386 mBluetoothLatencyModesEnabled ? "" : "not ");
6387 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6388 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6389 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006390}
6391
Andy Hung4b17e882023-07-07 13:47:37 -07006392uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006393{
6394 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6395}
6396
Andy Hung4b17e882023-07-07 13:47:37 -07006397uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006398{
6399 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6400}
6401
Andy Hung4b17e882023-07-07 13:47:37 -07006402void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006403{
6404 PlaybackThread::cacheParameters_l();
6405
6406 // FIXME: Relaxed timing because of a certain device that can't meet latency
6407 // Should be reduced to 2x after the vendor fixes the driver issue
6408 // increase threshold again due to low power audio mode. The way this warning
6409 // threshold is calculated and its usefulness should be reconsidered anyway.
6410 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6411}
6412
Andy Hung4b17e882023-07-07 13:47:37 -07006413void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006414 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006415}
6416
Andy Hung4b17e882023-07-07 13:47:37 -07006417void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006418 // Only handle latency mode if:
6419 // - mBluetoothLatencyModesEnabled is true
6420 // - the HAL supports latency modes
6421 // - the selected device is Bluetooth LE or A2DP
6422 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6423 return;
6424 }
6425 if (mOutDeviceTypeAddrs.size() != 1
6426 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6427 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6428 return;
6429 }
6430
6431 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6432 if (mSupportedLatencyModes.size() == 1) {
6433 // If the HAL only support one latency mode currently, confirm the choice
6434 latencyMode = mSupportedLatencyModes[0];
6435 } else if (mSupportedLatencyModes.size() > 1) {
6436 // Request low latency if:
6437 // - At least one active track is either:
6438 // - a fast track with gaming usage or
6439 // - a track with acessibility usage
6440 for (const auto& track : mActiveTracks) {
6441 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6442 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6443 latencyMode = AUDIO_LATENCY_MODE_LOW;
6444 break;
6445 }
6446 }
6447 }
6448
6449 if (latencyMode != mSetLatencyMode) {
6450 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6451 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6452 __func__, mId, toString(latencyMode).c_str(), status);
6453 if (status == NO_ERROR) {
6454 mSetLatencyMode = latencyMode;
6455 }
6456 }
6457}
6458
Andy Hung4b17e882023-07-07 13:47:37 -07006459void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006460
6461 if (mOutput == nullptr || mOutput->stream == nullptr) {
6462 return;
6463 }
6464 std::vector<audio_latency_mode_t> latencyModes;
6465 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6466 if (status != NO_ERROR) {
6467 latencyModes.clear();
6468 }
6469 if (latencyModes != mSupportedLatencyModes) {
6470 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6471 __func__, mId, status, toString(latencyModes).c_str());
6472 mSupportedLatencyModes.swap(latencyModes);
6473 sendHalLatencyModesChangedEvent_l();
6474 }
6475}
6476
Andy Hung4b17e882023-07-07 13:47:37 -07006477status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006478 std::vector<audio_latency_mode_t>* modes) {
6479 if (modes == nullptr) {
6480 return BAD_VALUE;
6481 }
Andy Hungf8635b62023-08-31 16:13:39 -07006482 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006483 *modes = mSupportedLatencyModes;
6484 return NO_ERROR;
6485}
6486
Andy Hung4b17e882023-07-07 13:47:37 -07006487void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006488 std::vector<audio_latency_mode_t> modes) {
Andy Hungf8635b62023-08-31 16:13:39 -07006489 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006490 if (modes != mSupportedLatencyModes) {
6491 ALOGD("%s: thread(%d) supported latency modes: %s",
6492 __func__, mId, toString(modes).c_str());
6493 mSupportedLatencyModes.swap(modes);
6494 sendHalLatencyModesChangedEvent_l();
6495 }
6496}
6497
Andy Hung4b17e882023-07-07 13:47:37 -07006498status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006499 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6500 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6501 return INVALID_OPERATION;
6502 }
6503 mBluetoothLatencyModesEnabled.store(enabled);
6504 return NO_ERROR;
6505}
6506
Eric Laurent81784c32012-11-19 14:55:58 -08006507// ----------------------------------------------------------------------------
6508
Andy Hung4b17e882023-07-07 13:47:37 -07006509/* static */
6510sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006511 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006512 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6513 const audio_offload_info_t& offloadInfo) {
6514 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006515 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006516}
6517
Andy Hung7535ed92023-07-17 17:05:00 -07006518DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006519 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6520 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006521 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006522 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006523{
Andy Hung7535ed92023-07-17 17:05:00 -07006524 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006525}
6526
Andy Hung4b17e882023-07-07 13:47:37 -07006527DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006528{
6529}
6530
Andy Hung4b17e882023-07-07 13:47:37 -07006531void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006532{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006533 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006534 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6535 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6536}
6537
Andy Hung4b17e882023-07-07 13:47:37 -07006538void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006539{
Andy Hungf8635b62023-08-31 16:13:39 -07006540 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006541 if (mMasterBalance != balance) {
6542 mMasterBalance.store(balance);
6543 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6544 broadcast_l();
6545 }
6546}
6547
Andy Hung4b17e882023-07-07 13:47:37 -07006548void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006549{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006550 float left, right;
6551
Andy Hung333ab962019-05-28 20:23:35 -07006552 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006553 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006554
Andy Hung398ffa22022-12-13 19:19:53 -08006555 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6556 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6557
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006558 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6559 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006560
6561 const int64_t volumeShaperFrames =
6562 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6563 const auto [shaperVolume, shaperActive] =
6564 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006565 mVolumeShaperActive = shaperActive;
6566
Vlad Popae2f5aef2022-07-25 16:00:20 +02006567 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6568 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6569 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6570
6571 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6572
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006573 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006574 left = right = 0;
6575 } else {
6576 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006577 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006578
Glenn Kastenc56f3422014-03-21 17:53:17 -07006579 if (left > GAIN_FLOAT_UNITY) {
6580 left = GAIN_FLOAT_UNITY;
6581 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006582 if (right > GAIN_FLOAT_UNITY) {
6583 right = GAIN_FLOAT_UNITY;
6584 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006585 left *= v;
6586 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006587 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006588 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6589 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6590 right *= mMasterBalanceRight;
6591 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006592 }
6593
Andy Hung7535ed92023-07-17 17:05:00 -07006594 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006595 /*muteState=*/{mMasterMute,
6596 mStreamTypes[track->streamType()].volume == 0.f,
6597 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006598 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006599 clientVolumeMute,
6600 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006601
Eric Laurentbfb1b832013-01-07 09:53:42 -08006602 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006603 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006604 if (left != mLeftVolFloat || right != mRightVolFloat) {
6605 mLeftVolFloat = left;
6606 mRightVolFloat = right;
6607
Eric Laurentbfb1b832013-01-07 09:53:42 -08006608 // Delegate volume control to effect in track effect chain if needed
6609 // only one effect chain can be present on DirectOutputThread, so if
6610 // there is one, the track is connected to it
6611 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006612 // if effect chain exists, volume is handled by it.
6613 // Convert volumes from float to 8.24
6614 uint32_t vl = (uint32_t)(left * (1 << 24));
6615 uint32_t vr = (uint32_t)(right * (1 << 24));
6616 // Direct/Offload effect chains set output volume in setVolume_l().
6617 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6618 } else {
6619 // otherwise we directly set the volume.
6620 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006621 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006622 }
6623 }
6624}
6625
Andy Hung4b17e882023-07-07 13:47:37 -07006626void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006627{
Andy Hung11e74242023-06-26 19:20:57 -07006628 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6629 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006630
Eric Laurent0f0631e2015-07-06 18:01:25 -07006631 if (previousTrack != 0 && latestTrack != 0) {
6632 if (mType == DIRECT) {
6633 if (previousTrack.get() != latestTrack.get()) {
6634 mFlushPending = true;
6635 }
6636 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006637 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6638 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006639 mFlushPending = true;
6640 }
6641 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006642 } else if (previousTrack == 0) {
6643 // there could be an old track added back during track transition for direct
6644 // output, so always issues flush to flush data of the previous track if it
6645 // was already destroyed with HAL paused, then flush can resume the playback
6646 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006647 }
6648 PlaybackThread::onAddNewTrack_l();
6649}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006650
Andy Hung4b17e882023-07-07 13:47:37 -07006651PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006652 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006653)
6654{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006655 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006656 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006657 bool doHwPause = false;
6658 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006659
6660 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006661 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006662 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006663 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006664 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006665 continue;
6666 }
6667
Andy Hung11e74242023-06-26 19:20:57 -07006668 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006669#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006670 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006671#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006672 // Only consider last track started for volume and mixer state control.
6673 // In theory an older track could underrun and restart after the new one starts
6674 // but as we only care about the transition phase between two tracks on a
6675 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006676 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006677 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006678
Kuowei Li23666472021-01-20 10:23:25 +08006679 if (track->isPausePending()) {
6680 track->pauseAck();
6681 // It is possible a track might have been flushed or stopped.
6682 // Other operations such as flush pending might occur on the next prepare.
6683 if (track->isPausing()) {
6684 track->setPaused();
6685 }
6686 // Always perform pause, as an immediate flush will change
6687 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006688 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006689 doHwPause = true;
6690 mHwPaused = true;
6691 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006692 } else if (track->isFlushPending()) {
6693 track->flushAck();
6694 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006695 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006696 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006697 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006698 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006699 if (last) {
6700 mLeftVolFloat = mRightVolFloat = -1.0;
6701 if (mHwPaused) {
6702 doHwResume = true;
6703 mHwPaused = false;
6704 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006705 }
6706 }
6707
Eric Laurent81784c32012-11-19 14:55:58 -08006708 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006709 // for all its buffers to be filled before processing it.
6710 // Allow draining the buffer in case the client
6711 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006712 // hence the test on (track->retryCount() > 1).
6713 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006714 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6715 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006716 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006717
6718 // target retry count that we will use is based on the time we wait for retries.
6719 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6720 // the retry threshold is when we accept any size for PCM data. This is slightly
6721 // smaller than the retry count so we can push small bits of data without a glitch.
6722 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006723 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006724 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006725 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006726 minFrames = mNormalFrameCount;
6727 } else {
6728 minFrames = 1;
6729 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006730
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006731 const size_t framesReady = track->framesReady();
6732 const int trackId = track->id();
6733 if (ATRACE_ENABLED()) {
6734 std::string traceName("nRdy");
6735 traceName += std::to_string(trackId);
6736 ATRACE_INT(traceName.c_str(), framesReady);
6737 }
6738 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006739 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006740 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006741 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006742
Andy Hung11e74242023-06-26 19:20:57 -07006743 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6744 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006745 if (last) {
6746 // make sure processVolume_l() will apply new volume even if 0
6747 mLeftVolFloat = mRightVolFloat = -1.0;
6748 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006749 if (!mHwSupportsPause) {
6750 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006751 }
6752 }
6753
6754 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006755 processVolume_l(track, last);
6756 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006757 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006758 if (previousTrack != 0) {
6759 if (track != previousTrack.get()) {
6760 // Flush any data still being written from last track
6761 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006762 // Invalidate previous track to force a seek when resuming.
6763 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006764 }
6765 }
6766 mPreviousTrack = track;
6767
Eric Laurentd595b7c2013-04-03 17:27:56 -07006768 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006769 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006770 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006771 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006772 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006773 doHwResume = true;
6774 mHwPaused = false;
6775 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006776 }
Eric Laurent81784c32012-11-19 14:55:58 -08006777 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006778 // clear effect chain input buffer if the last active track started underruns
6779 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006780 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006781 mEffectChains[0]->clearInputBuffer();
6782 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006783 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006784 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006785 if (last && mHwPaused) {
6786 doHwResume = true;
6787 mHwPaused = false;
6788 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006789 }
6790 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6791 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006792 // We have consumed all the buffers of this track.
6793 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006794 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006795 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006796 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006797 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006798 if (presComplete) {
6799 mOutput->presentationComplete();
6800 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006801 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006802 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006803 }
Eric Laurent81784c32012-11-19 14:55:58 -08006804 if (track->isStopped()) {
6805 track->reset();
6806 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006807 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006808 }
6809 } else {
6810 // No buffers for this track. Give it a few chances to
6811 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006812 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006813 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006814 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006815 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006816 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006817 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006818 } else {
6819 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6820 tracksToRemove->add(track);
6821 // indicate to client process that the track was disabled because of
6822 // underrun; it will then automatically call start() when data is available
6823 track->disable();
6824 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6825 // unlike mixerthread, HAL can be paused for direct output
6826 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6827 "minFrames = %u, mFormat = %#x",
6828 framesReady, minFrames, mFormat);
6829 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6830 doHwPause = true;
6831 mHwPaused = true;
6832 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006833 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006834 } else if (last) {
6835 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006836 }
6837 }
6838 }
6839 }
6840
Eric Laurentd1f69b02014-12-15 14:33:13 -08006841 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006842 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006843 for (size_t i = 0; i < mTracks.size(); i++) {
6844 if (mTracks[i]->isFlushPending()) {
6845 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006846 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006847 }
6848 }
6849 }
6850
6851 // make sure the pause/flush/resume sequence is executed in the right order.
6852 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6853 // before flush and then resume HW. This can happen in case of pause/flush/resume
6854 // if resume is received before pause is executed.
6855 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006856 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006857 status_t result = mOutput->stream->pause();
6858 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006859 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006860 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006861 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006862 flushHw_l();
6863 }
6864 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006865 status_t result = mOutput->stream->resume();
6866 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006867 }
Eric Laurent81784c32012-11-19 14:55:58 -08006868 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006869 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006870
6871 return mixerStatus;
6872}
6873
Andy Hung4b17e882023-07-07 13:47:37 -07006874void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006875{
Eric Laurent81784c32012-11-19 14:55:58 -08006876 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006877 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006878 // output audio to hardware
6879 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006880 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006881 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006882 status_t status = mActiveTrack->getNextBuffer(&buffer);
6883 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006884 // no need to pad with 0 for compressed audio
6885 if (audio_has_proportional_frames(mFormat)) {
6886 memset(curBuf, 0, frameCount * mFrameSize);
6887 }
Eric Laurent81784c32012-11-19 14:55:58 -08006888 break;
6889 }
6890 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6891 frameCount -= buffer.frameCount;
6892 curBuf += buffer.frameCount * mFrameSize;
6893 mActiveTrack->releaseBuffer(&buffer);
6894 }
Andy Hung2098f272014-02-27 14:00:06 -08006895 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006896 mSleepTimeUs = 0;
6897 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006898 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006899}
6900
Andy Hung4b17e882023-07-07 13:47:37 -07006901void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006902{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006903 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006904 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006905 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006906 return;
6907 }
Andy Hung85ba3332021-04-27 17:40:26 -07006908 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6909 mSleepTimeUs = mActiveSleepTimeUs;
6910 } else {
6911 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006912 }
Andy Hung85ba3332021-04-27 17:40:26 -07006913 // Note: In S or later, we do not write zeroes for
6914 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006915}
6916
Andy Hung4b17e882023-07-07 13:47:37 -07006917void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006918{
6919 {
Andy Hungf8635b62023-08-31 16:13:39 -07006920 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006921 for (size_t i = 0; i < mTracks.size(); i++) {
6922 if (mTracks[i]->isFlushPending()) {
6923 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006924 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006925 }
6926 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006927 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006928 flushHw_l();
6929 }
6930 }
6931 PlaybackThread::threadLoop_exit();
6932}
6933
6934// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07006935bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006936{
6937 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006938 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006939
6940 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6941 // after a timeout and we will enter standby then.
6942 if (mTracks.size() > 0) {
6943 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006944 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07006945 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006946 }
6947
Eric Laurent5cff4032015-05-26 13:49:58 -07006948 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006949}
6950
Andy Hungb17d24b2023-08-29 14:26:09 -07006951// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006952bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006953 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006954{
6955 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006956 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006957
Eric Laurent10351942014-05-08 18:49:52 -07006958 AudioParameter param = AudioParameter(keyValuePair);
6959 int value;
6960 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006961 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006962 }
Eric Laurent10351942014-05-08 18:49:52 -07006963 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6964 // do not accept frame count changes if tracks are open as the track buffer
6965 // size depends on frame count and correct behavior would not be garantied
6966 // if frame count is changed after track creation
6967 if (!mTracks.isEmpty()) {
6968 status = INVALID_OPERATION;
6969 } else {
6970 reconfig = true;
6971 }
6972 }
6973 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006974 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006975 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006976 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006977 if (!mStandby) {
6978 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006979 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006980 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006981 }
Eric Laurent10351942014-05-08 18:49:52 -07006982 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006983 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006984 }
6985 if (status == NO_ERROR && reconfig) {
6986 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006987 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006988 }
6989 }
6990
Dean Wheatley68918102021-03-19 22:09:19 +11006991 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006992}
6993
Andy Hung4b17e882023-07-07 13:47:37 -07006994uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006995{
6996 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006997 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006998 time = PlaybackThread::activeSleepTimeUs();
6999 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007000 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007001 }
7002 return time;
7003}
7004
Andy Hung4b17e882023-07-07 13:47:37 -07007005uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007006{
7007 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007008 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007009 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7010 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007011 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007012 }
7013 return time;
7014}
7015
Andy Hung4b17e882023-07-07 13:47:37 -07007016uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007017{
7018 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007019 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007020 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7021 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007022 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007023 }
7024 return time;
7025}
7026
Andy Hung4b17e882023-07-07 13:47:37 -07007027void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007028{
7029 PlaybackThread::cacheParameters_l();
7030
7031 // use shorter standby delay as on normal output to release
7032 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007033 // no delay on outputs with HW A/V sync
7034 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007035 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007036 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007037 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007038 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007039 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007040 }
Eric Laurent81784c32012-11-19 14:55:58 -08007041}
7042
Andy Hung4b17e882023-07-07 13:47:37 -07007043void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007044{
ziyangch8f194f12021-12-01 13:48:04 -08007045 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007046 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007047 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007048 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007049 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007050 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007051 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007052}
7053
Andy Hung4b17e882023-07-07 13:47:37 -07007054int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007055 // If a VolumeShaper is active, we must wake up periodically to update volume.
7056 const int64_t NS_PER_MS = 1000000;
7057 return mVolumeShaperActive ?
7058 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7059}
7060
Eric Laurent81784c32012-11-19 14:55:58 -08007061// ----------------------------------------------------------------------------
7062
Andy Hung4b17e882023-07-07 13:47:37 -07007063AsyncCallbackThread::AsyncCallbackThread(
7064 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007065 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007066 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007067 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007068 mDrainSequence(0),
7069 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007070{
7071}
7072
Andy Hung4b17e882023-07-07 13:47:37 -07007073void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007074{
7075 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7076}
7077
Andy Hung4b17e882023-07-07 13:47:37 -07007078bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079{
7080 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007081 uint32_t writeAckSequence;
7082 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007083 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007084
7085 {
Andy Hungb17d24b2023-08-29 14:26:09 -07007086 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007087 while (!((mWriteAckSequence & 1) ||
7088 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007089 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007090 exitPending())) {
Andy Hungb17d24b2023-08-29 14:26:09 -07007091 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007092 }
7093
Eric Laurentbfb1b832013-01-07 09:53:42 -08007094 if (exitPending()) {
7095 break;
7096 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007097 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7098 mWriteAckSequence, mDrainSequence);
7099 writeAckSequence = mWriteAckSequence;
7100 mWriteAckSequence &= ~1;
7101 drainSequence = mDrainSequence;
7102 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007103 asyncError = mAsyncError;
7104 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007105 }
7106 {
Andy Hung4b17e882023-07-07 13:47:37 -07007107 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007108 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007109 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007110 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007111 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007112 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007113 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007114 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007115 if (asyncError) {
7116 playbackThread->onAsyncError();
7117 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007118 }
7119 }
7120 }
7121 return false;
7122}
7123
Andy Hung4b17e882023-07-07 13:47:37 -07007124void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007125{
7126 ALOGV("AsyncCallbackThread::exit");
Andy Hungf8635b62023-08-31 16:13:39 -07007127 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007128 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -07007129 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007130}
7131
Andy Hung4b17e882023-07-07 13:47:37 -07007132void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007133{
Andy Hungf8635b62023-08-31 16:13:39 -07007134 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007135 // bit 0 is cleared
7136 mWriteAckSequence = sequence << 1;
7137}
7138
Andy Hung4b17e882023-07-07 13:47:37 -07007139void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007140{
Andy Hungf8635b62023-08-31 16:13:39 -07007141 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007142 // ignore unexpected callbacks
7143 if (mWriteAckSequence & 2) {
7144 mWriteAckSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007145 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007146 }
7147}
7148
Andy Hung4b17e882023-07-07 13:47:37 -07007149void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007150{
Andy Hungf8635b62023-08-31 16:13:39 -07007151 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007152 // bit 0 is cleared
7153 mDrainSequence = sequence << 1;
7154}
7155
Andy Hung4b17e882023-07-07 13:47:37 -07007156void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007157{
Andy Hungf8635b62023-08-31 16:13:39 -07007158 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007159 // ignore unexpected callbacks
7160 if (mDrainSequence & 2) {
7161 mDrainSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007162 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007163 }
7164}
7165
Andy Hung4b17e882023-07-07 13:47:37 -07007166void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007167{
Andy Hungf8635b62023-08-31 16:13:39 -07007168 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007169 mAsyncError = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07007170 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007171}
7172
Eric Laurentbfb1b832013-01-07 09:53:42 -08007173
7174// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007175
7176/* static */
7177sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007178 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007179 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7180 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007181 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007182}
7183
Andy Hung7535ed92023-07-17 17:05:00 -07007184OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007185 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7186 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007187 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007188 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007189{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007190 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007191 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007192 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007193}
7194
Andy Hung4b17e882023-07-07 13:47:37 -07007195void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007196{
7197 if (mFlushPending || mHwPaused) {
7198 // If a flush is pending or track was paused, just discard buffered data
7199 flushHw_l();
7200 } else {
7201 mMixerStatus = MIXER_DRAIN_ALL;
7202 threadLoop_drain();
7203 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007204 if (mUseAsyncWrite) {
7205 ALOG_ASSERT(mCallbackThread != 0);
7206 mCallbackThread->exit();
7207 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007208 PlaybackThread::threadLoop_exit();
7209}
7210
Andy Hung4b17e882023-07-07 13:47:37 -07007211PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007212 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007213)
7214{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007215 size_t count = mActiveTracks.size();
7216
7217 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007218 bool doHwPause = false;
7219 bool doHwResume = false;
7220
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007221 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007222
Eric Laurentbfb1b832013-01-07 09:53:42 -08007223 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007224 for (const sp<IAfTrack>& t : mActiveTracks) {
7225 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007226#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007227 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007228#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007229 // Only consider last track started for volume and mixer state control.
7230 // In theory an older track could underrun and restart after the new one starts
7231 // but as we only care about the transition phase between two tracks on a
7232 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007233 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007234 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007235
Haynes Mathew George7844f672014-01-15 12:32:55 -08007236 if (track->isInvalid()) {
7237 ALOGW("An invalidated track shouldn't be in active list");
7238 tracksToRemove->add(track);
7239 continue;
7240 }
7241
Andy Hung11e74242023-06-26 19:20:57 -07007242 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007243 ALOGW("An idle track shouldn't be in active list");
7244 continue;
7245 }
7246
Kuowei Li23666472021-01-20 10:23:25 +08007247 if (track->isPausePending()) {
7248 track->pauseAck();
7249 // It is possible a track might have been flushed or stopped.
7250 // Other operations such as flush pending might occur on the next prepare.
7251 if (track->isPausing()) {
7252 track->setPaused();
7253 }
7254 // Always perform pause if last, as an immediate flush will change
7255 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007256 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007257 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007258 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007259 mHwPaused = true;
7260 }
7261 // If we were part way through writing the mixbuffer to
7262 // the HAL we must save this until we resume
7263 // BUG - this will be wrong if a different track is made active,
7264 // in that case we want to discard the pending data in the
7265 // mixbuffer and tell the client to present it again when the
7266 // track is resumed
7267 mPausedWriteLength = mCurrentWriteLength;
7268 mPausedBytesRemaining = mBytesRemaining;
7269 mBytesRemaining = 0; // stop writing
7270 }
7271 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007272 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007273 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007274 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007275 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007276 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007277 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007278 track->flushAck();
7279 if (last) {
7280 mFlushPending = true;
7281 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007282 } else if (track->isResumePending()){
7283 track->resumeAck();
7284 if (last) {
7285 if (mPausedBytesRemaining) {
7286 // Need to continue write that was interrupted
7287 mCurrentWriteLength = mPausedWriteLength;
7288 mBytesRemaining = mPausedBytesRemaining;
7289 mPausedBytesRemaining = 0;
7290 }
7291 if (mHwPaused) {
7292 doHwResume = true;
7293 mHwPaused = false;
7294 // threadLoop_mix() will handle the case that we need to
7295 // resume an interrupted write
7296 }
7297 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007298 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007299
Eric Laurent3df841a2016-07-15 15:15:40 -07007300 mLeftVolFloat = mRightVolFloat = -1.0;
7301
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007302 // Do not handle new data in this iteration even if track->framesReady()
7303 mixerStatus = MIXER_TRACKS_ENABLED;
7304 }
7305 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007306 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007307 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007308 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7309 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007310 if (last) {
7311 // make sure processVolume_l() will apply new volume even if 0
7312 mLeftVolFloat = mRightVolFloat = -1.0;
7313 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007314 }
7315
7316 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007317 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007318 if (previousTrack != 0) {
7319 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007320 // Flush any data still being written from last track
7321 mBytesRemaining = 0;
7322 if (mPausedBytesRemaining) {
7323 // Last track was paused so we also need to flush saved
7324 // mixbuffer state and invalidate track so that it will
7325 // re-submit that unwritten data when it is next resumed
7326 mPausedBytesRemaining = 0;
7327 // Invalidate is a bit drastic - would be more efficient
7328 // to have a flag to tell client that some of the
7329 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007330 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007331 }
7332 // flush data already sent to the DSP if changing audio session as audio
7333 // comes from a different source. Also invalidate previous track to force a
7334 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007335 if (previousTrack->sessionId() != track->sessionId()) {
7336 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007337 }
7338 }
7339 }
7340 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007341 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007342 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007343 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007344 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007345 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007346 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007347 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 mixerStatus = MIXER_TRACKS_READY;
7349 }
7350 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007351 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007352 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007353 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007354 // Hardware buffer can hold a large amount of audio so we must
7355 // wait for all current track's data to drain before we say
7356 // that the track is stopped.
7357 if (mBytesRemaining == 0) {
7358 // Only start draining when all data in mixbuffer
7359 // has been written
7360 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007361 track->setState(IAfTrackBase::STOPPING_2);
7362 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007363 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7364 if (last && !mStandby) {
7365 // do not modify drain sequence if we are already draining. This happens
7366 // when resuming from pause after drain.
7367 if ((mDrainSequence & 1) == 0) {
7368 mSleepTimeUs = 0;
7369 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7370 mixerStatus = MIXER_DRAIN_TRACK;
7371 mDrainSequence += 2;
7372 }
7373 if (mHwPaused) {
7374 // It is possible to move from PAUSED to STOPPING_1 without
7375 // a resume so we must ensure hardware is running
7376 doHwResume = true;
7377 mHwPaused = false;
7378 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007379 }
7380 }
Eric Laurente93cc032016-05-05 10:15:10 -07007381 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007382 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007383 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007384 }
7385 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007386 // Drain has completed or we are in standby, signal presentation complete
7387 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007388 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007389 mOutput->presentationComplete();
7390 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007391 track->reset();
7392 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007393 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007394 if (!mUseAsyncWrite) {
7395 // If we don't get explicit drain notification we must
7396 // register discontinuity regardless of whether this is
7397 // the previous (!last) or the upcoming (last) track
7398 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007399 mTimestampVerifier.discontinuity(
7400 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007401 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007402 }
7403 } else {
7404 // No buffers for this track. Give it a few chances to
7405 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007406 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007407 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007408 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007409 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007410 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007411 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007412 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7413 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007414 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007415 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007416 // it will then automatically call start() when data is available
7417 track->disable();
7418 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007419 } else if (last){
7420 mixerStatus = MIXER_TRACKS_ENABLED;
7421 }
7422 }
7423 }
7424 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007425 if (track->isReady()) { // check ready to prevent premature start.
7426 processVolume_l(track, last);
7427 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007428 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007429
Eric Laurentea0fade2013-10-04 16:23:48 -07007430 // make sure the pause/flush/resume sequence is executed in the right order.
7431 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7432 // before flush and then resume HW. This can happen in case of pause/flush/resume
7433 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007434 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007435 status_t result = mOutput->stream->pause();
7436 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007437 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007438 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007439 if (mFlushPending) {
7440 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007441 }
Eric Laurentfd477972013-10-25 18:10:40 -07007442 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007443 status_t result = mOutput->stream->resume();
7444 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007445 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007446
Eric Laurentbfb1b832013-01-07 09:53:42 -08007447 // remove all the tracks that need to be...
7448 removeTracks_l(*tracksToRemove);
7449
7450 return mixerStatus;
7451}
7452
Eric Laurentbfb1b832013-01-07 09:53:42 -08007453// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007454bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007455{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007456 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7457 mWriteAckSequence, mDrainSequence);
7458 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007459 return true;
7460 }
7461 return false;
7462}
7463
Andy Hung4b17e882023-07-07 13:47:37 -07007464bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007465{
Andy Hungf8635b62023-08-31 16:13:39 -07007466 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007467 return waitingAsyncCallback_l();
7468}
7469
Andy Hung4b17e882023-07-07 13:47:37 -07007470void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007471{
Eric Laurente659ef42014-09-29 13:06:46 -07007472 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007473 // Flush anything still waiting in the mixbuffer
7474 mCurrentWriteLength = 0;
7475 mBytesRemaining = 0;
7476 mPausedWriteLength = 0;
7477 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007478 // reset bytes written count to reflect that DSP buffers are empty after flush.
7479 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007480
Eric Laurentbfb1b832013-01-07 09:53:42 -08007481 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007482 // discard any pending drain or write ack by incrementing sequence
7483 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7484 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007485 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007486 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7487 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007488 }
7489}
7490
Andy Hung4b17e882023-07-07 13:47:37 -07007491void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007492{
Andy Hungf8635b62023-08-31 16:13:39 -07007493 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007494 if (PlaybackThread::invalidateTracks_l(streamType)) {
7495 mFlushPending = true;
7496 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007497}
7498
Andy Hung4b17e882023-07-07 13:47:37 -07007499void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07007500 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007501 if (PlaybackThread::invalidateTracks_l(portIds)) {
7502 mFlushPending = true;
7503 }
7504}
7505
Eric Laurentbfb1b832013-01-07 09:53:42 -08007506// ----------------------------------------------------------------------------
7507
Andy Hung4b17e882023-07-07 13:47:37 -07007508/* static */
7509sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007510 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007511 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007512 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007513}
7514
Andy Hung7535ed92023-07-17 17:05:00 -07007515DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007516 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007517 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007518 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007519 mWaitTimeMs(UINT_MAX)
7520{
7521 addOutputTrack(mainThread);
7522}
7523
Andy Hung4b17e882023-07-07 13:47:37 -07007524DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007525{
7526 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7527 mOutputTracks[i]->destroy();
7528 }
7529}
7530
Andy Hung4b17e882023-07-07 13:47:37 -07007531void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007532{
7533 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007534 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007535 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007536 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007537 if (mMixerBufferValid) {
7538 memset(mMixerBuffer, 0, mMixerBufferSize);
7539 } else {
7540 memset(mSinkBuffer, 0, mSinkBufferSize);
7541 }
Eric Laurent81784c32012-11-19 14:55:58 -08007542 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007543 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007544 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007545 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007546 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007547}
7548
Andy Hung4b17e882023-07-07 13:47:37 -07007549void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007550{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007551 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007552 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007553 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007554 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007555 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007556 }
7557 } else if (mBytesWritten != 0) {
7558 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7559 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007560 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007561 } else {
7562 // flush remaining overflow buffers in output tracks
7563 writeFrames = 0;
7564 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007565 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007566 }
7567}
7568
Andy Hung4b17e882023-07-07 13:47:37 -07007569ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007570{
7571 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007572 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7573
7574 // Consider the first OutputTrack for timestamp and frame counting.
7575
7576 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7577 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7578 // we always claim success.
7579 if (i == 0) {
7580 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7581 ALOGD_IF(correction != 0 && writeFrames != 0,
7582 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7583 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7584 mFramesWritten -= correction;
7585 }
7586
7587 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007588 }
Andy Hungcf10d742020-04-28 15:38:24 -07007589 if (mStandby) {
7590 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007591 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007592 mStandby = false;
7593 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007594 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007595}
7596
Andy Hung4b17e882023-07-07 13:47:37 -07007597void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007598{
7599 // DuplicatingThread implements standby by stopping all tracks
7600 for (size_t i = 0; i < outputTracks.size(); i++) {
7601 outputTracks[i]->stop();
7602 }
7603}
7604
Andy Hung4b17e882023-07-07 13:47:37 -07007605void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007606{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007607 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007608
7609 std::stringstream ss;
7610 const size_t numTracks = mOutputTracks.size();
7611 ss << " " << numTracks << " OutputTracks";
7612 if (numTracks > 0) {
7613 ss << ":";
7614 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007615 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007616 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007617 if (thread.get() != nullptr) {
7618 ss << thread.get() << ", " << thread->id();
7619 } else {
7620 ss << "null";
7621 }
7622 ss << ")";
7623 }
7624 }
7625 ss << "\n";
7626 std::string result = ss.str();
7627 write(fd, result.c_str(), result.size());
7628}
7629
Andy Hung4b17e882023-07-07 13:47:37 -07007630void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007631{
7632 outputTracks = mOutputTracks;
7633}
7634
Andy Hung4b17e882023-07-07 13:47:37 -07007635void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007636{
7637 outputTracks.clear();
7638}
7639
Andy Hung4b17e882023-07-07 13:47:37 -07007640void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007641{
Andy Hungf8635b62023-08-31 16:13:39 -07007642 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007643 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7644 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7645 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7646 const size_t frameCount =
7647 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7648 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7649 // from different OutputTracks and their associated MixerThreads (e.g. one may
7650 // nearly empty and the other may be dropping data).
7651
Svet Ganov33761132021-05-13 22:51:08 +00007652 // TODO b/182392769: use attribution source util, move to server edge
7653 AttributionSourceState attributionSource = AttributionSourceState();
7654 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007655 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007656 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007657 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007658 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007659 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007660 this,
7661 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007662 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007663 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007664 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007665 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007666 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7667 if (status != NO_ERROR) {
7668 ALOGE("addOutputTrack() initCheck failed %d", status);
7669 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007670 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007671 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7672 mOutputTracks.add(outputTrack);
7673 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7674 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007675}
7676
Andy Hung4b17e882023-07-07 13:47:37 -07007677void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007678{
Andy Hungf8635b62023-08-31 16:13:39 -07007679 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007680 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7681 if (mOutputTracks[i]->thread() == thread) {
7682 mOutputTracks[i]->destroy();
7683 mOutputTracks.removeAt(i);
7684 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007685 if (thread->getOutput() == mOutput) {
7686 mOutput = NULL;
7687 }
Eric Laurent81784c32012-11-19 14:55:58 -08007688 return;
7689 }
7690 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007691 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007692}
7693
Andy Hungb17d24b2023-08-29 14:26:09 -07007694// caller must hold mutex()
Andy Hung4b17e882023-07-07 13:47:37 -07007695void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007696{
7697 mWaitTimeMs = UINT_MAX;
7698 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007699 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007700 if (strong != 0) {
7701 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7702 if (waitTimeMs < mWaitTimeMs) {
7703 mWaitTimeMs = waitTimeMs;
7704 }
7705 }
7706 }
7707}
7708
Andy Hung4b17e882023-07-07 13:47:37 -07007709bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007710{
7711 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007712 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007713 if (thread == 0) {
7714 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7715 outputTracks[i].get());
7716 return false;
7717 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007718 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007719 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007720 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007721 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7722 thread.get());
7723 return false;
7724 }
7725 }
7726 return true;
7727}
7728
Andy Hung4b17e882023-07-07 13:47:37 -07007729void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007730 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007731{
Kevin Rocard12381092018-04-11 09:19:59 -07007732 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7733 outputTrack->setMetadatas(metadata.tracks);
7734 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007735}
7736
Andy Hung4b17e882023-07-07 13:47:37 -07007737uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007738{
7739 return (mWaitTimeMs * 1000) / 2;
7740}
7741
Andy Hung4b17e882023-07-07 13:47:37 -07007742void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007743{
7744 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7745 updateWaitTime_l();
7746
7747 MixerThread::cacheParameters_l();
7748}
7749
Eric Laurentb3f315a2021-07-13 15:09:05 +02007750// ----------------------------------------------------------------------------
7751
Andy Hung4b17e882023-07-07 13:47:37 -07007752/* static */
7753sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007754 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007755 AudioStreamOut* output,
7756 audio_io_handle_t id,
7757 bool systemReady,
7758 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007759 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007760}
7761
Andy Hung7535ed92023-07-17 17:05:00 -07007762SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007763 AudioStreamOut* output,
7764 audio_io_handle_t id,
7765 bool systemReady,
7766 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007767 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007768{
7769}
7770
Andy Hung4b17e882023-07-07 13:47:37 -07007771void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007772 // if mSupportedLatencyModes is empty, the HAL stream does not support
7773 // latency mode control and we can exit.
7774 if (mSupportedLatencyModes.empty()) {
7775 return;
7776 }
7777 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7778 if (mSupportedLatencyModes.size() == 1) {
7779 // If the HAL only support one latency mode currently, confirm the choice
7780 latencyMode = mSupportedLatencyModes[0];
7781 } else if (mSupportedLatencyModes.size() > 1) {
7782 // Request low latency if:
7783 // - The low latency mode is requested by the spatializer controller
7784 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7785 // AND
7786 // - At least one active track is spatialized
7787 bool hasSpatializedActiveTrack = false;
7788 for (const auto& track : mActiveTracks) {
7789 if (track->isSpatialized()) {
7790 hasSpatializedActiveTrack = true;
7791 break;
7792 }
7793 }
7794 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7795 latencyMode = AUDIO_LATENCY_MODE_LOW;
7796 }
7797 }
7798
7799 if (latencyMode != mSetLatencyMode) {
7800 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007801 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7802 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007803 if (status == NO_ERROR) {
7804 mSetLatencyMode = latencyMode;
7805 }
7806 }
7807}
7808
Andy Hung4b17e882023-07-07 13:47:37 -07007809status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007810 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7811 return BAD_VALUE;
7812 }
Andy Hungf8635b62023-08-31 16:13:39 -07007813 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007814 mRequestedLatencyMode = mode;
7815 return NO_ERROR;
7816}
7817
Andy Hung4b17e882023-07-07 13:47:37 -07007818void SpatializerThread::checkOutputStageEffects()
Andy Hungf8635b62023-08-31 16:13:39 -07007819NO_THREAD_SAFETY_ANALYSIS
7820// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007821{
7822 bool hasVirtualizer = false;
7823 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007824 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007825 {
Andy Hungf8635b62023-08-31 16:13:39 -07007826 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007827 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007828 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007829 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007830 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7831 }
7832
7833 finalDownMixer = mFinalDownMixer;
7834 mFinalDownMixer.clear();
7835 }
7836
7837 if (hasVirtualizer) {
7838 if (finalDownMixer != nullptr) {
7839 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007840 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007841 }
7842 finalDownMixer.clear();
7843 } else if (!hasDownMixer) {
7844 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07007845 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007846 EFFECT_UIID_DOWNMIX, &descriptors);
7847 if (status != NO_ERROR) {
7848 return;
7849 }
7850 ALOG_ASSERT(!descriptors.empty(),
7851 "%s getDescriptors() returned no error but empty list", __func__);
7852
7853 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7854 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007855 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007856
7857 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7858 ALOGW("%s error creating downmixer %d", __func__, status);
7859 finalDownMixer.clear();
7860 } else {
7861 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007862 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007863 }
7864 }
7865
7866 {
Andy Hungf8635b62023-08-31 16:13:39 -07007867 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007868 mFinalDownMixer = finalDownMixer;
7869 }
7870}
7871
Eric Laurent81784c32012-11-19 14:55:58 -08007872// ----------------------------------------------------------------------------
7873// Record
7874// ----------------------------------------------------------------------------
7875
Andy Hung7535ed92023-07-17 17:05:00 -07007876sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007877 AudioStreamIn* input,
7878 audio_io_handle_t id,
7879 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007880 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07007881}
7882
Andy Hung7535ed92023-07-17 17:05:00 -07007883RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007884 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007885 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007886 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007887 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07007888 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007889 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007890 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007891 mActiveTracks(&this->mLocalLog),
7892 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007893 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007894 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007895 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7896 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007897 // mFastCapture below
7898 , mFastCaptureFutex(0)
7899 // mInputSource
7900 // mPipeSink
7901 // mPipeSource
7902 , mPipeFramesP2(0)
7903 // mPipeMemory
7904 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007905 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007906 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007907{
Glenn Kastend7dca052015-03-05 16:05:54 -08007908 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07007909 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007910
George Burgess IVa8f90c12020-05-14 11:27:19 -07007911 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007912 mIsMsdDevice = strcmp(
7913 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7914 }
7915
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007916 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007917
Andy Hungc8fddf32018-08-08 18:32:37 -07007918 // TODO: We may also match on address as well as device type for
7919 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007920 // TODO: This property should be ensure that only contains one single device type.
7921 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7922 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007923 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7924 : AUDIO_DEVICE_NONE));
7925
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007926 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007927 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007928 size_t numCounterOffers = 0;
7929 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007930#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007931 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007932#else
7933 (void)
7934#endif
7935 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007936 ALOG_ASSERT(index == 0);
7937
7938 // initialize fast capture depending on configuration
7939 bool initFastCapture;
7940 switch (kUseFastCapture) {
7941 case FastCapture_Never:
7942 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007943 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007944 break;
7945 case FastCapture_Always:
7946 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007947 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007948 break;
7949 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007950 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7951 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7952 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7953 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7954 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007955 break;
7956 // case FastCapture_Dynamic:
7957 }
7958
7959 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007960 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007961 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007962 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7963 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007964 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007965 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007966 const sp<MemoryDealer> roHeap(readOnlyHeap());
7967 sp<IMemory> pipeMemory;
7968 if ((roHeap == 0) ||
7969 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007970 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007971 ALOGE("not enough memory for pipe buffer size=%zu; "
7972 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7973 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7974 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007975 goto failed;
7976 }
7977 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7978 memset(pipeBuffer, 0, pipeSize);
7979 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007980 const NBAIO_Format offersFast[1] = {format};
7981 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007982 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007983 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007984 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007985 mPipeSink = pipe;
7986 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007987 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007988 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007989 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007990 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007991 mPipeSource = pipeReader;
7992 mPipeFramesP2 = pipeFramesP2;
7993 mPipeMemory = pipeMemory;
7994
7995 // create fast capture
7996 mFastCapture = new FastCapture();
7997 FastCaptureStateQueue *sq = mFastCapture->sq();
7998#ifdef STATE_QUEUE_DUMP
7999 // FIXME
8000#endif
8001 FastCaptureState *state = sq->begin();
8002 state->mCblk = NULL;
8003 state->mInputSource = mInputSource.get();
8004 state->mInputSourceGen++;
8005 state->mPipeSink = pipe;
8006 state->mPipeSinkGen++;
8007 state->mFrameCount = mFrameCount;
8008 state->mCommand = FastCaptureState::COLD_IDLE;
8009 // already done in constructor initialization list
8010 //mFastCaptureFutex = 0;
8011 state->mColdFutexAddr = &mFastCaptureFutex;
8012 state->mColdGen++;
8013 state->mDumpState = &mFastCaptureDumpState;
8014#ifdef TEE_SINK
8015 // FIXME
8016#endif
Andy Hung7535ed92023-07-17 17:05:00 -07008017 mFastCaptureNBLogWriter =
8018 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008019 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8020 sq->end();
8021 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8022
8023 // start the fast capture
8024 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8025 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008026 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008027 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008028#ifdef AUDIO_WATCHDOG
8029 // FIXME
8030#endif
8031
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008032 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008033 }
Andy Hung8946a282018-04-19 20:04:56 -07008034#ifdef TEE_SINK
8035 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8036 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8037#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008038failed: ;
8039
8040 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008041}
8042
Andy Hung4b17e882023-07-07 13:47:37 -07008043RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008044{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008045 if (mFastCapture != 0) {
8046 FastCaptureStateQueue *sq = mFastCapture->sq();
8047 FastCaptureState *state = sq->begin();
8048 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8049 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8050 if (old == -1) {
8051 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8052 }
8053 }
8054 state->mCommand = FastCaptureState::EXIT;
8055 sq->end();
8056 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8057 mFastCapture->join();
8058 mFastCapture.clear();
8059 }
Andy Hung7535ed92023-07-17 17:05:00 -07008060 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8061 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008062 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008063}
8064
Andy Hung4b17e882023-07-07 13:47:37 -07008065void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008066{
Glenn Kastend7dca052015-03-05 16:05:54 -08008067 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008068}
8069
Andy Hung4b17e882023-07-07 13:47:37 -07008070void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008071{
8072 ALOGV(" preExit()");
Andy Hungf8635b62023-08-31 16:13:39 -07008073 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008074 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008075 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008076 track->invalidate();
8077 }
8078 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008079 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008080}
8081
Andy Hung4b17e882023-07-07 13:47:37 -07008082bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008083{
Eric Laurent81784c32012-11-19 14:55:58 -08008084 nsecs_t lastWarning = 0;
8085
8086 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008087
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008088reacquire_wakelock:
Andy Hung11e74242023-06-26 19:20:57 -07008089 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008090 {
Andy Hungf8635b62023-08-31 16:13:39 -07008091 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008092 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008093 }
8094
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008095 // used to request a deferred sleep, to be executed later while mutex is unlocked
8096 uint32_t sleepUs = 0;
8097
Andy Hung446f4df2019-02-21 12:26:41 -08008098 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8099
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008100 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008101 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008102 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008103
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008104 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008105 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008106
Glenn Kasten735f45f2014-08-18 15:51:59 -07008107 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008108 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008109
Glenn Kasten735f45f2014-08-18 15:51:59 -07008110 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008111 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008112
Eric Laurent33403f02020-05-29 18:35:06 -07008113 bool silenceFastCapture = false;
8114
Andy Hungb17d24b2023-08-29 14:26:09 -07008115 { // scope for mutex()
8116 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008117
Eric Laurent021cf962014-05-13 10:18:14 -07008118 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008119
Eric Laurent000a4192014-01-29 15:17:32 -08008120 // check exitPending here because checkForNewParameters_l() and
Andy Hungb17d24b2023-08-29 14:26:09 -07008121 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008122 if (exitPending()) {
8123 break;
8124 }
8125
Eric Laurent5c25d562016-07-13 17:17:45 -07008126 // sleep with mutex unlocked
8127 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008128 ATRACE_BEGIN("sleepC");
Andy Hungb17d24b2023-08-29 14:26:09 -07008129 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008130 ATRACE_END();
8131 sleepUs = 0;
8132 continue;
8133 }
8134
Glenn Kasten2b806402013-11-20 16:37:38 -08008135 // if no active track(s), then standby and release wakelock
8136 size_t size = mActiveTracks.size();
8137 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008138 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008139 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008140 releaseWakeLock_l();
8141 ALOGV("RecordThread: loop stopping");
8142 // go to sleep
Andy Hungb17d24b2023-08-29 14:26:09 -07008143 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008144 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008145 goto reacquire_wakelock;
8146 }
8147
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008148 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008149 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008150 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008151
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008152 activeTrack = mActiveTracks[i];
8153 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008154 if (activeTrack->isFastTrack()) {
8155 ALOG_ASSERT(fastTrackToRemove == 0);
8156 fastTrackToRemove = activeTrack;
8157 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008158 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008159 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008160 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008161 continue;
8162 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008163
Andy Hung11e74242023-06-26 19:20:57 -07008164 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008165 switch (activeTrackState) {
8166
Andy Hung11e74242023-06-26 19:20:57 -07008167 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008168 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008169 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008170 doBroadcast = true;
8171 size--;
8172 continue;
8173
Andy Hung11e74242023-06-26 19:20:57 -07008174 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008175 sleepUs = 10000;
8176 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008177 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008178 continue;
8179
Andy Hung11e74242023-06-26 19:20:57 -07008180 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008181 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008182 if (mStandby) {
8183 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008184 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008185 mStandby = false;
8186 }
Andy Hung11e74242023-06-26 19:20:57 -07008187 activeTrack->setState(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::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008192 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008193 break;
8194
Andy Hung11e74242023-06-26 19:20:57 -07008195 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8196 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8197 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008198 default:
Andy Hungce685402018-10-05 17:23:27 -07008199 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8200 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008201 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008202
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008203 if (activeTrack->isFastTrack()) {
8204 ALOG_ASSERT(!mFastTrackAvail);
8205 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008206 // if the active fast track is silenced either:
8207 // 1) silence the whole capture from fast capture buffer if this is
8208 // the only active track
8209 // 2) invalidate this track: this will cause the client to reconnect and possibly
8210 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008211 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008212 if (activeTrack->isSilenced()) {
8213 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008214 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008215 } else {
8216 silenceFastCapture = true;
8217 }
8218 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008219 // Invalidate fast tracks if access to audio history is required as this is not
8220 // possible with fast tracks. Once the fast track has been invalidated, no new
8221 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8222 if (mMaxSharedAudioHistoryMs != 0) {
8223 invalidate = true;
8224 }
8225 if (invalidate) {
8226 activeTrack->invalidate();
8227 ALOG_ASSERT(fastTrackToRemove == 0);
8228 fastTrackToRemove = activeTrack;
8229 removeTrack_l(activeTrack);
8230 mActiveTracks.remove(activeTrack);
8231 size--;
8232 continue;
8233 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008234 fastTrack = activeTrack;
8235 }
Eric Laurent33403f02020-05-29 18:35:06 -07008236
8237 activeTracks.add(activeTrack);
8238 i++;
8239
Glenn Kasten9e982352013-08-14 14:39:50 -07008240 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008241
Andy Hungdae27702016-10-31 14:01:16 -07008242 mActiveTracks.updatePowerState(this);
8243
Kevin Rocard069c2712018-03-29 19:09:14 -07008244 updateMetadata_l();
8245
Eric Laurent5c25d562016-07-13 17:17:45 -07008246 if (allStopped) {
8247 standbyIfNotAlreadyInStandby();
8248 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008249 if (doBroadcast) {
Andy Hungb17d24b2023-08-29 14:26:09 -07008250 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008251 }
8252
8253 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008254 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008255 if (sleepUs == 0) {
8256 sleepUs = kRecordThreadSleepUs;
8257 }
8258 continue;
8259 }
8260 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008261
Eric Laurent81784c32012-11-19 14:55:58 -08008262 lockEffectChains_l(effectChains);
8263 }
8264
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008265 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008266
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008267 size_t size = effectChains.size();
8268 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008269 // thread mutex is not locked, but effect chain is locked
8270 effectChains[i]->process_l();
8271 }
8272
Glenn Kasten735f45f2014-08-18 15:51:59 -07008273 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008274 if (mFastCapture != 0) {
8275 FastCaptureStateQueue *sq = mFastCapture->sq();
8276 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008277 bool didModify = false;
8278 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008279 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8280 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8281 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8282 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8283 if (old == -1) {
8284 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8285 }
8286 }
8287 state->mCommand = FastCaptureState::READ_WRITE;
8288#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008289 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008290 FastThreadDumpState::kSamplingNforLowRamDevice :
8291 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008292#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008293 didModify = true;
8294 }
8295 audio_track_cblk_t *cblkOld = state->mCblk;
8296 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8297 if (cblkNew != cblkOld) {
8298 state->mCblk = cblkNew;
8299 // block until acked if removing a fast track
8300 if (cblkOld != NULL) {
8301 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8302 }
8303 didModify = true;
8304 }
jiabin01c8f562018-07-19 17:47:28 -07008305 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8306 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8307 if (state->mFastPatchRecordBufferProvider != abp) {
8308 state->mFastPatchRecordBufferProvider = abp;
8309 state->mFastPatchRecordFormat = fastTrack == 0 ?
8310 AUDIO_FORMAT_INVALID : fastTrack->format();
8311 didModify = true;
8312 }
Eric Laurent33403f02020-05-29 18:35:06 -07008313 if (state->mSilenceCapture != silenceFastCapture) {
8314 state->mSilenceCapture = silenceFastCapture;
8315 didModify = true;
8316 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008317 sq->end(didModify);
8318 if (didModify) {
8319 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008320#if 0
8321 if (kUseFastCapture == FastCapture_Dynamic) {
8322 mNormalSource = mPipeSource;
8323 }
8324#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008325 }
8326 }
8327
Glenn Kasten735f45f2014-08-18 15:51:59 -07008328 // now run the fast track destructor with thread mutex unlocked
8329 fastTrackToRemove.clear();
8330
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008331 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8332 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8333 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8334 // If destination is non-contiguous, first read past the nominal end of buffer, then
8335 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008336
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008337 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008338 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008339 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008340
8341 // If an NBAIO source is present, use it to read the normal capture's data
8342 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008343 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008344
8345 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8346 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8347 // we immediately retry the read() to get data and prevent another overflow.
8348 for (int retries = 0; retries <= 2; ++retries) {
8349 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8350 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8351 framesToRead);
8352 if (framesRead != OVERRUN) break;
8353 }
8354
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008355 const ssize_t availableToRead = mPipeSource->availableToRead();
8356 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008357 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008358 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008359 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8360 "more frames to read than fifo size, %zd > %zu",
8361 availableToRead, mPipeFramesP2);
8362 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8363 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8364 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8365 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008366 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8367 }
8368 if (framesRead < 0) {
8369 status_t status = (status_t) framesRead;
8370 switch (status) {
8371 case OVERRUN:
8372 ALOGW("overrun on read from pipe");
8373 framesRead = 0;
8374 break;
8375 case NEGOTIATE:
8376 ALOGE("re-negotiation is needed");
8377 framesRead = -1; // Will cause an attempt to recover.
8378 break;
8379 default:
8380 ALOGE("unknown error %d on read from pipe", status);
8381 break;
8382 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008383 }
8384 // otherwise use the HAL / AudioStreamIn directly
8385 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008386 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008387 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008388 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008389 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008390 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008391 if (result < 0) {
8392 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008393 } else {
8394 framesRead = bytesRead / mFrameSize;
8395 }
8396 }
8397
Andy Hung446f4df2019-02-21 12:26:41 -08008398 const int64_t lastIoEndNs = systemTime(); // end IO timing
8399
Andy Hung3f0c9022016-01-15 17:49:46 -08008400 // Update server timestamp with server stats
8401 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008402 if (framesRead >= 0) {
8403 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8404 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8405 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008406
8407 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008408 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008409 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008410 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008411 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8412 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8413 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008414 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008415 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8416
8417 mTimestampVerifier.add(position, time, mSampleRate);
8418
8419 // Correct timestamps
8420 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008421 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008422 id(), (long long)time, (long long)position);
8423 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8424 position = correctedTimestamp.mFrames;
8425 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008426 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008427 id(), (long long)time, (long long)position);
8428 }
8429
Andy Hung3f0c9022016-01-15 17:49:46 -08008430 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8431 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8432 // Note: In general record buffers should tend to be empty in
8433 // a properly running pipeline.
8434 //
8435 // Also, it is not advantageous to call get_presentation_position during the read
8436 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008437 } else {
8438 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008439 }
8440 }
Andy Hunge6c37112019-02-26 17:38:10 -08008441
8442 // From the timestamp, input read latency is negative output write latency.
8443 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008444 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008445 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8446 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8447 mLatencyMs.add(latencyMs);
8448 }
8449
Andy Hung3f0c9022016-01-15 17:49:46 -08008450 // Use this to track timestamp information
8451 // ALOGD("%s", mTimestamp.toString().c_str());
8452
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008453 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008454 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008455 // Force input into standby so that it tries to recover at next read attempt
8456 inputStandBy();
8457 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008458 }
8459 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008460 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008461 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008462 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008463 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008464
Andy Hung8946a282018-04-19 20:04:56 -07008465#ifdef TEE_SINK
8466 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8467#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008468 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008469 {
8470 size_t part1 = mRsmpInFramesP2 - rear;
8471 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008472 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008473 (framesRead - part1) * mFrameSize);
8474 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008475 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008476 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008477
8478 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008479
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008480 // loop over each active track
8481 for (size_t i = 0; i < size; i++) {
8482 activeTrack = activeTracks[i];
8483
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008484 // skip fast tracks, as those are handled directly by FastCapture
8485 if (activeTrack->isFastTrack()) {
8486 continue;
8487 }
8488
Andy Hung73c02e42015-03-29 01:13:58 -07008489 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008490 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8491
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008492 enum {
8493 OVERRUN_UNKNOWN,
8494 OVERRUN_TRUE,
8495 OVERRUN_FALSE
8496 } overrun = OVERRUN_UNKNOWN;
8497
8498 // loop over getNextBuffer to handle circular sink
8499 for (;;) {
8500
Andy Hung11e74242023-06-26 19:20:57 -07008501 activeTrack->sinkBuffer().frameCount = ~0;
8502 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8503 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008504 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8505
Andy Hung73c02e42015-03-29 01:13:58 -07008506 // check available frames and handle overrun conditions
8507 // if the record track isn't draining fast enough.
8508 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008509 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008510 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008511 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008512 overrun = OVERRUN_TRUE;
8513 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008514 if (framesOut == 0 || framesIn == 0) {
8515 break;
8516 }
8517
Andy Hung6770c6f2015-04-07 13:43:36 -07008518 // Don't allow framesOut to be larger than what is possible with resampling
8519 // from framesIn.
8520 // This isn't strictly necessary but helps limit buffer resizing in
8521 // RecordBufferConverter. TODO: remove when no longer needed.
8522 framesOut = min(framesOut,
8523 destinationFramesPossible(
Andy Hung11e74242023-06-26 19:20:57 -07008524 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008525
8526 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008527 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008528 // straight from RecordThread buffer to RecordTrack buffer.
8529 AudioBufferProvider::Buffer buffer;
8530 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008531 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008532 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008533 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008534 ALOGV_IF(buffer.frameCount != framesOut,
8535 "%s() read less than expected (%zu vs %zu)",
8536 __func__, buffer.frameCount, framesOut);
8537 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008538 memcpy(activeTrack->sinkBuffer().raw,
8539 buffer.raw, buffer.frameCount * mFrameSize);
8540 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008541 } else {
8542 framesOut = 0;
8543 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008544 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008545 }
8546 } else {
8547 // process frames from the RecordThread buffer provider to the RecordTrack
8548 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008549 framesOut = activeTrack->recordBufferConverter()->convert(
8550 activeTrack->sinkBuffer().raw,
8551 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008552 framesOut);
8553 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008554
8555 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8556 overrun = OVERRUN_FALSE;
8557 }
8558
Andy Hung93bb5732023-05-04 21:16:34 -07008559 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8560 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008561 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008562 if (framesToDrop == 0) {
8563 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008564 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008565 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008566 // Sanitize before releasing if the track has no access to the source data
8567 // An idle UID receives silence from non virtual devices until active
8568 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008569 memset(activeTrack->sinkBuffer().raw,
8570 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008571 }
Andy Hung11e74242023-06-26 19:20:57 -07008572 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008573 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008574 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008575 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008576 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008577 }
8578 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008579
8580 switch (overrun) {
8581 case OVERRUN_TRUE:
8582 // client isn't retrieving buffers fast enough
8583 if (!activeTrack->setOverflow()) {
8584 nsecs_t now = systemTime();
8585 // FIXME should lastWarning per track?
8586 if ((now - lastWarning) > kWarningThrottleNs) {
8587 ALOGW("RecordThread: buffer overflow");
8588 lastWarning = now;
8589 }
8590 }
8591 break;
8592 case OVERRUN_FALSE:
8593 activeTrack->clearOverflow();
8594 break;
8595 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008596 break;
8597 }
8598
Andy Hung3f0c9022016-01-15 17:49:46 -08008599 // update frame information and push timestamp out
8600 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008601 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008602 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8603 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008604 }
8605
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008606unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008607 // enable changes in effect chain
8608 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008609 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008610 if (audio_has_proportional_frames(mFormat)
8611 && loopCount == lastLoopCountRead + 1) {
8612 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8613 const double jitterMs =
8614 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8615 {framesRead, readPeriodNs},
8616 {0, 0} /* lastTimestamp */, mSampleRate);
8617 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8618
Andy Hungf8635b62023-08-31 16:13:39 -07008619 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008620 mIoJitterMs.add(jitterMs);
8621 mProcessTimeMs.add(processMs);
8622 }
8623 // update timing info.
8624 mLastIoBeginNs = lastIoBeginNs;
8625 mLastIoEndNs = lastIoEndNs;
8626 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008627 }
8628
Glenn Kasten93e471f2013-08-19 08:40:07 -07008629 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008630
8631 {
Andy Hungf8635b62023-08-31 16:13:39 -07008632 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008633 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008634 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008635 track->invalidate();
8636 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008637 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008638 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008639 }
8640
8641 releaseWakeLock();
8642
8643 ALOGV("RecordThread %p exiting", this);
8644 return false;
8645}
8646
Andy Hung4b17e882023-07-07 13:47:37 -07008647void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008648{
8649 if (!mStandby) {
8650 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008651 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008652 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008653 mStandby = true;
8654 }
8655}
8656
Andy Hung4b17e882023-07-07 13:47:37 -07008657void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008658{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008659 // Idle the fast capture if it's currently running
8660 if (mFastCapture != 0) {
8661 FastCaptureStateQueue *sq = mFastCapture->sq();
8662 FastCaptureState *state = sq->begin();
8663 if (!(state->mCommand & FastCaptureState::IDLE)) {
8664 state->mCommand = FastCaptureState::COLD_IDLE;
8665 state->mColdFutexAddr = &mFastCaptureFutex;
8666 state->mColdGen++;
8667 mFastCaptureFutex = 0;
8668 sq->end();
8669 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8670 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8671#if 0
8672 if (kUseFastCapture == FastCapture_Dynamic) {
8673 // FIXME
8674 }
8675#endif
8676#ifdef AUDIO_WATCHDOG
8677 // FIXME
8678#endif
8679 } else {
8680 sq->end(false /*didModify*/);
8681 }
8682 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008683 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008684 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008685
8686 // If going into standby, flush the pipe source.
8687 if (mPipeSource.get() != nullptr) {
8688 const ssize_t flushed = mPipeSource->flush();
8689 if (flushed > 0) {
8690 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8691 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8692 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8693 }
8694 }
Eric Laurent81784c32012-11-19 14:55:58 -08008695}
8696
Andy Hungb17d24b2023-08-29 14:26:09 -07008697// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07008698sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008699 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008700 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008701 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008702 audio_format_t format,
8703 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008704 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008705 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008706 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008707 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008708 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008709 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008710 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008711 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008712 audio_port_handle_t portId,
8713 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008714{
Glenn Kasten74935e42013-12-19 08:56:45 -08008715 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008716 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008717 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008718 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008719 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008720 audio_input_flags_t requestedFlags = *flags;
8721 uint32_t sampleRate;
8722
8723 lStatus = initCheck();
8724 if (lStatus != NO_ERROR) {
8725 ALOGE("createRecordTrack_l() audio driver not initialized");
8726 goto Exit;
8727 }
8728
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008729 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8730 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8731 lStatus = BAD_VALUE;
8732 goto Exit;
8733 }
8734
Eric Laurentec376dc2021-04-08 20:41:22 +02008735 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008736 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008737 lStatus = PERMISSION_DENIED;
8738 goto Exit;
8739 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008740 if (maxSharedAudioHistoryMs < 0
Andy Hung409572b2023-07-19 12:47:35 -07008741 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008742 lStatus = BAD_VALUE;
8743 goto Exit;
8744 }
8745 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008746 if (*pSampleRate == 0) {
8747 *pSampleRate = mSampleRate;
8748 }
8749 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008750
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008751 // special case for FAST flag considered OK if fast capture is present and access to
8752 // audio history is not required
8753 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008754 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8755 }
8756
Eric Laurentf14db3c2017-12-08 14:20:36 -08008757 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008758 if ((*flags & inputFlags) != *flags) {
8759 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8760 " input flags (%08x)",
8761 *flags, inputFlags);
8762 *flags = (audio_input_flags_t)(*flags & inputFlags);
8763 }
Eric Laurent81784c32012-11-19 14:55:58 -08008764
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008765 // client expresses a preference for FAST and no access to audio history,
8766 // but we get the final say
8767 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008768 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008769 // we formerly checked for a callback handler (non-0 tid),
8770 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008771 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008772 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008773 // Frame count is not specified (0), or is less than or equal the pipe depth.
8774 // It is OK to provide a higher capacity than requested.
8775 // We will force it to mPipeFramesP2 below.
8776 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008777 // PCM data
8778 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008779 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008780 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008781 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008782 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008783 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008784 hasFastCapture() &&
8785 // there are sufficient fast track slots available
8786 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008787 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008788 // check compatibility with audio effects.
Andy Hungf8635b62023-08-31 16:13:39 -07008789 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008790 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008791 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008792 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008793 audio_input_flags_t old = *flags;
8794 chain->checkInputFlagCompatibility(flags);
8795 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008796 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8797 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008798 }
8799 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008800 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008801 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8802 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008803 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008804 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8805 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008806 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008807 this, frameCount, mFrameCount, mPipeFramesP2,
8808 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008809 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008810 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008811 }
8812 }
8813
Eric Laurentf14db3c2017-12-08 14:20:36 -08008814 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8815 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8816 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8817 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8818 lStatus = BAD_TYPE;
8819 goto Exit;
8820 }
8821
Glenn Kasten74105912014-07-03 12:28:53 -07008822 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008823 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008824 // fast track: frame count is exactly the pipe depth
8825 frameCount = mPipeFramesP2;
8826 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008827 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008828 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008829 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8830 // or 20 ms if there is a fast capture
8831 // TODO This could be a roundupRatio inline, and const
8832 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8833 * sampleRate + mSampleRate - 1) / mSampleRate;
8834 // minimum number of notification periods is at least kMinNotifications,
8835 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8836 static const size_t kMinNotifications = 3;
8837 static const uint32_t kMinMs = 30;
8838 // TODO This could be a roundupRatio inline
8839 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8840 // TODO This could be a roundupRatio inline
8841 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8842 maxNotificationFrames;
8843 const size_t minFrameCount = maxNotificationFrames *
8844 max(kMinNotifications, minNotificationsByMs);
8845 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008846 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8847 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008848 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008849 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008850 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008851 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008852
Andy Hungb17d24b2023-08-29 14:26:09 -07008853 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07008854 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008855 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008856 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008857 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008858 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008859 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008860 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008861 }
Eric Laurent81784c32012-11-19 14:55:58 -08008862
Andy Hung11e74242023-06-26 19:20:57 -07008863 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008864 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008865 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07008866 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008867 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008868
Glenn Kasten03003332013-08-06 15:40:54 -07008869 lStatus = track->initCheck();
8870 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008871 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008872 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008873 goto Exit;
8874 }
8875 mTracks.add(track);
8876
Eric Laurent05067782016-06-01 18:27:28 -07008877 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008878 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8879 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8880 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008881 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008882 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008883
8884 if (maxSharedAudioHistoryMs != 0) {
8885 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8886 }
Eric Laurent81784c32012-11-19 14:55:58 -08008887 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008888
Eric Laurent81784c32012-11-19 14:55:58 -08008889 lStatus = NO_ERROR;
8890
8891Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008892 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008893 return track;
8894}
8895
Andy Hung4b17e882023-07-07 13:47:37 -07008896status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008897 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008898 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008899{
8900 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8901 sp<ThreadBase> strongMe = this;
8902 status_t status = NO_ERROR;
8903
8904 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008905 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008906 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07008907 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07008908 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008909 event, triggerSession,
8910 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008911 }
8912
8913 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008914 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hungf8635b62023-08-31 16:13:39 -07008915 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07008916 if (recordTrack->isInvalid()) {
8917 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008918 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8919 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008920 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008921 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008922 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008923 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8924 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008925 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07008926 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008927 } else {
Andy Hung11e74242023-06-26 19:20:57 -07008928 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008929 }
8930 return status;
8931 }
8932
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008933 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8934 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8935 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07008936 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008937 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008938 if (recordTrack->isExternalTrack()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07008939 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008940 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07008941 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07008942 if (recordTrack->isInvalid()) {
8943 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07008944 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8945 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008946 // STARTING_2 forces destroy to call stopInput.
8947 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008948 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8949 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008950 }
Andy Hung11e74242023-06-26 19:20:57 -07008951 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008952 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07008953 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008954 // Someone else has changed state, let them take over,
8955 // leave mState in the new state.
8956 recordTrack->clearSyncStartEvent();
8957 return INVALID_OPERATION;
8958 }
8959 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008960 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008961 ALOGW("%s(%d): startInput failed, status %d",
8962 __func__, recordTrack->id(), status);
8963 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8964 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008965 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008966 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008967 return status;
8968 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008969 sendIoConfigEvent_l(
8970 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008971 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008972
8973 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8974
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008975 // Catch up with current buffer indices if thread is already running.
8976 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8977 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8978 // see previously buffered data before it called start(), but with greater risk of overrun.
8979
Andy Hung11e74242023-06-26 19:20:57 -07008980 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008981 if (!recordTrack->isDirect()) {
8982 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07008983 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008984 }
Andy Hung11e74242023-06-26 19:20:57 -07008985 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008986 // signal thread to start
Andy Hungb17d24b2023-08-29 14:26:09 -07008987 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008988 return status;
8989 }
Eric Laurent81784c32012-11-19 14:55:58 -08008990}
8991
Andy Hung4b17e882023-07-07 13:47:37 -07008992void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008993{
Andy Hung4b17e882023-07-07 13:47:37 -07008994 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008995
8996 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07008997 sp<IAfTrackBase> ptr =
8998 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8999 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07009000 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07009001 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009002 }
Eric Laurent81784c32012-11-19 14:55:58 -08009003 }
9004}
9005
Andy Hung4b17e882023-07-07 13:47:37 -07009006bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009007 ALOGV("RecordThread::stop");
Andy Hungb17d24b2023-08-29 14:26:09 -07009008 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009009 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07009010 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009011 return false;
9012 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009013 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07009014 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009015
Andy Hungabfab202019-03-07 19:45:54 -08009016 // NOTE: Waiting here is important to keep stop synchronous.
9017 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07009018 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009019 mWaitWorkCV.notify_all(); // signal thread to stop
9020 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009021 }
Andy Hungce685402018-10-05 17:23:27 -07009022
Andy Hung11e74242023-06-26 19:20:57 -07009023 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009024 ALOGV("Record stopped OK");
9025 return true;
9026 }
Andy Hungce685402018-10-05 17:23:27 -07009027
9028 // don't handle anything - we've been invalidated or restarted and in a different state
9029 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07009030 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009031 return false;
9032}
9033
Andy Hung4b17e882023-07-07 13:47:37 -07009034bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009035{
9036 return false;
9037}
9038
Andy Hung4b17e882023-07-07 13:47:37 -07009039status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009040{
9041#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9042 if (!isValidSyncEvent(event)) {
9043 return BAD_VALUE;
9044 }
9045
Glenn Kastend848eb42016-03-08 13:42:11 -08009046 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009047 status_t ret = NAME_NOT_FOUND;
9048
Andy Hungf8635b62023-08-31 16:13:39 -07009049 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009050
9051 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009052 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009053 if (eventSession == track->sessionId()) {
9054 (void) track->setSyncEvent(event);
9055 ret = NO_ERROR;
9056 }
9057 }
9058 return ret;
9059#else
9060 return BAD_VALUE;
9061#endif
9062}
9063
Andy Hung4b17e882023-07-07 13:47:37 -07009064status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07009065 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009066{
9067 ALOGV("RecordThread::getActiveMicrophones");
Andy Hungf8635b62023-08-31 16:13:39 -07009068 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009069 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009070 return NO_INIT;
9071 }
jiabin9ff780e2018-03-19 18:19:52 -07009072 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9073 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009074}
9075
Andy Hung4b17e882023-07-07 13:47:37 -07009076status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009077 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009078{
Paul McLean12340082019-03-19 09:35:05 -06009079 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hungf8635b62023-08-31 16:13:39 -07009080 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009081 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009082 return NO_INIT;
9083 }
Paul McLean12340082019-03-19 09:35:05 -06009084 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009085}
9086
Andy Hung4b17e882023-07-07 13:47:37 -07009087status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009088{
Paul McLean12340082019-03-19 09:35:05 -06009089 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hungf8635b62023-08-31 16:13:39 -07009090 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009091 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009092 return NO_INIT;
9093 }
Paul McLean12340082019-03-19 09:35:05 -06009094 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009095}
9096
Andy Hung4b17e882023-07-07 13:47:37 -07009097status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009098 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9099 int64_t sharedAudioStartMs) {
Andy Hungf8635b62023-08-31 16:13:39 -07009100 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009101 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9102}
9103
Andy Hung4b17e882023-07-07 13:47:37 -07009104status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009105 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9106 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009107
Eric Laurentec376dc2021-04-08 20:41:22 +02009108 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9109 return BAD_VALUE;
9110 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009111
9112 if (sharedAudioStartMs < 0
9113 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009114 return BAD_VALUE;
9115 }
9116
Eric Laurent2407ce32021-04-26 14:56:03 +02009117 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9118 // As we cannot detect more than one wraparound, only accept values up current write position
9119 // after one wraparound
9120 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9121 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009122 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009123 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9124 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009125 // Bring the start frame position within the input buffer to match the documented
9126 // "best effort" behavior of the API.
9127 if (sharedOffset < 0) {
9128 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009129 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009130 sharedAudioStartFrames =
9131 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009132 }
9133
Eric Laurentec376dc2021-04-08 20:41:22 +02009134 mSharedAudioPackageName = sharedAudioPackageName;
9135 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009136 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009137 } else {
9138 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009139 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009140 }
9141 return NO_ERROR;
9142}
9143
Andy Hung4b17e882023-07-07 13:47:37 -07009144void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009145 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9146 mSharedAudioStartFrames = -1;
9147 mSharedAudioPackageName = "";
9148}
9149
Andy Hung4b17e882023-07-07 13:47:37 -07009150ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009151{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009152 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009153 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009154 }
9155 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009156 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009157 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009158 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009159 }
9160 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009161 MetadataUpdate change;
9162 change.recordMetadataUpdate = metadata.tracks;
9163 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009164}
9165
Andy Hungb17d24b2023-08-29 14:26:09 -07009166// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07009167void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009168{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009169 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009170 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009171
Eric Laurent81784c32012-11-19 14:55:58 -08009172 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009173 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009174 removeTrack_l(track);
9175 }
9176}
9177
Andy Hung4b17e882023-07-07 13:47:37 -07009178void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009179{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009180 String8 result;
9181 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009182 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009183
Eric Laurent81784c32012-11-19 14:55:58 -08009184 mTracks.remove(track);
9185 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009186 if (track->isFastTrack()) {
9187 ALOG_ASSERT(!mFastTrackAvail);
9188 mFastTrackAvail = true;
9189 }
Eric Laurent81784c32012-11-19 14:55:58 -08009190}
9191
Andy Hung4b17e882023-07-07 13:47:37 -07009192void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009193{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009194 AudioStreamIn *input = mInput;
9195 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9196 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009197 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009198 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009199 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009200 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009201 }
Andy Hungbfa64962017-06-12 14:43:19 -07009202
9203 if (input != nullptr) {
9204 dprintf(fd, " Hal stream dump:\n");
9205 (void)input->stream->dump(fd);
9206 }
9207
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009208 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009209 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009210
Glenn Kasten2f90c512015-12-02 11:40:09 -08009211 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9212 // while we are dumping it. It may be inconsistent, but it won't mutate!
9213 // This is a large object so we place it on the heap.
9214 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009215 const std::unique_ptr<FastCaptureDumpState> copy =
9216 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009217 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009218}
9219
Andy Hung4b17e882023-07-07 13:47:37 -07009220void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009221{
Eric Laurent81784c32012-11-19 14:55:58 -08009222 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009223 size_t numtracks = mTracks.size();
9224 size_t numactive = mActiveTracks.size();
9225 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009226 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009227 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009228 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009229 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009230 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009231 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009232 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009233 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009234 if (track != 0) {
9235 bool active = mActiveTracks.indexOf(track) >= 0;
9236 if (active) {
9237 numactiveseen++;
9238 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009239 result.append(prefix);
9240 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009241 }
Eric Laurent81784c32012-11-19 14:55:58 -08009242 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009243 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009244 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009245 }
9246
Marco Nelissenb2208842014-02-07 14:00:50 -08009247 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009248 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009249 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009250 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009251 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009252 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009253 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009254 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009255 result.append(prefix);
9256 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009257 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009258 }
Eric Laurent81784c32012-11-19 14:55:58 -08009259
9260 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009261 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009262}
9263
Andy Hung4b17e882023-07-07 13:47:37 -07009264void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009265{
Andy Hungf8635b62023-08-31 16:13:39 -07009266 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009267 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009268 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009269 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009270 track->setSilenced(silenced);
9271 }
9272 }
9273}
Andy Hung73c02e42015-03-29 01:13:58 -07009274
Andy Hung11e74242023-06-26 19:20:57 -07009275void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009276{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009277 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009278 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009279 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009280 const int32_t rear = recordThread->mRsmpInRear;
9281 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009282 if (mRecordTrack->startFrames() >= 0) {
9283 int32_t startFrames = mRecordTrack->startFrames();
9284 // Accept a recent wraparound of mRsmpInRear
9285 if (startFrames <= rear) {
9286 deltaFrames = rear - startFrames;
9287 } else {
9288 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009289 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009290 // start frame cannot be further in the past than start of resampling buffer
9291 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9292 deltaFrames = recordThread->mRsmpInFrames;
9293 }
9294 }
9295 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009296}
9297
Andy Hung11e74242023-06-26 19:20:57 -07009298void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009299 size_t *framesAvailable, bool *hasOverrun)
9300{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009301 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009302 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009303 const int32_t rear = recordThread->mRsmpInRear;
9304 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009305 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009306
9307 size_t framesIn;
9308 bool overrun = false;
9309 if (filled < 0) {
9310 // should not happen, but treat like a massive overrun and re-sync
9311 framesIn = 0;
9312 mRsmpInFront = rear;
9313 overrun = true;
9314 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9315 framesIn = (size_t) filled;
9316 } else {
9317 // client is not keeping up with server, but give it latest data
9318 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009319 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9320 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009321 overrun = true;
9322 }
9323 if (framesAvailable != NULL) {
9324 *framesAvailable = framesIn;
9325 }
9326 if (hasOverrun != NULL) {
9327 *hasOverrun = overrun;
9328 }
9329}
9330
Eric Laurent81784c32012-11-19 14:55:58 -08009331// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009332status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009333 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009334{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009335 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009336 if (threadBase == 0) {
9337 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009338 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009339 return NOT_ENOUGH_DATA;
9340 }
Andy Hung4b17e882023-07-07 13:47:37 -07009341 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009342 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009343 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009344 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009345 // FIXME should not be P2 (don't want to increase latency)
9346 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009347 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009348 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009349
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009350 front &= recordThread->mRsmpInFramesP2 - 1;
9351 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009352 if (part1 > (size_t) filled) {
9353 part1 = filled;
9354 }
9355 size_t ask = buffer->frameCount;
9356 ALOG_ASSERT(ask > 0);
9357 if (part1 > ask) {
9358 part1 = ask;
9359 }
9360 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009361 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009362 buffer->raw = NULL;
9363 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009364 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009365 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009366 }
9367
Andy Hung57446612015-04-19 23:56:46 -07009368 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009369 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009370 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009371 return NO_ERROR;
9372}
9373
9374// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009375void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009376 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009377{
Hongwei Wang95e37682019-04-12 11:13:36 -07009378 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009379 if (stepCount == 0) {
9380 return;
9381 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009382 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009383 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009384 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009385 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009386 buffer->frameCount = 0;
9387}
9388
Andy Hung4b17e882023-07-07 13:47:37 -07009389void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009390{
Andy Hungf8635b62023-08-31 16:13:39 -07009391 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009392 checkBtNrec_l();
9393}
9394
Andy Hung4b17e882023-07-07 13:47:37 -07009395void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009396{
9397 // disable AEC and NS if the device is a BT SCO headset supporting those
9398 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009399 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009400 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009401 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9402 for (size_t i = 0; i < mEffectChains.size(); i++) {
9403 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9404 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9405 }
9406 }
9407}
9408
Andy Hung97a893e2015-03-29 01:03:07 -07009409
Andy Hung4b17e882023-07-07 13:47:37 -07009410bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009411 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009412{
9413 bool reconfig = false;
9414
Eric Laurent10351942014-05-08 18:49:52 -07009415 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009416
Eric Laurent10351942014-05-08 18:49:52 -07009417 audio_format_t reqFormat = mFormat;
9418 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009419 // 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 +08009420 [[maybe_unused]] audio_channel_mask_t channelMask =
9421 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009422
9423 AudioParameter param = AudioParameter(keyValuePair);
9424 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009425
9426 // scope for AutoPark extends to end of method
9427 AutoPark<FastCapture> park(mFastCapture);
9428
Eric Laurent10351942014-05-08 18:49:52 -07009429 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9430 // channel count change can be requested. Do we mandate the first client defines the
9431 // HAL sampling rate and channel count or do we allow changes on the fly?
9432 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9433 samplingRate = value;
9434 reconfig = true;
9435 }
9436 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009437 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009438 status = BAD_VALUE;
9439 } else {
9440 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009441 reconfig = true;
9442 }
Eric Laurent10351942014-05-08 18:49:52 -07009443 }
9444 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9445 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009446 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009447 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009448 status = BAD_VALUE;
9449 } else {
9450 channelMask = mask;
9451 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009452 }
Eric Laurent10351942014-05-08 18:49:52 -07009453 }
9454 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9455 // do not accept frame count changes if tracks are open as the track buffer
9456 // size depends on frame count and correct behavior would not be guaranteed
9457 // if frame count is changed after track creation
9458 if (mActiveTracks.size() > 0) {
9459 status = INVALID_OPERATION;
9460 } else {
9461 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009462 }
Eric Laurent10351942014-05-08 18:49:52 -07009463 }
9464 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009465 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009466 }
9467 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9468 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009469 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009470 }
Glenn Kastene198c362013-08-13 09:13:36 -07009471
Eric Laurent10351942014-05-08 18:49:52 -07009472 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009473 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009474 if (status == INVALID_OPERATION) {
9475 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009476 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009477 }
9478 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009479 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009480 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9481 if (mInput->stream->getAudioProperties(&config) == OK &&
9482 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9483 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009484 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009485 status = NO_ERROR;
9486 }
Eric Laurent81784c32012-11-19 14:55:58 -08009487 }
Eric Laurent10351942014-05-08 18:49:52 -07009488 if (status == NO_ERROR) {
9489 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009490 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009491 }
9492 }
Eric Laurent81784c32012-11-19 14:55:58 -08009493 }
Eric Laurent10351942014-05-08 18:49:52 -07009494
Eric Laurent81784c32012-11-19 14:55:58 -08009495 return reconfig;
9496}
9497
Andy Hung4b17e882023-07-07 13:47:37 -07009498String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009499{
Andy Hungf8635b62023-08-31 16:13:39 -07009500 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009501 if (initCheck() == NO_ERROR) {
9502 String8 out_s8;
9503 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9504 return out_s8;
9505 }
Eric Laurent81784c32012-11-19 14:55:58 -08009506 }
Andy Hung920f6572022-10-06 12:09:49 -07009507 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009508}
9509
Andy Hung4b17e882023-07-07 13:47:37 -07009510void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009511 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009512 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009513 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009514 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009515 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009516 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009517 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9518 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009519 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009520 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009521 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009522 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009523 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009524 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009525 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009526 break;
9527 }
Andy Hung7535ed92023-07-17 17:05:00 -07009528 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009529}
9530
Andy Hung4b17e882023-07-07 13:47:37 -07009531void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009532{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009533 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9534 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009535 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009536 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9537 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009538 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9539 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009540 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009541 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009542 ALOGI("HAL format %#x is not linear pcm", mFormat);
9543 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009544 result = mInput->stream->getFrameSize(&mFrameSize);
9545 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009546 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9547 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009548 result = mInput->stream->getBufferSize(&mBufferSize);
9549 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009550 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009551 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9552 "mBufferSize=%zu, mFrameCount=%zu",
9553 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009554
Eric Laurentec376dc2021-04-08 20:41:22 +02009555 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9556 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009557 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009558
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009559 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9560 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009561
9562 audio_input_flags_t flags = mInput->flags;
9563 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9564 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07009565 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009566 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9567 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9568 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9569 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9570 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9571 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009572}
9573
Andy Hung4b17e882023-07-07 13:47:37 -07009574uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009575{
Andy Hungf8635b62023-08-31 16:13:39 -07009576 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009577 uint32_t result;
9578 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9579 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009580 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009581 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009582}
9583
Andy Hung4b17e882023-07-07 13:47:37 -07009584KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009585{
Glenn Kastend848eb42016-03-08 13:42:11 -08009586 KeyedVector<audio_session_t, bool> ids;
Andy Hungf8635b62023-08-31 16:13:39 -07009587 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009588 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009589 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009590 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009591 if (ids.indexOfKey(sessionId) < 0) {
9592 ids.add(sessionId, true);
9593 }
9594 }
9595 return ids;
9596}
9597
Andy Hung4b17e882023-07-07 13:47:37 -07009598AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009599{
Andy Hungf8635b62023-08-31 16:13:39 -07009600 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009601 AudioStreamIn *input = mInput;
9602 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009603 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009604 return input;
9605}
9606
Andy Hungb17d24b2023-08-29 14:26:09 -07009607// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009608sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009609{
9610 if (mInput == NULL) {
9611 return NULL;
9612 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009613 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009614}
9615
Andy Hung4b17e882023-07-07 13:47:37 -07009616status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009617{
Eric Laurent81784c32012-11-19 14:55:58 -08009618 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009619 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009620 chain->setInBuffer(NULL);
9621 chain->setOutBuffer(NULL);
9622
9623 checkSuspendOnAddEffectChain_l(chain);
9624
Eric Laurent1b928682014-10-02 19:41:47 -07009625 // make sure enabled pre processing effects state is communicated to the HAL as we
9626 // just moved them to a new input stream.
9627 chain->syncHalEffectsState();
9628
Eric Laurent81784c32012-11-19 14:55:58 -08009629 mEffectChains.add(chain);
9630
9631 return NO_ERROR;
9632}
9633
Andy Hung4b17e882023-07-07 13:47:37 -07009634size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009635{
9636 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009637
9638 for (size_t i = 0; i < mEffectChains.size(); i++) {
9639 if (chain == mEffectChains[i]) {
9640 mEffectChains.removeAt(i);
9641 break;
9642 }
Eric Laurent81784c32012-11-19 14:55:58 -08009643 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009644 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009645}
9646
Andy Hung4b17e882023-07-07 13:47:37 -07009647status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009648 audio_patch_handle_t *handle)
9649{
9650 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009651
9652 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009653 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009654 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009655 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009656 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009657 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009658 }
9659
Eric Laurentd8365c52017-07-16 15:27:05 -07009660 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009661
9662 // store new source and send to effects
9663 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9664 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009665 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009666 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009667 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009668 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009669
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009670 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009671 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9672 status = hwDevice->createAudioPatch(patch->num_sources,
9673 patch->sources,
9674 patch->num_sinks,
9675 patch->sinks,
9676 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009677 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009678 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9679 patch->sinks[0].ext.mix.usecase.source,
9680 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009681 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009682 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009683
jiabinc52b1ff2019-10-31 17:20:42 -07009684 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009685 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009686 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009687 }
Eric Laurent296fb132015-05-01 11:38:42 -07009688
Andy Hungc2b11cb2020-04-22 09:04:01 -07009689 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009690 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009691 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009692 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009693 // also dispatch to active AudioRecords
9694 for (const auto &track : mActiveTracks) {
9695 track->logEndInterval();
9696 track->logBeginInterval(pathSourcesAsString);
9697 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009698 // Force meteadata update after a route change
9699 mActiveTracks.setHasChanged();
9700
Eric Laurent1c333e22014-05-20 10:48:17 -07009701 return status;
9702}
9703
Andy Hung4b17e882023-07-07 13:47:37 -07009704status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009705{
9706 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009707
jiabinc52b1ff2019-10-31 17:20:42 -07009708 mPatch = audio_patch{};
9709 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009710
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009711 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009712 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9713 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009714 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009715 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009716 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009717 // Force meteadata update after a route change
9718 mActiveTracks.setHasChanged();
9719
Eric Laurent1c333e22014-05-20 10:48:17 -07009720 return status;
9721}
9722
Andy Hung4b17e882023-07-07 13:47:37 -07009723void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009724{
Andy Hungf8635b62023-08-31 16:13:39 -07009725 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009726 mOutDevices = outDevices;
9727 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9728 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009729 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009730 }
9731}
9732
Andy Hung4b17e882023-07-07 13:47:37 -07009733int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009734{
9735 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009736 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009737 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009738 int32_t oldestFront = mRsmpInRear;
9739 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009740 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009741 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009742 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009743 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009744 if (filled > maxFilled) {
9745 oldestFront = front;
9746 maxFilled = filled;
9747 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009748 }
Andy Hung920f6572022-10-06 12:09:49 -07009749 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009750 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9751 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009752 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009753}
9754
Andy Hung4b17e882023-07-07 13:47:37 -07009755void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009756{
9757 if (offset == 0) {
9758 return;
9759 }
9760 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009761 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009762 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009763 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009764 }
9765}
9766
Andy Hung4b17e882023-07-07 13:47:37 -07009767void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009768{
9769 // This is the formula for calculating the temporary buffer size.
9770 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9771 // 1 full output buffer, regardless of the alignment of the available input.
9772 // The value is somewhat arbitrary, and could probably be even larger.
9773 // A larger value should allow more old data to be read after a track calls start(),
9774 // without increasing latency.
9775 //
9776 // Note this is independent of the maximum downsampling ratio permitted for capture.
9777 size_t minRsmpInFrames = mFrameCount * 7;
9778
9779 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9780 // capture history available to another client using the same session ID:
9781 // dimension the resampler input buffer accordingly.
9782
9783 // Get oldest client read position: getOldestFront_l() must be called before altering
9784 // mRsmpInRear, or mRsmpInFrames
9785 int32_t previousFront = getOldestFront_l();
9786 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9787 int32_t previousRear = mRsmpInRear;
9788 mRsmpInRear = 0;
9789
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009790 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009791 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009792 "resizeInputBuffer_l() called with invalid max shared history %d",
9793 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009794 if (maxSharedAudioHistoryMs != 0) {
9795 // resizeInputBuffer_l should never be called with a non zero shared history if the
9796 // buffer was not already allocated
9797 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9798 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9799 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9800 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009801 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009802 return;
9803 }
9804 mRsmpInFrames = rsmpInFrames;
9805 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009806 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009807 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9808 // initialized
9809 if (mRsmpInFrames < minRsmpInFrames) {
9810 mRsmpInFrames = minRsmpInFrames;
9811 }
9812 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9813
9814 // TODO optimize audio capture buffer sizes ...
9815 // Here we calculate the size of the sliding buffer used as a source
9816 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9817 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9818 // be better to have it derived from the pipe depth in the long term.
9819 // The current value is higher than necessary. However it should not add to latency.
9820
9821 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9822 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9823
9824 void *rsmpInBuffer;
9825 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9826 // if posix_memalign fails, will segv here.
9827 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9828
9829 // Copy audio history if any from old buffer before freeing it
9830 if (previousRear != 0) {
9831 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9832 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9833
9834 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9835 previousFront &= previousRsmpInFramesP2 - 1;
9836 size_t part1 = previousRsmpInFramesP2 - previousFront;
9837 if (part1 > (size_t) unread) {
9838 part1 = unread;
9839 }
9840 if (part1 != 0) {
9841 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9842 part1 * mFrameSize);
9843 mRsmpInRear = part1;
9844 part1 = unread - part1;
9845 if (part1 != 0) {
9846 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9847 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9848 mRsmpInRear += part1;
9849 }
9850 }
9851 // Update front for all clients according to new rear
9852 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9853 } else {
9854 mRsmpInRear = 0;
9855 }
9856 free(mRsmpInBuffer);
9857 mRsmpInBuffer = rsmpInBuffer;
9858}
9859
Andy Hung4b17e882023-07-07 13:47:37 -07009860void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009861{
Andy Hungf8635b62023-08-31 16:13:39 -07009862 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009863 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009864 if (record->getSource()) {
9865 mSource = record->getSource();
9866 }
Eric Laurent83b88082014-06-20 18:31:16 -07009867}
9868
Andy Hung4b17e882023-07-07 13:47:37 -07009869void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009870{
Andy Hungf8635b62023-08-31 16:13:39 -07009871 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009872 if (mSource == record->getSource()) {
9873 mSource = mInput;
9874 }
Eric Laurent83b88082014-06-20 18:31:16 -07009875 destroyTrack_l(record);
9876}
9877
Andy Hung4b17e882023-07-07 13:47:37 -07009878void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009879{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009880 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009881 config->role = AUDIO_PORT_ROLE_SINK;
9882 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9883 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009884 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9885 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9886 config->flags.input = mInput->flags;
9887 }
Eric Laurent83b88082014-06-20 18:31:16 -07009888}
Eric Laurent1c333e22014-05-20 10:48:17 -07009889
Eric Laurent6acd1d42017-01-04 14:23:29 -08009890// ----------------------------------------------------------------------------
9891// Mmap
9892// ----------------------------------------------------------------------------
9893
Andy Hung765de282023-07-07 15:58:48 -07009894// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9895// MmapPlaybackThread or MmapCaptureThread instance.
9896class MmapThreadHandle : public MmapStreamInterface {
9897public:
9898 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9899 ~MmapThreadHandle() override;
9900
9901 // MmapStreamInterface virtuals
9902 status_t createMmapBuffer(int32_t minSizeFrames,
9903 struct audio_mmap_buffer_info* info) final;
9904 status_t getMmapPosition(struct audio_mmap_position* position) final;
9905 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9906 status_t start(const AudioClient& client,
9907 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9908 status_t stop(audio_port_handle_t handle) final;
9909 status_t standby() final;
9910 status_t reportData(const void* buffer, size_t frameCount) final;
9911private:
9912 const sp<IAfMmapThread> mThread;
9913};
9914
9915/* static */
9916sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9917 const sp<IAfMmapThread>& mmapThread) {
9918 return sp<MmapThreadHandle>::make(mmapThread);
9919}
9920
9921MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009922 : mThread(thread)
9923{
Phil Burk9fabbf82017-08-03 12:02:00 -07009924 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009925}
9926
Andy Hung765de282023-07-07 15:58:48 -07009927// MmapStreamInterface could be directly implemented by MmapThread excepting this
9928// special handling on adapter dtor.
9929MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930{
Phil Burk9fabbf82017-08-03 12:02:00 -07009931 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009932}
9933
Andy Hung765de282023-07-07 15:58:48 -07009934status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009935 struct audio_mmap_buffer_info *info)
9936{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009937 return mThread->createMmapBuffer(minSizeFrames, info);
9938}
9939
Andy Hung765de282023-07-07 15:58:48 -07009940status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009942 return mThread->getMmapPosition(position);
9943}
9944
Andy Hung765de282023-07-07 15:58:48 -07009945status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009946 int64_t *timeNanos) {
9947 return mThread->getExternalPosition(position, timeNanos);
9948}
9949
Andy Hung765de282023-07-07 15:58:48 -07009950status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009951 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009952{
jiabind1f1cb62020-03-24 11:57:57 -07009953 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009954}
9955
Andy Hung765de282023-07-07 15:58:48 -07009956status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009958 return mThread->stop(handle);
9959}
9960
Andy Hung765de282023-07-07 15:58:48 -07009961status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009962{
Eric Laurent18b57012017-02-13 16:23:52 -08009963 return mThread->standby();
9964}
9965
Andy Hung765de282023-07-07 15:58:48 -07009966status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9967{
jiabinfc791ee2023-02-15 19:43:40 +00009968 return mThread->reportData(buffer, frameCount);
9969}
9970
Eric Laurent6acd1d42017-01-04 14:23:29 -08009971
Andy Hung4b17e882023-07-07 13:47:37 -07009972MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -07009973 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009974 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -07009975 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009976 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009977 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009978 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009979 mActiveTracks(&this->mLocalLog),
9980 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9981 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009982{
Eric Laurent18b57012017-02-13 16:23:52 -08009983 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009984 readHalParameters_l();
9985}
9986
Andy Hung4b17e882023-07-07 13:47:37 -07009987void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988{
9989 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9990}
9991
Andy Hung4b17e882023-07-07 13:47:37 -07009992void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009993{
Andy Hung11e74242023-06-26 19:20:57 -07009994 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009995 {
Andy Hungf8635b62023-08-31 16:13:39 -07009996 audio_utils::lock_guard _l(mutex());
Andy Hung11e74242023-06-26 19:20:57 -07009997 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009998 activeTracks.add(t);
9999 }
10000 }
Andy Hung11e74242023-06-26 19:20:57 -070010001 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010002 stop(t->portId());
10003 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010004 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010006 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010007 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010008 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010009 }
10010}
10011
10012
Andy Hung4b17e882023-07-07 13:47:37 -070010013void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010014 audio_stream_type_t streamType __unused,
10015 audio_session_t sessionId,
10016 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010017 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 audio_port_handle_t portId)
10019{
10020 mAttr = *attr;
10021 mSessionId = sessionId;
10022 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010023 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010024 mPortId = portId;
10025}
10026
Andy Hung4b17e882023-07-07 13:47:37 -070010027status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010028 struct audio_mmap_buffer_info *info)
10029{
10030 if (mHalStream == 0) {
10031 return NO_INIT;
10032 }
Eric Laurent18b57012017-02-13 16:23:52 -080010033 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010034 return mHalStream->createMmapBuffer(minSizeFrames, info);
10035}
10036
Andy Hung4b17e882023-07-07 13:47:37 -070010037status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010038{
10039 if (mHalStream == 0) {
10040 return NO_INIT;
10041 }
10042 return mHalStream->getMmapPosition(position);
10043}
10044
Andy Hung4b17e882023-07-07 13:47:37 -070010045status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010046{
Eric Laurentdda206a2022-07-08 17:28:35 +020010047 // The HAL must receive track metadata before starting the stream
10048 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010049 status_t ret = mHalStream->start();
10050 if (ret != NO_ERROR) {
10051 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10052 return ret;
10053 }
Andy Hungcf10d742020-04-28 15:38:24 -070010054 if (mStandby) {
10055 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010056 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010057 mStandby = false;
10058 }
Eric Laurent331679c2018-04-16 17:03:16 -070010059 return NO_ERROR;
10060}
10061
Andy Hung4b17e882023-07-07 13:47:37 -070010062status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010063 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064 audio_port_handle_t *handle)
10065{
Eric Laurenta54f1282017-07-01 19:39:32 -070010066 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010067 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010068 if (mHalStream == 0) {
10069 return NO_INIT;
10070 }
10071
10072 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010073
Eric Laurentdda206a2022-07-08 17:28:35 +020010074 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010075 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010076 acquireWakeLock();
10077 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010078 }
10079
10080 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10081
10082 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010083 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010084 client.attributionSource);
10085
Eric Laurenta54f1282017-07-01 19:39:32 -070010086 if (isOutput()) {
10087 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10088 config.sample_rate = mSampleRate;
10089 config.channel_mask = mChannelMask;
10090 config.format = mFormat;
10091 audio_stream_type_t stream = streamType();
10092 audio_output_flags_t flags =
10093 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010094 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010095 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010096 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010097 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010098 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10099 mSessionId,
10100 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010101 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010102 &config,
10103 flags,
10104 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010105 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010106 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010107 &isSpatialized,
10108 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010109 ALOGD_IF(!secondaryOutputs.empty(),
10110 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010111 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010112 audio_config_base_t config;
10113 config.sample_rate = mSampleRate;
10114 config.channel_mask = mChannelMask;
10115 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010116 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010117 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010118 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010119 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010120 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010121 &config,
10122 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10123 &deviceId,
10124 &portId);
10125 }
10126 // APM should not chose a different input or output stream for the same set of attributes
10127 // and audo configuration
10128 if (ret != NO_ERROR || io != mId) {
10129 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10130 __FUNCTION__, ret, io, mId);
10131 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010132 }
10133
10134 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010135 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010136 } else {
jiabin09609032022-06-15 19:26:01 +000010137 {
10138 // Add the track record before starting input so that the silent status for the
10139 // client can be cached.
Andy Hungf8635b62023-08-31 16:13:39 -070010140 audio_utils::lock_guard _l(mutex());
jiabin09609032022-06-15 19:26:01 +000010141 setClientSilencedState_l(portId, false /*silenced*/);
10142 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010143 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144 }
10145
Andy Hungf8635b62023-08-31 16:13:39 -070010146 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010147 // abort if start is rejected by audio policy manager
10148 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010149 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010150 if (!mActiveTracks.isEmpty()) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010151 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010153 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010154 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010155 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010157 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010158 } else {
10159 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010160 }
jiabin09609032022-06-15 19:26:01 +000010161 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010162 return PERMISSION_DENIED;
10163 }
10164
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010165 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010166 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10167 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010168 mChannelMask, mSessionId, isOutput(),
10169 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010170 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010171 if (!isOutput()) {
10172 track->setSilenced_l(isClientSilenced_l(portId));
10173 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174
Eric Laurent4eb58f12018-12-07 16:41:02 -080010175 if (isOutput()) {
10176 // force volume update when a new track is added
10177 mHalVolFloat = -1.0f;
10178 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010179 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010180 if (t->isSilenced_l()
10181 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010182 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010183 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010184 }
10185 }
10186
Eric Laurent6acd1d42017-01-04 14:23:29 -080010187 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010188 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010189 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010190 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191 chain->incTrackCnt();
10192 chain->incActiveTrackCnt();
10193 }
10194
Andy Hungc2b11cb2020-04-22 09:04:01 -070010195 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010197
10198 if (mActiveTracks.size() == 1) {
10199 ret = exitStandby_l();
10200 }
10201
Eric Laurent6acd1d42017-01-04 14:23:29 -080010202 broadcast_l();
10203
Eric Laurentdda206a2022-07-08 17:28:35 +020010204 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010205
Eric Laurentdda206a2022-07-08 17:28:35 +020010206 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207}
10208
Andy Hung4b17e882023-07-07 13:47:37 -070010209status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010210{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010211 ALOGV("%s handle %d", __FUNCTION__, handle);
10212
10213 if (mHalStream == 0) {
10214 return NO_INIT;
10215 }
10216
Eric Laurenta54f1282017-07-01 19:39:32 -070010217 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010218 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010219 return NO_ERROR;
10220 }
10221
Andy Hungf8635b62023-08-31 16:13:39 -070010222 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070010223
Andy Hung11e74242023-06-26 19:20:57 -070010224 sp<IAfMmapTrack> track;
10225 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010226 if (handle == t->portId()) {
10227 track = t;
10228 break;
10229 }
10230 }
10231 if (track == 0) {
10232 return BAD_VALUE;
10233 }
10234
10235 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010236 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010237
Andy Hungb17d24b2023-08-29 14:26:09 -070010238 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010239 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010240 AudioSystem::stopOutput(track->portId());
10241 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010243 AudioSystem::stopInput(track->portId());
10244 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010246 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010247
Andy Hung116bc262023-06-20 18:56:17 -070010248 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010249 if (chain != 0) {
10250 chain->decActiveTrackCnt();
10251 chain->decTrackCnt();
10252 }
10253
Eric Laurentdda206a2022-07-08 17:28:35 +020010254 if (mActiveTracks.isEmpty()) {
10255 mHalStream->stop();
10256 }
10257
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 broadcast_l();
10259
Eric Laurent6acd1d42017-01-04 14:23:29 -080010260 return NO_ERROR;
10261}
10262
Andy Hung4b17e882023-07-07 13:47:37 -070010263status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010264{
10265 ALOGV("%s", __FUNCTION__);
10266
10267 if (mHalStream == 0) {
10268 return NO_INIT;
10269 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010270 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010271 return INVALID_OPERATION;
10272 }
10273 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010274 if (!mStandby) {
10275 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010276 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010277 mStandby = true;
10278 }
Eric Laurent18b57012017-02-13 16:23:52 -080010279 releaseWakeLock();
10280 return NO_ERROR;
10281}
10282
Andy Hung4b17e882023-07-07 13:47:37 -070010283status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010284 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10285 return INVALID_OPERATION;
10286}
10287
Andy Hung4b17e882023-07-07 13:47:37 -070010288void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289{
10290 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10291 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10292 mFormat = mHALFormat;
10293 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10294 result = mHalStream->getFrameSize(&mFrameSize);
10295 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010296 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10297 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298 result = mHalStream->getBufferSize(&mBufferSize);
10299 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10300 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010301
Andy Hungcf10d742020-04-28 15:38:24 -070010302 // TODO: make a readHalParameters call?
10303 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010304 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -070010305 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010306 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10307 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10308 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10309 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10310 /*
10311 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10312 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10313 (int32_t)mHapticChannelMask)
10314 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10315 (int32_t)mHapticChannelCount)
10316 */
10317 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -070010318 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010319 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10320 (int32_t)mFrameCount) // sic - added HAL
10321 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010322}
10323
Andy Hung4b17e882023-07-07 13:47:37 -070010324bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010326 checkSilentMode_l();
10327
10328 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10329
10330 while (!exitPending())
10331 {
Andy Hung116bc262023-06-20 18:56:17 -070010332 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333
Andy Hung13850be2019-03-14 11:33:09 -070010334 { // under Thread lock
Andy Hungb17d24b2023-08-29 14:26:09 -070010335 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010336
Eric Laurent6acd1d42017-01-04 14:23:29 -080010337 if (mSignalPending) {
10338 // A signal was raised while we were unlocked
10339 mSignalPending = false;
10340 } else {
10341 if (mConfigEvents.isEmpty()) {
10342 // we're about to wait, flush the binder command buffer
10343 IPCThreadState::self()->flushCommands();
10344
10345 if (exitPending()) {
10346 break;
10347 }
10348
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010350 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -070010351 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010352 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353
10354 checkSilentMode_l();
10355
10356 continue;
10357 }
10358 }
10359
10360 processConfigEvents_l();
10361
10362 processVolume_l();
10363
10364 checkInvalidTracks_l();
10365
10366 mActiveTracks.updatePowerState(this);
10367
Kevin Rocard069c2712018-03-29 19:09:14 -070010368 updateMetadata_l();
10369
Eric Laurent6acd1d42017-01-04 14:23:29 -080010370 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010371 } // release Thread lock
10372
Eric Laurent6acd1d42017-01-04 14:23:29 -080010373 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010374 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375 }
Andy Hung13850be2019-03-14 11:33:09 -070010376
10377 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010378 unlockEffectChains(effectChains);
10379 // Effect chains will be actually deleted here if they were removed from
10380 // mEffectChains list during mixing or effects processing
10381 }
10382
10383 threadLoop_exit();
10384
10385 if (!mStandby) {
10386 threadLoop_standby();
10387 mStandby = true;
10388 }
10389
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390 ALOGV("Thread %p type %d exiting", this, mType);
10391 return false;
10392}
10393
Andy Hungb17d24b2023-08-29 14:26:09 -070010394// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070010395bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396 status_t& status)
10397{
10398 AudioParameter param = AudioParameter(keyValuePair);
10399 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010400 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010402 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010403 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010404 if (sendToHal) {
10405 status = mHalStream->setParameters(keyValuePair);
10406 } else {
10407 status = NO_ERROR;
10408 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010409
10410 return false;
10411}
10412
Andy Hung4b17e882023-07-07 13:47:37 -070010413String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414{
Andy Hungf8635b62023-08-31 16:13:39 -070010415 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010416 String8 out_s8;
10417 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10418 return out_s8;
10419 }
Andy Hung920f6572022-10-06 12:09:49 -070010420 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421}
10422
Andy Hung4b17e882023-07-07 13:47:37 -070010423void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010424 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010425 sp<AudioIoDescriptor> desc;
10426 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010427 switch (event) {
10428 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010429 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010430 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010431 isInput = true;
10432 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010433 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010434 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010435 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010436 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10437 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010438 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439 case AUDIO_INPUT_CLOSED:
10440 case AUDIO_OUTPUT_CLOSED:
10441 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010442 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010443 break;
10444 }
Andy Hung7535ed92023-07-17 17:05:00 -070010445 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010446}
10447
Andy Hung4b17e882023-07-07 13:47:37 -070010448status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 audio_patch_handle_t *handle)
Andy Hungb17d24b2023-08-29 14:26:09 -070010450NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451{
10452 status_t status = NO_ERROR;
10453
10454 // store new device and send to effects
10455 audio_devices_t type = AUDIO_DEVICE_NONE;
10456 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010457 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10458 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10459 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010460 if (isOutput()) {
10461 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010462 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10463 && !mAudioHwDev->supportsAudioPatches(),
10464 "Enumerated device type(%#x) must not be used "
10465 "as it does not support audio patches",
10466 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010467 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010468 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10469 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470 }
10471 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010472 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010473 } else {
10474 type = patch->sources[0].ext.device.type;
10475 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010476 numDevices = mPatch.num_sources;
10477 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010478 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010479 }
10480
10481 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010482 if (isOutput()) {
10483 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10484 } else {
10485 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10486 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010487 }
10488
jiabinc52b1ff2019-10-31 17:20:42 -070010489 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010490 // store new source and send to effects
10491 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10492 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10493 for (size_t i = 0; i < mEffectChains.size(); i++) {
10494 mEffectChains[i]->setAudioSource_l(mAudioSource);
10495 }
10496 }
10497 }
10498
10499 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010500 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10501 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010502 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010503 audio_port_config port;
10504 std::optional<audio_source_t> source;
10505 if (isOutput()) {
10506 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010507 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010508 port = patch->sources[0];
10509 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010510 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010511 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512 *handle = AUDIO_PATCH_HANDLE_NONE;
10513 }
10514
jiabinc52b1ff2019-10-31 17:20:42 -070010515 if (numDevices == 0 || mDeviceId != deviceId) {
10516 if (isOutput()) {
10517 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10518 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010519 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010520 } else {
10521 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10522 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10523 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010524 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010525 if (mDeviceId != deviceId && callback != 0) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010526 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010527 callback->onRoutingChanged(deviceId);
Andy Hungb17d24b2023-08-29 14:26:09 -070010528 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010529 }
jiabinc52b1ff2019-10-31 17:20:42 -070010530 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010531 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010532 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010533 // Force meteadata update after a route change
10534 mActiveTracks.setHasChanged();
10535
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536 return status;
10537}
10538
Andy Hung4b17e882023-07-07 13:47:37 -070010539status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010540{
10541 status_t status = NO_ERROR;
10542
jiabinc52b1ff2019-10-31 17:20:42 -070010543 mPatch = audio_patch{};
10544 mOutDeviceTypeAddrs.clear();
10545 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010546
10547 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10548 supportsAudioPatches : false;
10549
10550 if (supportsAudioPatches) {
10551 status = mHalDevice->releaseAudioPatch(handle);
10552 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010553 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010554 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010555 // Force meteadata update after a route change
10556 mActiveTracks.setHasChanged();
10557
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558 return status;
10559}
10560
Andy Hung4b17e882023-07-07 13:47:37 -070010561void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010562{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010563 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564 if (isOutput()) {
10565 config->role = AUDIO_PORT_ROLE_SOURCE;
10566 config->ext.mix.hw_module = mAudioHwDev->handle();
10567 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10568 } else {
10569 config->role = AUDIO_PORT_ROLE_SINK;
10570 config->ext.mix.hw_module = mAudioHwDev->handle();
10571 config->ext.mix.usecase.source = mAudioSource;
10572 }
10573}
10574
Andy Hung4b17e882023-07-07 13:47:37 -070010575status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576{
10577 audio_session_t session = chain->sessionId();
10578
10579 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10580 // Attach all tracks with same session ID to this chain.
10581 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010582 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010583 if (session == track->sessionId()) {
10584 chain->incTrackCnt();
10585 chain->incActiveTrackCnt();
10586 }
10587 }
10588
10589 chain->setThread(this);
10590 chain->setInBuffer(nullptr);
10591 chain->setOutBuffer(nullptr);
10592 chain->syncHalEffectsState();
10593
10594 mEffectChains.add(chain);
10595 checkSuspendOnAddEffectChain_l(chain);
10596 return NO_ERROR;
10597}
10598
Andy Hung4b17e882023-07-07 13:47:37 -070010599size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010600{
10601 audio_session_t session = chain->sessionId();
10602
10603 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10604
10605 for (size_t i = 0; i < mEffectChains.size(); i++) {
10606 if (chain == mEffectChains[i]) {
10607 mEffectChains.removeAt(i);
10608 // detach all active tracks from the chain
10609 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010610 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010611 if (session == track->sessionId()) {
10612 chain->decActiveTrackCnt();
10613 chain->decTrackCnt();
10614 }
10615 }
10616 break;
10617 }
10618 }
10619 return mEffectChains.size();
10620}
10621
Andy Hung4b17e882023-07-07 13:47:37 -070010622void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010623{
10624 mHalStream->standby();
10625}
10626
Andy Hung4b17e882023-07-07 13:47:37 -070010627void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010628{
Phil Burk7dce7282017-09-27 13:51:41 -070010629 // Do not call callback->onTearDown() because it is redundant for thread exit
10630 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010631}
10632
Andy Hung4b17e882023-07-07 13:47:37 -070010633status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634{
10635 return BAD_VALUE;
10636}
10637
Andy Hung4b17e882023-07-07 13:47:37 -070010638bool MmapThread::isValidSyncEvent(
10639 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010640{
10641 return false;
10642}
10643
Andy Hung4b17e882023-07-07 13:47:37 -070010644status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010645 const effect_descriptor_t *desc, audio_session_t sessionId)
10646{
10647 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010648 if (audio_is_global_session(sessionId)) {
10649 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010650 desc->name, mThreadName);
10651 return BAD_VALUE;
10652 }
10653
10654 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10655 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10656 desc->name);
10657 return BAD_VALUE;
10658 }
10659 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010660 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10661 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010662 return BAD_VALUE;
10663 }
10664
10665 // Only allow effects without processing load or latency
10666 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10667 return BAD_VALUE;
10668 }
10669
Andy Hung116bc262023-06-20 18:56:17 -070010670 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010671 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10672 return BAD_VALUE;
10673 }
10674
Eric Laurent6acd1d42017-01-04 14:23:29 -080010675 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010676}
10677
Andy Hung4b17e882023-07-07 13:47:37 -070010678void MmapThread::checkInvalidTracks_l()
Andy Hungb17d24b2023-08-29 14:26:09 -070010679NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010680{
Eric Laurent039c24a2022-10-07 14:01:59 +020010681 sp<MmapStreamCallback> callback;
Andy Hung11e74242023-06-26 19:20:57 -070010682 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010683 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010684 callback = mCallback.promote();
10685 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10686 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10687 mNoCallbackWarningCount++;
10688 }
10689 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010690 }
10691 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010692 if (callback != 0) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010693 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010694 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungb17d24b2023-08-29 14:26:09 -070010695 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010696 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697}
10698
Andy Hung4b17e882023-07-07 13:47:37 -070010699void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010701 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10702 mAttr.content_type, mAttr.usage, mAttr.source);
10703 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010704 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010705 dprintf(fd, " No active clients\n");
10706 }
10707}
10708
Andy Hung4b17e882023-07-07 13:47:37 -070010709void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010710{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010711 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010712 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010713 dprintf(fd, " %zu Tracks\n", numtracks);
10714 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010715 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010716 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010717 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010718 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010719 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010720 result.append(prefix);
10721 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722 }
10723 } else {
10724 dprintf(fd, "\n");
10725 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010726 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727}
10728
Andy Hung4b17e882023-07-07 13:47:37 -070010729/* static */
10730sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010731 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010732 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010733 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010734}
10735
10736MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010737 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010738 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010739 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010741 mStreamVolume(1.0),
10742 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010743 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744{
10745 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10746 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070010747 mMasterVolume = afThreadCallback->masterVolume_l();
10748 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010749 if (mAudioHwDev) {
10750 if (mAudioHwDev->canSetMasterVolume()) {
10751 mMasterVolume = 1.0;
10752 }
10753
10754 if (mAudioHwDev->canSetMasterMute()) {
10755 mMasterMute = false;
10756 }
10757 }
10758}
10759
Andy Hung4b17e882023-07-07 13:47:37 -070010760void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010761 audio_stream_type_t streamType,
10762 audio_session_t sessionId,
10763 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010764 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010765 audio_port_handle_t portId)
10766{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010767 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010768 mStreamType = streamType;
10769}
10770
Andy Hung4b17e882023-07-07 13:47:37 -070010771AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010772{
Andy Hungf8635b62023-08-31 16:13:39 -070010773 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774 AudioStreamOut *output = mOutput;
10775 mOutput = NULL;
10776 return output;
10777}
10778
Andy Hung4b17e882023-07-07 13:47:37 -070010779void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780{
Andy Hungf8635b62023-08-31 16:13:39 -070010781 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010782 // Don't apply master volume in SW if our HAL can do it for us.
10783 if (mAudioHwDev &&
10784 mAudioHwDev->canSetMasterVolume()) {
10785 mMasterVolume = 1.0;
10786 } else {
10787 mMasterVolume = value;
10788 }
10789}
10790
Andy Hung4b17e882023-07-07 13:47:37 -070010791void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010792{
Andy Hungf8635b62023-08-31 16:13:39 -070010793 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010794 // Don't apply master mute in SW if our HAL can do it for us.
10795 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10796 mMasterMute = false;
10797 } else {
10798 mMasterMute = muted;
10799 }
10800}
10801
Andy Hung4b17e882023-07-07 13:47:37 -070010802void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010803{
Andy Hungf8635b62023-08-31 16:13:39 -070010804 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010805 if (stream == mStreamType) {
10806 mStreamVolume = value;
10807 broadcast_l();
10808 }
10809}
10810
Andy Hung4b17e882023-07-07 13:47:37 -070010811float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010812{
Andy Hungf8635b62023-08-31 16:13:39 -070010813 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010814 if (stream == mStreamType) {
10815 return mStreamVolume;
10816 }
10817 return 0.0f;
10818}
10819
Andy Hung4b17e882023-07-07 13:47:37 -070010820void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010821{
Andy Hungf8635b62023-08-31 16:13:39 -070010822 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010823 if (stream == mStreamType) {
10824 mStreamMute= muted;
10825 broadcast_l();
10826 }
10827}
10828
Andy Hung4b17e882023-07-07 13:47:37 -070010829void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010830{
Andy Hungf8635b62023-08-31 16:13:39 -070010831 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010832 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070010833 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010834 track->invalidate();
10835 }
10836 broadcast_l();
10837 }
10838}
10839
Andy Hung4b17e882023-07-07 13:47:37 -070010840void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010841{
Andy Hungf8635b62023-08-31 16:13:39 -070010842 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010843 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070010844 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010845 if (portIds.find(track->portId()) != portIds.end()) {
10846 track->invalidate();
10847 trackMatch = true;
10848 portIds.erase(track->portId());
10849 }
10850 if (portIds.empty()) {
10851 break;
10852 }
10853 }
10854 if (trackMatch) {
10855 broadcast_l();
10856 }
10857}
10858
Andy Hung4b17e882023-07-07 13:47:37 -070010859void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010860NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861{
10862 float volume;
10863
10864 if (mMasterMute || mStreamMute) {
10865 volume = 0;
10866 } else {
10867 volume = mMasterVolume * mStreamVolume;
10868 }
10869
10870 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010871
10872 // Convert volumes from float to 8.24
10873 uint32_t vol = (uint32_t)(volume * (1 << 24));
10874
10875 // Delegate volume control to effect in track effect chain if needed
10876 // only one effect chain can be present on DirectOutputThread, so if
10877 // there is one, the track is connected to it
10878 if (!mEffectChains.isEmpty()) {
10879 mEffectChains[0]->setVolume_l(&vol, &vol);
10880 volume = (float)vol / (1 << 24);
10881 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010882 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010883 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10884 mHalVolFloat = volume; // HW volume control worked, so update value.
10885 mNoCallbackWarningCount = 0;
10886 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010887 sp<MmapStreamCallback> callback = mCallback.promote();
10888 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010889 mHalVolFloat = volume; // SW volume control worked, so update value.
10890 mNoCallbackWarningCount = 0;
Andy Hungb17d24b2023-08-29 14:26:09 -070010891 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010892 callback->onVolumeChanged(volume);
Andy Hungb17d24b2023-08-29 14:26:09 -070010893 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010894 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010895 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10896 ALOGW("Could not set MMAP stream volume: no volume callback!");
10897 mNoCallbackWarningCount++;
10898 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010899 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010900 }
Andy Hung11e74242023-06-26 19:20:57 -070010901 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010902 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070010903 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010904 /*muteState=*/{mMasterMute,
10905 mStreamVolume == 0.f,
10906 mStreamMute,
10907 // TODO(b/241533526): adjust logic to include mute from AppOps
10908 false /*muteFromPlaybackRestricted*/,
10909 false /*muteFromClientVolume*/,
10910 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010911 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912 }
10913}
10914
Andy Hung4b17e882023-07-07 13:47:37 -070010915ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010916{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010917 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010918 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010919 }
10920 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070010921 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010922 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010923 playback_track_metadata_v7_t trackMetadata;
10924 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010925 .usage = track->attributes().usage,
10926 .content_type = track->attributes().content_type,
10927 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010928 };
10929 trackMetadata.channel_mask = track->channelMask(),
10930 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10931 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010932 }
10933 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010934
10935 MetadataUpdate change;
10936 change.playbackMetadataUpdate = metadata.tracks;
10937 return change;
10938};
Kevin Rocard069c2712018-03-29 19:09:14 -070010939
Andy Hung4b17e882023-07-07 13:47:37 -070010940void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010941{
10942 if (!mMasterMute) {
10943 char value[PROPERTY_VALUE_MAX];
10944 if (property_get("ro.audio.silent", value, "0") > 0) {
10945 char *endptr;
10946 unsigned long ul = strtoul(value, &endptr, 0);
10947 if (*endptr == '\0' && ul != 0) {
10948 ALOGD("Silence is golden");
10949 // The setprop command will not allow a property to be changed after
10950 // the first time it is set, so we don't have to worry about un-muting.
10951 setMasterMute_l(true);
10952 }
10953 }
10954 }
10955}
10956
Andy Hung4b17e882023-07-07 13:47:37 -070010957void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010958{
10959 MmapThread::toAudioPortConfig(config);
10960 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10961 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10962 config->flags.output = mOutput->flags;
10963 }
10964}
10965
Andy Hung4b17e882023-07-07 13:47:37 -070010966status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070010967 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010968{
10969 if (mOutput == nullptr) {
10970 return NO_INIT;
10971 }
10972 struct timespec timestamp;
10973 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10974 if (status == NO_ERROR) {
10975 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10976 }
10977 return status;
10978}
10979
Andy Hung4b17e882023-07-07 13:47:37 -070010980status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010981 // Send to MelProcessor for sound dose measurement.
10982 auto processor = mMelProcessor.load();
10983 if (processor) {
10984 processor->process(buffer, frameCount * mFrameSize);
10985 }
10986
jiabinfc791ee2023-02-15 19:43:40 +000010987 return NO_ERROR;
10988}
10989
Andy Hungb17d24b2023-08-29 14:26:09 -070010990// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070010991void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010992 const sp<audio_utils::MelProcessor>& processor)
10993{
10994 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010995 mMelProcessor.store(processor);
10996 if (processor) {
10997 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010998 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010999
11000 // no need to update output format for MMapPlaybackThread since it is
11001 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011002}
11003
Andy Hungb17d24b2023-08-29 14:26:09 -070011004// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011005void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011006{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011007 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11008 auto melProcessor = mMelProcessor.load();
11009 if (melProcessor != nullptr) {
11010 melProcessor->pause();
11011 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011012}
11013
Andy Hung4b17e882023-07-07 13:47:37 -070011014void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011015{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011016 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011017
Glenn Kastend3bb6452016-12-05 18:14:37 -080011018 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
11019 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011020 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11021}
11022
Andy Hung4b17e882023-07-07 13:47:37 -070011023/* static */
11024sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070011025 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070011026 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011027 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011028}
11029
11030MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011031 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011032 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011033 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011034 mInput(input)
11035{
11036 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11037 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11038}
11039
Andy Hung4b17e882023-07-07 13:47:37 -070011040status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011041{
Phil Burkf054fc32018-12-06 09:45:59 -080011042 {
11043 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011044 if (mInput != nullptr && mInput->stream != nullptr) {
11045 mInput->stream->setGain(1.0f);
11046 }
11047 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011048 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011049}
11050
Andy Hung4b17e882023-07-07 13:47:37 -070011051AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011052{
Andy Hungf8635b62023-08-31 16:13:39 -070011053 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011054 AudioStreamIn *input = mInput;
11055 mInput = NULL;
11056 return input;
11057}
Kevin Rocard069c2712018-03-29 19:09:14 -070011058
Andy Hung4b17e882023-07-07 13:47:37 -070011059void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011060{
11061 bool changed = false;
11062 bool silenced = false;
11063
11064 sp<MmapStreamCallback> callback = mCallback.promote();
11065 if (callback == 0) {
11066 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11067 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11068 mNoCallbackWarningCount++;
11069 }
11070 }
11071
11072 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11073 // track is silenced and unmute otherwise
11074 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11075 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11076 changed = true;
11077 silenced = mActiveTracks[i]->isSilenced_l();
11078 }
11079 }
11080
11081 if (changed) {
11082 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11083 }
11084}
11085
Andy Hung4b17e882023-07-07 13:47:37 -070011086ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011087{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011088 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011089 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011090 }
11091 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011092 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011093 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011094 record_track_metadata_v7_t trackMetadata;
11095 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011096 .source = track->attributes().source,
11097 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011098 };
11099 trackMetadata.channel_mask = track->channelMask(),
11100 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11101 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011102 }
11103 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011104 MetadataUpdate change;
11105 change.recordMetadataUpdate = metadata.tracks;
11106 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011107}
11108
Andy Hung4b17e882023-07-07 13:47:37 -070011109void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011110{
Andy Hungf8635b62023-08-31 16:13:39 -070011111 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011112 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011113 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011114 mActiveTracks[i]->setSilenced_l(silenced);
11115 broadcast_l();
11116 }
11117 }
jiabin09609032022-06-15 19:26:01 +000011118 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011119}
11120
Andy Hung4b17e882023-07-07 13:47:37 -070011121void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011122{
11123 MmapThread::toAudioPortConfig(config);
11124 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11125 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11126 config->flags.input = mInput->flags;
11127 }
11128}
11129
Andy Hung4b17e882023-07-07 13:47:37 -070011130status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011131 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011132{
11133 if (mInput == nullptr) {
11134 return NO_INIT;
11135 }
11136 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11137}
11138
jiabinc658e452022-10-21 20:52:21 +000011139// ----------------------------------------------------------------------------
11140
Andy Hung4b17e882023-07-07 13:47:37 -070011141/* static */
11142sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011143 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011144 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011145 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011146}
11147
Andy Hung7535ed92023-07-17 17:05:00 -070011148BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011149 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011150 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011151
Andy Hung4b17e882023-07-07 13:47:37 -070011152PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011153 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011154 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11155 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011156 float volumeLeft = 1.0f;
11157 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011158 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11159 const int trackId = mActiveTracks[0]->id();
11160 mAudioMixer->setParameter(
11161 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11162 mAudioMixer->setParameter(
11163 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11164 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011165 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011166 mIsBitPerfect = true;
11167 } else {
11168 mIsBitPerfect = false;
11169 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11170 // active.
11171 for (const auto& track : mActiveTracks) {
11172 const int trackId = track->id();
11173 mAudioMixer->setParameter(
11174 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11175 }
11176 }
jiabin76d94692022-12-15 21:51:21 +000011177 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11178 mVolumeLeft = volumeLeft;
11179 mVolumeRight = volumeRight;
11180 setVolumeForOutput_l(volumeLeft, volumeRight);
11181 }
jiabinc658e452022-10-21 20:52:21 +000011182 return result;
11183}
11184
Andy Hung4b17e882023-07-07 13:47:37 -070011185void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011186 MixerThread::threadLoop_mix();
11187 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11188}
11189
Glenn Kasten63238ef2015-03-02 15:50:29 -080011190} // namespace android