blob: 2b17e92f484b5152415e4d967535f9063c38f087 [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.
Andy Hung0ff14292023-12-20 15:55:16 -0800188static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200189
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();"
Andy Hungef2096d2024-03-21 19:43:05 -0700694
695 // For TimeCheck: track waiting on the thread join of getTid().
696 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
697
Eric Laurent81784c32012-11-19 14:55:58 -0800698 requestExitAndWait();
699}
700
Andy Hung4b17e882023-07-07 13:47:37 -0700701status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800702{
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000703 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hungf8635b62023-08-31 16:13:39 -0700704 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800705
Eric Laurent10351942014-05-08 18:49:52 -0700706 return sendSetParameterConfigEvent_l(keyValuePairs);
707}
708
709// sendConfigEvent_l() must be called with ThreadBase::mLock held
710// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung4b17e882023-07-07 13:47:37 -0700711status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700712NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700713{
714 status_t status = NO_ERROR;
715
Eric Laurent72e3f392015-05-20 14:43:50 -0700716 if (event->mRequiresSystemReady && !mSystemReady) {
717 event->mWaitStatus = false;
718 mPendingConfigEvents.add(event);
719 return status;
720 }
Eric Laurent10351942014-05-08 18:49:52 -0700721 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700722 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungb17d24b2023-08-29 14:26:09 -0700723 mWaitWorkCV.notify_one();
724 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700725 {
Andy Hungb17d24b2023-08-29 14:26:09 -0700726 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700727 while (event->mWaitStatus) {
Andy Hung5529c132024-01-25 17:02:30 -0800728 if (event->mCondition.wait_for(
729 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
730 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700731 event->mStatus = TIMED_OUT;
732 event->mWaitStatus = false;
733 }
734 }
735 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Andy Hungb17d24b2023-08-29 14:26:09 -0700737 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800738 return status;
739}
740
Andy Hung4b17e882023-07-07 13:47:37 -0700741void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700742 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800743{
Andy Hungf8635b62023-08-31 16:13:39 -0700744 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700745 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800746}
747
Andy Hungb17d24b2023-08-29 14:26:09 -0700748// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700749void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700750 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800751{
Andy Hungd0979812019-02-21 15:51:44 -0800752 // The audio statistics history is exponentially weighted to forget events
753 // about five or more seconds in the past. In order to have
754 // crisper statistics for mediametrics, we reset the statistics on
755 // an IoConfigEvent, to reflect different properties for a new device.
756 mIoJitterMs.reset();
757 mLatencyMs.reset();
758 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000759 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100760 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800761
Eric Laurent09f1ed22019-04-24 17:45:17 -0700762 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700763 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800764}
765
Andy Hung4b17e882023-07-07 13:47:37 -0700766void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700767{
Andy Hungf8635b62023-08-31 16:13:39 -0700768 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800769 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700770}
771
Andy Hungb17d24b2023-08-29 14:26:09 -0700772// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700773void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800774 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800775{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800776 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700777 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800778}
779
Andy Hungb17d24b2023-08-29 14:26:09 -0700780// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700781status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800782{
Andy Hung2ddee192015-12-18 17:34:44 -0800783 sp<ConfigEvent> configEvent;
784 AudioParameter param(keyValuePair);
785 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700786 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800787 setMasterMono_l(value != 0);
788 if (param.size() == 1) {
789 return NO_ERROR; // should be a solo parameter - we don't pass down
790 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700791 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800792 configEvent = new SetParameterConfigEvent(param.toString());
793 } else {
794 configEvent = new SetParameterConfigEvent(keyValuePair);
795 }
Eric Laurent10351942014-05-08 18:49:52 -0700796 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700797}
798
Andy Hung4b17e882023-07-07 13:47:37 -0700799status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 const struct audio_patch *patch,
801 audio_patch_handle_t *handle)
802{
Andy Hungf8635b62023-08-31 16:13:39 -0700803 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700804 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
805 status_t status = sendConfigEvent_l(configEvent);
806 if (status == NO_ERROR) {
807 CreateAudioPatchConfigEventData *data =
808 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
809 *handle = data->mHandle;
810 }
811 return status;
812}
813
Andy Hung4b17e882023-07-07 13:47:37 -0700814status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700815 const audio_patch_handle_t handle)
816{
Andy Hungf8635b62023-08-31 16:13:39 -0700817 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700818 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
819 return sendConfigEvent_l(configEvent);
820}
821
Andy Hung4b17e882023-07-07 13:47:37 -0700822status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700823 const DeviceDescriptorBaseVector& outDevices)
824{
825 if (type() != RECORD) {
826 // The update out device operation is only for record thread.
827 return INVALID_OPERATION;
828 }
Andy Hungf8635b62023-08-31 16:13:39 -0700829 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700830 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
831 return sendConfigEvent_l(configEvent);
832}
833
Andy Hung4b17e882023-07-07 13:47:37 -0700834void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200835{
836 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
837 sp<ConfigEvent> configEvent =
838 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
839 sendConfigEvent_l(configEvent);
840}
Eric Laurent1c333e22014-05-20 10:48:17 -0700841
Andy Hung4b17e882023-07-07 13:47:37 -0700842void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200843{
Andy Hungf8635b62023-08-31 16:13:39 -0700844 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200845 sendCheckOutputStageEffectsEvent_l();
846}
847
Andy Hung4b17e882023-07-07 13:47:37 -0700848void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200849{
850 sp<ConfigEvent> configEvent =
851 (ConfigEvent *)new CheckOutputStageEffectsEvent();
852 sendConfigEvent_l(configEvent);
853}
854
Andy Hung4b17e882023-07-07 13:47:37 -0700855void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200856{
857 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
858 sendConfigEvent_l(configEvent);
859}
860
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700861// post condition: mConfigEvents.isEmpty()
Andy Hung4b17e882023-07-07 13:47:37 -0700862void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700863{
Eric Laurent10351942014-05-08 18:49:52 -0700864 bool configChanged = false;
865
Eric Laurent81784c32012-11-19 14:55:58 -0800866 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700867 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700868 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800869 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700870 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700871 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700872 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
873 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800874 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700875 true /*asynchronous*/);
876 if (err != 0) {
877 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700878 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700879 }
880 } break;
881 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700882 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hung94dfbb42023-09-06 19:41:47 -0700883 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700884 } break;
885 case CFG_EVENT_SET_PARAMETER: {
886 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
887 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
888 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700889 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000890 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700891 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700892 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700893 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700894 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700895 CreateAudioPatchConfigEventData *data =
896 (CreateAudioPatchConfigEventData *)event->mData.get();
897 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700898 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200899 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700900 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
901 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
902 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700903 } break;
904 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700905 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700906 ReleaseAudioPatchConfigEventData *data =
907 (ReleaseAudioPatchConfigEventData *)event->mData.get();
908 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700909 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200910 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700911 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
912 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
913 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
914 } break;
915 case CFG_EVENT_UPDATE_OUT_DEVICE: {
916 UpdateOutDevicesConfigEventData *data =
917 (UpdateOutDevicesConfigEventData *)event->mData.get();
918 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700919 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200920 case CFG_EVENT_RESIZE_BUFFER: {
921 ResizeBufferConfigEventData *data =
922 (ResizeBufferConfigEventData *)event->mData.get();
923 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
924 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200925
926 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
927 setCheckOutputStageEffects();
928 } break;
929
Eric Laurent68a40a82022-05-03 18:15:04 +0200930 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
931 onHalLatencyModesChanged_l();
932 } break;
933
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700934 default:
Eric Laurent10351942014-05-08 18:49:52 -0700935 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700936 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800937 }
Eric Laurent10351942014-05-08 18:49:52 -0700938 {
Andy Hungf8635b62023-08-31 16:13:39 -0700939 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700940 if (event->mWaitStatus) {
941 event->mWaitStatus = false;
Andy Hungb17d24b2023-08-29 14:26:09 -0700942 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700943 }
944 }
945 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
946 }
947
948 if (configChanged) {
949 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800950 }
Eric Laurent81784c32012-11-19 14:55:58 -0800951}
952
Marco Nelissenb2208842014-02-07 14:00:50 -0800953String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
954 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700955 const audio_channel_representation_t representation =
956 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700957
958 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800959 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700960 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
961 if (output) {
962 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
963 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
964 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700965 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700966 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
967 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
968 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
969 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
970 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
971 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
972 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700978 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
979 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
980 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
981 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
982 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
983 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
984 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700985 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700986 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
987 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700988 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
989 } else {
990 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
991 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
992 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
993 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
994 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
995 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
996 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
997 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
998 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
999 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1000 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1001 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001002 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1003 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1004 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001005 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001006 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1007 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001008 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1009 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1010 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1011 }
1012 const int len = s.length();
1013 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001014 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001015 s.unlockBuffer(len - 2); // remove trailing ", "
1016 }
1017 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001018 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001019 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1020 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1021 return s;
1022 default:
1023 s.appendFormat("unknown mask, representation:%d bits:%#x",
1024 representation, audio_channel_mask_get_bits(mask));
1025 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001026 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001027}
1028
Andy Hung4b17e882023-07-07 13:47:37 -07001029void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001030NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001031{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001032 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1033 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1034
Andy Hungb17d24b2023-08-29 14:26:09 -07001035 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001036 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001037 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001038 }
1039
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001040 dumpBase_l(fd, args);
1041 dumpInternals_l(fd, args);
1042 dumpTracks_l(fd, args);
1043 dumpEffectChains_l(fd, args);
1044
1045 if (locked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001046 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001047 }
1048
1049 dprintf(fd, " Local log:\n");
1050 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001051
1052 // --all does the statistics
1053 bool dumpAll = false;
1054 for (const auto &arg : args) {
1055 if (arg == String16("--all")) {
1056 dumpAll = true;
1057 }
1058 }
1059 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001060 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001061 if (!sched.empty()) {
1062 (void)write(fd, sched.c_str(), sched.size());
1063 }
1064 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001065}
1066
Andy Hung4b17e882023-07-07 13:47:37 -07001067void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001068{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001069 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001070 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001071 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001072 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung409572b2023-07-19 12:47:35 -07001073 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1074 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001075 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001076 dprintf(fd, " Channel count: %u\n", mChannelCount);
1077 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001078 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung409572b2023-07-19 12:47:35 -07001079 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1080 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001081 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001082 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001083 size_t numConfig = mConfigEvents.size();
1084 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001085 const size_t SIZE = 256;
1086 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001087 for (size_t i = 0; i < numConfig; i++) {
1088 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001089 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001090 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001091 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001092 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001093 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001094 }
Andy Hung293558a2017-03-21 12:19:20 -07001095 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001096 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001097 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001098 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001099 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001100 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001101
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001102 // Dump timestamp statistics for the Thread types that support it.
1103 if (mType == RECORD
1104 || mType == MIXER
1105 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001106 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001107 || mType == OFFLOAD
1108 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001109 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hung94dfbb42023-09-06 19:41:47 -07001110 dprintf(fd, " Timestamp corrected: %s\n",
1111 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001112 }
1113
Andy Hung446f4df2019-02-21 12:26:41 -08001114 if (mLastIoBeginNs > 0) { // MMAP may not set this
1115 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1116 isOutput() ? "write" : "read",
1117 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1118 }
1119
1120 if (mProcessTimeMs.getN() > 0) {
1121 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1122 }
1123
1124 if (mIoJitterMs.getN() > 0) {
1125 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1126 isOutput() ? "write" : "read",
1127 mIoJitterMs.toString().c_str());
1128 }
1129
Andy Hunge6c37112019-02-26 17:38:10 -08001130 if (mLatencyMs.getN() > 0) {
1131 dprintf(fd, " Threadloop %s latency stats: %s\n",
1132 isOutput() ? "write" : "read",
1133 mLatencyMs.toString().c_str());
1134 }
Robert Wu06db0a32021-08-10 19:05:34 +00001135
1136 if (mMonopipePipeDepthStats.getN() > 0) {
1137 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1138 isOutput() ? "write" : "read",
1139 mMonopipePipeDepthStats.toString().c_str());
1140 }
Eric Laurent81784c32012-11-19 14:55:58 -08001141}
1142
Andy Hung4b17e882023-07-07 13:47:37 -07001143void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001144{
1145 const size_t SIZE = 256;
1146 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001147
Marco Nelissenb2208842014-02-07 14:00:50 -08001148 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001149 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001150 write(fd, buffer, strlen(buffer));
1151
Marco Nelissenb2208842014-02-07 14:00:50 -08001152 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001153 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001154 if (chain != 0) {
1155 chain->dump(fd, args);
1156 }
1157 }
1158}
1159
Andy Hung4b17e882023-07-07 13:47:37 -07001160void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001161{
Andy Hungf8635b62023-08-31 16:13:39 -07001162 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001163 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001164}
1165
Andy Hung4b17e882023-07-07 13:47:37 -07001166String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001167{
1168 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001169 case MIXER:
1170 return String16("AudioMix");
1171 case DIRECT:
1172 return String16("AudioDirectOut");
1173 case DUPLICATING:
1174 return String16("AudioDup");
1175 case RECORD:
1176 return String16("AudioIn");
1177 case OFFLOAD:
1178 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001179 case MMAP_PLAYBACK:
1180 return String16("MmapPlayback");
1181 case MMAP_CAPTURE:
1182 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001183 case SPATIALIZER:
1184 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001185 default:
1186 ALOG_ASSERT(false);
1187 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001188 }
1189}
1190
Andy Hung4b17e882023-07-07 13:47:37 -07001191void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001192{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001193 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001194 if (mPowerManager != 0) {
1195 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001196 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001197 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1198 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001199 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001200 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001201 {} /* workSource */,
1202 {} /* historyTag */);
1203 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001204 mWakeLockToken = binder;
1205 }
Chris Ye6597d732020-02-28 22:38:25 -08001206 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001207 }
Wei Jia3f273d12015-11-24 09:06:49 -08001208
Andy Hung3f0c9022016-01-15 17:49:46 -08001209 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001210 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1211 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001212}
1213
Andy Hung4b17e882023-07-07 13:47:37 -07001214void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001215{
Andy Hungf8635b62023-08-31 16:13:39 -07001216 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001217 releaseWakeLock_l();
1218}
1219
Andy Hung4b17e882023-07-07 13:47:37 -07001220void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001221{
Andy Hung3f0c9022016-01-15 17:49:46 -08001222 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001223 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001224 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001225 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001226 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001227 }
1228 mWakeLockToken.clear();
1229 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001230}
1231
Andy Hung4b17e882023-07-07 13:47:37 -07001232void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001233 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001234 // use checkService() to avoid blocking if power service is not up yet
1235 sp<IBinder> binder =
1236 defaultServiceManager()->checkService(String16("power"));
1237 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001238 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001239 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001240 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001241 binder->linkToDeath(mDeathRecipient);
1242 }
1243 }
1244}
1245
Andy Hung4b17e882023-07-07 13:47:37 -07001246void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001247 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001248
1249#if !LOG_NDEBUG
1250 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001251 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001252 s << uid << " ";
1253 }
1254 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1255#endif
1256
Andy Hung438e7572015-12-14 15:51:17 -08001257 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1258 if (mSystemReady) {
1259 ALOGE("no wake lock to update, but system ready!");
1260 } else {
1261 ALOGW("no wake lock to update, system not ready yet");
1262 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001263 return;
1264 }
1265 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001266 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001267 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1268 mWakeLockToken, uidsAsInt);
1269 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001270 }
1271}
1272
Andy Hung4b17e882023-07-07 13:47:37 -07001273void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001274{
Andy Hungf8635b62023-08-31 16:13:39 -07001275 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001276 releaseWakeLock_l();
1277 mPowerManager.clear();
1278}
1279
Andy Hung4b17e882023-07-07 13:47:37 -07001280void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001281 const DeviceDescriptorBaseVector& outDevices __unused)
1282{
1283 ALOGE("%s should only be called in RecordThread", __func__);
1284}
1285
Andy Hung4b17e882023-07-07 13:47:37 -07001286void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001287{
1288 ALOGE("%s should only be called in RecordThread", __func__);
1289}
1290
Andy Hung4b17e882023-07-07 13:47:37 -07001291void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001292{
1293 sp<ThreadBase> thread = mThread.promote();
1294 if (thread != 0) {
1295 thread->clearPowerManager();
1296 }
1297 ALOGW("power manager service died !!!");
1298}
1299
Andy Hung4b17e882023-07-07 13:47:37 -07001300void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001301 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001302{
Andy Hung116bc262023-06-20 18:56:17 -07001303 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001304 if (chain != 0) {
1305 if (type != NULL) {
1306 chain->setEffectSuspended_l(type, suspend);
1307 } else {
1308 chain->setEffectSuspendedAll_l(suspend);
1309 }
1310 }
1311
1312 updateSuspendedSessions_l(type, suspend, sessionId);
1313}
1314
Andy Hung4b17e882023-07-07 13:47:37 -07001315void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001316{
1317 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1318 if (index < 0) {
1319 return;
1320 }
1321
1322 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1323 mSuspendedSessions.valueAt(index);
1324
1325 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001326 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001327 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001328 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001329 chain->setEffectSuspendedAll_l(true);
1330 } else {
1331 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1332 desc->mType.timeLow);
1333 chain->setEffectSuspended_l(&desc->mType, true);
1334 }
1335 }
1336 }
1337}
1338
Andy Hung4b17e882023-07-07 13:47:37 -07001339void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001340 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001341 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001342{
1343 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1344
1345 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1346
1347 if (suspend) {
1348 if (index >= 0) {
1349 sessionEffects = mSuspendedSessions.valueAt(index);
1350 } else {
1351 mSuspendedSessions.add(sessionId, sessionEffects);
1352 }
1353 } else {
1354 if (index < 0) {
1355 return;
1356 }
1357 sessionEffects = mSuspendedSessions.valueAt(index);
1358 }
1359
1360
Andy Hung116bc262023-06-20 18:56:17 -07001361 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001362 if (type != NULL) {
1363 key = type->timeLow;
1364 }
1365 index = sessionEffects.indexOfKey(key);
1366
1367 sp<SuspendedSessionDesc> desc;
1368 if (suspend) {
1369 if (index >= 0) {
1370 desc = sessionEffects.valueAt(index);
1371 } else {
1372 desc = new SuspendedSessionDesc();
1373 if (type != NULL) {
1374 desc->mType = *type;
1375 }
1376 sessionEffects.add(key, desc);
1377 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1378 }
1379 desc->mRefCount++;
1380 } else {
1381 if (index < 0) {
1382 return;
1383 }
1384 desc = sessionEffects.valueAt(index);
1385 if (--desc->mRefCount == 0) {
1386 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1387 sessionEffects.removeItemsAt(index);
1388 if (sessionEffects.isEmpty()) {
1389 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1390 sessionId);
1391 mSuspendedSessions.removeItem(sessionId);
1392 }
1393 }
1394 }
1395 if (!sessionEffects.isEmpty()) {
1396 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1397 }
1398}
1399
Andy Hung4b17e882023-07-07 13:47:37 -07001400void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001401 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001402 bool threadLocked)
1403NO_THREAD_SAFETY_ANALYSIS // manual locking
1404{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001405 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001406 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001407 }
Eric Laurent81784c32012-11-19 14:55:58 -08001408
Eric Laurent81784c32012-11-19 14:55:58 -08001409 if (mType != RECORD) {
1410 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1411 // another session. This gives the priority to well behaved effect control panels
1412 // and applications not using global effects.
1413 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1414 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001415 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001416 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1417 }
1418 }
1419
Eric Laurent6b446ce2019-12-13 10:56:31 -08001420 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001421 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001422 }
1423}
1424
Andy Hungb17d24b2023-08-29 14:26:09 -07001425// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001426status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001427 const effect_descriptor_t *desc, audio_session_t sessionId)
1428{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001429 // No global output effect sessions on record threads
1430 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1431 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001432 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1433 desc->name, mThreadName);
1434 return BAD_VALUE;
1435 }
1436 // only pre processing effects on record thread
1437 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1438 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1439 desc->name, mThreadName);
1440 return BAD_VALUE;
1441 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001442
1443 // always allow effects without processing load or latency
1444 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1445 return NO_ERROR;
1446 }
1447
Eric Laurent4c415062016-06-17 16:14:16 -07001448 audio_input_flags_t flags = mInput->flags;
1449 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1450 if (flags & AUDIO_INPUT_FLAG_RAW) {
1451 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1452 desc->name, mThreadName);
1453 return BAD_VALUE;
1454 }
1455 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1456 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1457 desc->name, mThreadName);
1458 return BAD_VALUE;
1459 }
1460 }
jiabineb3bda02020-06-30 14:07:03 -07001461
Andy Hung116bc262023-06-20 18:56:17 -07001462 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001463 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1464 return BAD_VALUE;
1465 }
Eric Laurent4c415062016-06-17 16:14:16 -07001466 return NO_ERROR;
1467}
1468
Andy Hungb17d24b2023-08-29 14:26:09 -07001469// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001470status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001471 const effect_descriptor_t *desc, audio_session_t sessionId)
1472{
1473 // no preprocessing on playback threads
1474 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001475 ALOGW("%s: pre processing effect %s created on playback"
1476 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001477 return BAD_VALUE;
1478 }
1479
Eric Laurent3e4de772017-07-16 16:55:08 -07001480 // always allow effects without processing load or latency
1481 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1482 return NO_ERROR;
1483 }
1484
Andy Hung116bc262023-06-20 18:56:17 -07001485 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001486 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1487 __func__);
1488 return BAD_VALUE;
1489 }
1490
Eric Laurentf690c462021-09-17 14:47:03 +02001491 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1492 && mType != SPATIALIZER) {
1493 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1494 __func__, mType);
1495 return BAD_VALUE;
1496 }
1497
Eric Laurent4c415062016-06-17 16:14:16 -07001498 switch (mType) {
1499 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001500 audio_output_flags_t flags = mOutput->flags;
1501 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1502 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1503 // global effects are applied only to non fast tracks if they are SW
1504 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1505 break;
1506 }
1507 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1508 // only post processing on output stage session
1509 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001510 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1511 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001512 return BAD_VALUE;
1513 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001514 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1515 // only post processing on output stage session
1516 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001517 ALOGW("%s: non post processing effect %s not allowed on device session",
1518 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001519 return BAD_VALUE;
1520 }
Eric Laurent4c415062016-06-17 16:14:16 -07001521 } else {
1522 // no restriction on effects applied on non fast tracks
1523 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1524 break;
1525 }
1526 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001527
Eric Laurent4c415062016-06-17 16:14:16 -07001528 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001529 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001530 return BAD_VALUE;
1531 }
1532 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001533 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1534 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001535 return BAD_VALUE;
1536 }
1537 }
1538 } break;
1539 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001540 // nothing actionable on offload threads, if the effect:
1541 // - is offloadable: the effect can be created
1542 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1543 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001544 break;
1545 case DIRECT:
1546 // Reject any effect on Direct output threads for now, since the format of
1547 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001548 ALOGW("%s: effect %s on DIRECT output thread %s",
1549 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001550 return BAD_VALUE;
1551 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001552 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001553 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1554 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001555 return BAD_VALUE;
1556 }
1557 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001558 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1559 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001560 return BAD_VALUE;
1561 }
1562 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001563 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1564 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001565 return BAD_VALUE;
1566 }
1567 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001568 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001569 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1570 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1571 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1572 // are supported and added after the spatializer.
1573 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1574 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1575 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001576 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001577 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1578 // only post processing , downmixer or spatializer effects on output stage session
1579 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1580 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1581 break;
1582 }
1583 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1584 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1585 __func__, desc->name);
1586 return BAD_VALUE;
1587 }
1588 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1589 // only post processing on output stage session
1590 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1591 ALOGW("%s: non post processing effect %s not allowed on device session",
1592 __func__, desc->name);
1593 return BAD_VALUE;
1594 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001595 }
1596 break;
jiabinc658e452022-10-21 20:52:21 +00001597 case BIT_PERFECT:
1598 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1599 // Allow HW accelerated effects of tunnel type
1600 break;
1601 }
1602 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1603 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1604 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1605 // 3) there is any bit-perfect track with the given session id.
1606 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1607 sessionId == AUDIO_SESSION_DEVICE) {
1608 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1609 __func__, desc->name, mThreadName);
1610 return BAD_VALUE;
1611 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1612 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1613 __func__, desc->name, sessionId);
1614 return BAD_VALUE;
1615 }
1616 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001617 default:
1618 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1619 }
1620
1621 return NO_ERROR;
1622}
1623
Andy Hungb17d24b2023-08-29 14:26:09 -07001624// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001625sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001626 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001627 const sp<IEffectClient>& effectClient,
1628 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001629 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001630 effect_descriptor_t *desc,
1631 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001632 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001633 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001634 bool probe,
1635 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001636{
Andy Hung116bc262023-06-20 18:56:17 -07001637 sp<IAfEffectModule> effect;
1638 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001639 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001640 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001641 bool chainCreated = false;
1642 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001643 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001644
1645 lStatus = initCheck();
1646 if (lStatus != NO_ERROR) {
1647 ALOGW("createEffect_l() Audio driver not initialized.");
1648 goto Exit;
1649 }
1650
Eric Laurent81784c32012-11-19 14:55:58 -08001651 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1652
Andy Hungb17d24b2023-08-29 14:26:09 -07001653 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07001654 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001655
Eric Laurent4c415062016-06-17 16:14:16 -07001656 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001657 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001658 goto Exit;
1659 }
1660
Eric Laurent81784c32012-11-19 14:55:58 -08001661 // check for existing effect chain with the requested audio session
1662 chain = getEffectChain_l(sessionId);
1663 if (chain == 0) {
1664 // create a new chain for this session
1665 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001666 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001667 addEffectChain_l(chain);
1668 chain->setStrategy(getStrategyForSession_l(sessionId));
1669 chainCreated = true;
1670 } else {
1671 effect = chain->getEffectFromDesc_l(desc);
1672 }
1673
1674 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1675
1676 if (effect == 0) {
Andy Hung7535ed92023-07-17 17:05:00 -07001677 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001678 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001679 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001680 if (lStatus != NO_ERROR) {
1681 goto Exit;
1682 }
1683 effectCreated = true;
1684
jiabinc52b1ff2019-10-31 17:20:42 -07001685 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001686 effect->setDevices(outDeviceTypeAddrs());
1687 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001688 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001689 effect->setAudioSource(mAudioSource);
1690 }
jiabin1319f5a2021-03-30 22:21:24 +00001691 if (effect->isHapticGenerator()) {
1692 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1693 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001694 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung7535ed92023-07-17 17:05:00 -07001695 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001696 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001697 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001698 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001699 }
1700 }
Eric Laurent81784c32012-11-19 14:55:58 -08001701 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001702 handle = IAfEffectHandle::create(
1703 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001704 lStatus = handle->initCheck();
1705 if (lStatus == OK) {
1706 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001707 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001708 }
Eric Laurent81784c32012-11-19 14:55:58 -08001709 if (enabled != NULL) {
1710 *enabled = (int)effect->isEnabled();
1711 }
1712 }
1713
1714Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001715 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hungf8635b62023-08-31 16:13:39 -07001716 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001717 if (effectCreated) {
1718 chain->removeEffect_l(effect);
1719 }
Eric Laurent81784c32012-11-19 14:55:58 -08001720 if (chainCreated) {
1721 removeEffectChain_l(chain);
1722 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001723 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001724 }
1725
Glenn Kasten9156ef32013-08-06 15:39:08 -07001726 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001727 return handle;
1728}
1729
Andy Hung4b17e882023-07-07 13:47:37 -07001730void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001731 bool unpinIfLast)
1732{
1733 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001734 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001735 {
Andy Hungf8635b62023-08-31 16:13:39 -07001736 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001737 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001738 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001739 return;
1740 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001741 effect = effectBase->asEffectModule();
1742 if (effect == nullptr) {
1743 return;
1744 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001745 // restore suspended effects if the disconnected handle was enabled and the last one.
1746 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1747 if (remove) {
1748 removeEffect_l(effect, true);
1749 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001750 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001751 }
1752 if (remove) {
Andy Hung7535ed92023-07-17 17:05:00 -07001753 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001754 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001755 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001756 }
1757 }
1758}
1759
Andy Hung4b17e882023-07-07 13:47:37 -07001760void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001761 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001762 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001763 broadcast_l();
1764 }
1765 if (!effect->isOffloadable()) {
1766 if (mType == ThreadBase::OFFLOAD) {
1767 PlaybackThread *t = (PlaybackThread *)this;
1768 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1769 }
1770 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung7535ed92023-07-17 17:05:00 -07001771 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001772 }
1773 }
1774}
1775
Andy Hung4b17e882023-07-07 13:47:37 -07001776void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001777 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001778 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001779 broadcast_l();
1780 }
1781}
1782
Andy Hung4b17e882023-07-07 13:47:37 -07001783sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001784 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001785{
Andy Hungf8635b62023-08-31 16:13:39 -07001786 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001787 return getEffect_l(sessionId, effectId);
1788}
1789
Andy Hung4b17e882023-07-07 13:47:37 -07001790sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001791 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001792{
Andy Hung116bc262023-06-20 18:56:17 -07001793 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001794 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1795}
1796
Andy Hung4b17e882023-07-07 13:47:37 -07001797std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001798{
Andy Hung116bc262023-06-20 18:56:17 -07001799 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001800 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1801}
1802
Andy Hungf8635b62023-08-31 16:13:39 -07001803// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1804// ThreadBase::mutex() held
1805status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001806{
1807 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001808 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001809 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001810 bool chainCreated = false;
1811
Eric Laurent5baf2af2013-09-12 17:37:00 -07001812 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hungf8635b62023-08-31 16:13:39 -07001813 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1814 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001815
Eric Laurent81784c32012-11-19 14:55:58 -08001816 if (chain == 0) {
1817 // create a new chain for this session
Andy Hungf8635b62023-08-31 16:13:39 -07001818 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001819 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001820 addEffectChain_l(chain);
1821 chain->setStrategy(getStrategyForSession_l(sessionId));
1822 chainCreated = true;
1823 }
Andy Hungf8635b62023-08-31 16:13:39 -07001824 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001825
1826 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hungf8635b62023-08-31 16:13:39 -07001827 ALOGW("%s: %p effect %s already present in chain %p",
1828 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001829 return BAD_VALUE;
1830 }
1831
Eric Laurent5baf2af2013-09-12 17:37:00 -07001832 effect->setOffloaded(mType == OFFLOAD, mId);
1833
Eric Laurent81784c32012-11-19 14:55:58 -08001834 status_t status = chain->addEffect_l(effect);
1835 if (status != NO_ERROR) {
1836 if (chainCreated) {
1837 removeEffectChain_l(chain);
1838 }
1839 return status;
1840 }
1841
jiabin8f278ee2019-11-11 12:16:27 -08001842 effect->setDevices(outDeviceTypeAddrs());
1843 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001844 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001845 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001846
Eric Laurent81784c32012-11-19 14:55:58 -08001847 return NO_ERROR;
1848}
1849
Andy Hung4b17e882023-07-07 13:47:37 -07001850void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001851
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001852 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001853 effect_descriptor_t desc = effect->desc();
1854 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1855 detachAuxEffect_l(effect->id());
1856 }
1857
Andy Hung116bc262023-06-20 18:56:17 -07001858 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001859 if (chain != 0) {
1860 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001861 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001862 removeEffectChain_l(chain);
1863 }
1864 } else {
1865 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1866 }
1867}
1868
Andy Hung4b17e882023-07-07 13:47:37 -07001869void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001870 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001871NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001872{
1873 effectChains = mEffectChains;
1874 for (size_t i = 0; i < mEffectChains.size(); i++) {
Andy Hung1f6d4cd2023-08-29 12:19:17 -07001875 mEffectChains[i]->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001876 }
1877}
1878
Andy Hung4b17e882023-07-07 13:47:37 -07001879void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001880 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001881NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001882{
1883 for (size_t i = 0; i < effectChains.size(); i++) {
Andy Hung1f6d4cd2023-08-29 12:19:17 -07001884 effectChains[i]->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001885 }
1886}
1887
Andy Hung4b17e882023-07-07 13:47:37 -07001888sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001889{
Andy Hungf8635b62023-08-31 16:13:39 -07001890 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001891 return getEffectChain_l(sessionId);
1892}
1893
Andy Hung4b17e882023-07-07 13:47:37 -07001894sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001895 const
Eric Laurent81784c32012-11-19 14:55:58 -08001896{
1897 size_t size = mEffectChains.size();
1898 for (size_t i = 0; i < size; i++) {
1899 if (mEffectChains[i]->sessionId() == sessionId) {
1900 return mEffectChains[i];
1901 }
1902 }
1903 return 0;
1904}
1905
Andy Hung4b17e882023-07-07 13:47:37 -07001906void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001907{
Andy Hungf8635b62023-08-31 16:13:39 -07001908 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001909 size_t size = mEffectChains.size();
1910 for (size_t i = 0; i < size; i++) {
1911 mEffectChains[i]->setMode_l(mode);
1912 }
1913}
1914
Andy Hung4b17e882023-07-07 13:47:37 -07001915void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001916{
1917 config->type = AUDIO_PORT_TYPE_MIX;
1918 config->ext.mix.handle = mId;
1919 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001920 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001921 config->channel_mask = mChannelMask;
1922 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1923 AUDIO_PORT_CONFIG_FORMAT;
1924}
1925
Andy Hung4b17e882023-07-07 13:47:37 -07001926void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001927{
Andy Hungf8635b62023-08-31 16:13:39 -07001928 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001929 if (mSystemReady) {
1930 return;
1931 }
1932 mSystemReady = true;
1933
1934 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1935 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1936 }
1937 mPendingConfigEvents.clear();
1938}
1939
Andy Hungdae27702016-10-31 14:01:16 -07001940template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001941ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001942 ssize_t index = mActiveTracks.indexOf(track);
1943 if (index >= 0) {
1944 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1945 return index;
1946 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001947 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001948 mActiveTracksGeneration++;
1949 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001950 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001951 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001952 return mActiveTracks.add(track);
1953}
1954
1955template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001956ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001957 ssize_t index = mActiveTracks.remove(track);
1958 if (index < 0) {
1959 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1960 return index;
1961 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001962 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001963 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001964 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001965 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001966 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001967#ifdef TEE_SINK
1968 track->dumpTee(-1 /* fd */, "_REMOVE");
1969#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001970 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001971 return index;
1972}
1973
1974template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001975void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001976 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001977 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001978 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001979 }
1980 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001981 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001982 mActiveTracks.clear();
1983 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001984}
1985
1986template <typename T>
Andy Hung94dfbb42023-09-06 19:41:47 -07001987void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001988 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001989 // Updates ActiveTracks client uids to the thread wakelock.
1990 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1991 thread->updateWakeLockUids_l(getWakeLockUids());
1992 mLastActiveTracksGeneration = mActiveTracksGeneration;
1993 }
Andy Hungdae27702016-10-31 14:01:16 -07001994}
Eric Laurent83b88082014-06-20 18:31:16 -07001995
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001996template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001997bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001998 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001999 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002000
2001 for (const sp<T> &track : mActiveTracks) {
2002 // Do not short-circuit as all hasChanged states must be reset
2003 // as all the metadata are going to be sent
2004 hasChanged |= track->readAndClearHasChanged();
2005 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002006 return hasChanged;
2007}
2008
2009template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002010void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002011 const char *funcName, const sp<T> &track) const {
2012 if (mLocalLog != nullptr) {
2013 String8 result;
2014 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002015 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002016 }
2017}
2018
Andy Hung4b17e882023-07-07 13:47:37 -07002019void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002020{
2021 // Thread could be blocked waiting for async
2022 // so signal it to handle state changes immediately
2023 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2024 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2025 mSignalPending = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07002026 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002027}
2028
Andy Hungd0979812019-02-21 15:51:44 -08002029// Call only from threadLoop() or when it is idle.
2030// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07002031void ThreadBase::sendStatistics(bool force)
Andy Hung94dfbb42023-09-06 19:41:47 -07002032NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002033{
2034 // Do not log if we have no stats.
2035 // We choose the timestamp verifier because it is the most likely item to be present.
2036 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2037 if (nstats == 0) {
2038 return;
2039 }
2040
2041 // Don't log more frequently than once per 12 hours.
2042 // We use BOOTTIME to include suspend time.
2043 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2044 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2045 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2046 return;
2047 }
2048
2049 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2050 mLastRecordedTimeNs = timeNs;
2051
Ray Essickf27e9872019-12-07 06:28:46 -08002052 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002053
2054#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2055
2056 // thread configuration
2057 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2058 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2059 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2060 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2061 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2062 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2063 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hung94dfbb42023-09-06 19:41:47 -07002064 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2065 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002066
2067 // thread statistics
2068 if (mIoJitterMs.getN() > 0) {
2069 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2070 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2071 }
2072 if (mProcessTimeMs.getN() > 0) {
2073 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2074 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2075 }
2076 const auto tsjitter = mTimestampVerifier.getJitterMs();
2077 if (tsjitter.getN() > 0) {
2078 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2079 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2080 }
2081 if (mLatencyMs.getN() > 0) {
2082 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2083 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2084 }
Robert Wu06db0a32021-08-10 19:05:34 +00002085 if (mMonopipePipeDepthStats.getN() > 0) {
2086 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2087 mMonopipePipeDepthStats.getMean());
2088 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2089 mMonopipePipeDepthStats.getStdDev());
2090 }
Andy Hungd0979812019-02-21 15:51:44 -08002091
2092 item->selfrecord();
2093}
2094
Andy Hung4b17e882023-07-07 13:47:37 -07002095product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002096{
Andy Hung7535ed92023-07-17 17:05:00 -07002097 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002098 return PRODUCT_STRATEGY_NONE;
2099 }
2100 return AudioSystem::getStrategyForStream(stream);
2101}
2102
Andy Hungb17d24b2023-08-29 14:26:09 -07002103// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002104void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002105 const sp<audio_utils::MelProcessor>& /*processor*/)
2106{
2107 // Do nothing
2108 ALOGW("%s: ThreadBase does not support CSD", __func__);
2109}
2110
Andy Hungb17d24b2023-08-29 14:26:09 -07002111// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002112void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002113{
2114 // Do nothing
2115 ALOGW("%s: ThreadBase does not support CSD", __func__);
2116}
2117
Eric Laurent81784c32012-11-19 14:55:58 -08002118// ----------------------------------------------------------------------------
2119// Playback
2120// ----------------------------------------------------------------------------
2121
Andy Hung7535ed92023-07-17 17:05:00 -07002122PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002123 AudioStreamOut* output,
2124 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002125 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002126 bool systemReady,
2127 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002128 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002129 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002130 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002131 mMixerBuffer(NULL),
2132 mMixerBufferSize(0),
2133 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2134 mMixerBufferValid(false),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002135 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002136 mEffectBuffer(NULL),
2137 mEffectBufferSize(0),
2138 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2139 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002140 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002141 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002142 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002143 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002144 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002145 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002146 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002147 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002148 mMixerStatus(MIXER_IDLE),
2149 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hungd58c4732023-07-20 21:31:38 -07002150 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151 mBytesRemaining(0),
2152 mCurrentWriteLength(0),
2153 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002154 mWriteAckSequence(0),
2155 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002156 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002157 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002158 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002159 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002160 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002161 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002162 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002163{
Glenn Kastend7dca052015-03-05 16:05:54 -08002164 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002165 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002166
Andy Hungb17d24b2023-08-29 14:26:09 -07002167 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002168 // it would be safer to explicitly pass initial masterVolume/masterMute as
2169 // parameter.
2170 //
2171 // If the HAL we are using has support for master volume or master mute,
2172 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2173 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002174 mMasterVolume = afThreadCallback->masterVolume_l();
2175 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002176 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002177 if (mOutput->audioHwDev->canSetMasterVolume()) {
2178 mMasterVolume = 1.0;
2179 }
2180
2181 if (mOutput->audioHwDev->canSetMasterMute()) {
2182 mMasterMute = false;
2183 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002184 mIsMsdDevice = strcmp(
2185 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002186 }
2187
Eric Laurentf1f22e72021-07-13 14:04:14 +02002188 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2189 mMixerChannelMask = mixerConfig->channel_mask;
2190 }
2191
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002192 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002193
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002194 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002195 && mMixerChannelMask != mChannelMask) {
2196 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2197 mChannelMask, mMixerChannelMask);
2198 }
2199
Andy Hungc8fddf32018-08-08 18:32:37 -07002200 // TODO: We may also match on address as well as device type for
2201 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002202 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002203 // TODO: This property should be ensure that only contains one single device type.
2204 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2205 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002206 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2207 : AUDIO_DEVICE_NONE));
2208 }
2209
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002210 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2211 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002212 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002213 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002214 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002215 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002216 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2217 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002218 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2219 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002220}
2221
Andy Hung4b17e882023-07-07 13:47:37 -07002222PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002223{
Andy Hung7535ed92023-07-17 17:05:00 -07002224 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002225 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002226 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002227 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002228 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002229}
2230
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002231// Thread virtuals
2232
Andy Hung4b17e882023-07-07 13:47:37 -07002233void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002234{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002235 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002236 ALOGE("The stream is not open yet"); // This should not happen.
2237 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002238 // Callbacks take strong or weak pointers as a parameter.
2239 // Since PlaybackThread passes itself as a callback handler, it can only
2240 // be done outside of the constructor. Creating weak and especially strong
2241 // pointers to a refcounted object in its own constructor is strongly
2242 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2243 // Even if a function takes a weak pointer, it is possible that it will
2244 // need to convert it to a strong pointer down the line.
2245 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2246 mOutput->stream->setCallback(this) == OK) {
2247 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002248 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002249 }
2250
jiabinf6eb4c32020-02-25 14:06:25 -08002251 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002252 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002253 }
2254 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002255 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002256 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002257}
2258
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002259// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002260void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002261{
2262 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002263 status_t result = mOutput->stream->exit();
2264 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002265}
2266
Andy Hung4b17e882023-07-07 13:47:37 -07002267void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002268{
Eric Laurent81784c32012-11-19 14:55:58 -08002269 String8 result;
2270
Marco Nelissenb2208842014-02-07 14:00:50 -08002271 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002272 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2273 const stream_type_t *st = &mStreamTypes[i];
2274 if (i > 0) {
2275 result.appendFormat(", ");
2276 }
2277 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2278 if (st->mute) {
2279 result.append("M");
2280 }
2281 }
2282 result.append("\n");
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002283 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002284 result.clear();
2285
Eric Laurent81784c32012-11-19 14:55:58 -08002286 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2287 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002288 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002289 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002290
2291 size_t numtracks = mTracks.size();
2292 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002293 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002294 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002295 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002296 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002297 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002298 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002299 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002300 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002301 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002302 if (track != 0) {
2303 bool active = mActiveTracks.indexOf(track) >= 0;
2304 if (active) {
2305 numactiveseen++;
2306 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002307 result.append(prefix);
2308 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002309 }
2310 }
2311 } else {
2312 result.append("\n");
2313 }
2314 if (numactiveseen != numactive) {
2315 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002316 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002317 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002318 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002319 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002320 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002321 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002322 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002323 result.append(prefix);
2324 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002325 }
2326 }
2327 }
2328
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002329 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002330}
2331
Andy Hung4b17e882023-07-07 13:47:37 -07002332void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002333{
Andy Hung04cb8f72020-03-20 13:44:33 -07002334 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002335 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002336 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2337 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002338 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2339 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2340 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2341 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002342 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002343 dprintf(fd, " Total writes: %d\n", mNumWrites);
2344 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2345 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung160664b2023-09-15 18:19:28 -07002346 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002347 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002348 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002349 AudioStreamOut *output = mOutput;
2350 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002351 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002352 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002353 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2354 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2355 if (mPipeSink.get() != nullptr) {
2356 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2357 }
2358 if (output != nullptr) {
2359 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002360 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002361 }
Eric Laurent81784c32012-11-19 14:55:58 -08002362}
2363
Andy Hungb17d24b2023-08-29 14:26:09 -07002364// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002365sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002366 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002367 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002368 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002369 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002370 audio_format_t format,
2371 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002372 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002373 size_t *pNotificationFrameCount,
2374 uint32_t notificationsPerBuffer,
2375 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002376 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002377 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002378 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002379 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002380 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002381 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002382 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002383 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002384 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002385 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002386 bool isBitPerfect,
2387 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002388{
Glenn Kasten74935e42013-12-19 08:56:45 -08002389 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002390 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002391 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002392 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002393 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002394 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002395 uint32_t sampleRate;
2396
2397 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2398 lStatus = BAD_VALUE;
2399 goto Exit;
2400 }
Eric Laurent21da6472017-11-09 16:29:26 -08002401
2402 if (*pSampleRate == 0) {
2403 *pSampleRate = mSampleRate;
2404 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002405 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002406
2407 // special case for FAST flag considered OK if fast mixer is present
2408 if (hasFastMixer()) {
2409 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2410 }
2411
2412 // Check if requested flags are compatible with output stream flags
2413 if ((*flags & outputFlags) != *flags) {
2414 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2415 *flags, outputFlags);
2416 *flags = (audio_output_flags_t)(*flags & outputFlags);
2417 }
Eric Laurent81784c32012-11-19 14:55:58 -08002418
jiabinc658e452022-10-21 20:52:21 +00002419 if (isBitPerfect) {
Andy Hung160664b2023-09-15 18:19:28 -07002420 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002421 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002422 if (chain.get() != nullptr) {
2423 // Bit-perfect is required according to the configuration and preferred mixer
2424 // attributes, but it is not in the output flag from the client's request. Explicitly
2425 // adding bit-perfect flag to check the compatibility
2426 audio_output_flags_t flagsToCheck =
2427 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2428 chain->checkOutputFlagCompatibility(&flagsToCheck);
2429 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2430 ALOGE("%s cannot create track as there is data-processing effect attached to "
2431 "given session id(%d)", __func__, sessionId);
2432 lStatus = BAD_VALUE;
2433 goto Exit;
2434 }
2435 *flags = flagsToCheck;
2436 }
2437 }
2438
Eric Laurent81784c32012-11-19 14:55:58 -08002439 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002440 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002441 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002442 // PCM data
2443 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002444 // TODO: extract as a data library function that checks that a computationally
2445 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002446 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002447 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2448 (channelMask == AUDIO_CHANNEL_OUT_MONO
2449 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // hardware sample rate
2451 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002452 // normal mixer has an associated fast mixer
2453 hasFastMixer() &&
2454 // there are sufficient fast track slots available
2455 (mFastTrackAvailMask != 0)
2456 // FIXME test that MixerThread for this fast track has a capable output HAL
2457 // FIXME add a permission test also?
2458 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002459 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2460 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002461 // read the fast track multiplier property the first time it is needed
2462 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2463 if (ok != 0) {
2464 ALOGE("%s pthread_once failed: %d", __func__, ok);
2465 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002466 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002467 }
Eric Laurent4c415062016-06-17 16:14:16 -07002468
2469 // check compatibility with audio effects.
Andy Hungb17d24b2023-08-29 14:26:09 -07002470 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002471 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002472 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002473 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002474 AUDIO_SESSION_OUTPUT_STAGE,
2475 AUDIO_SESSION_OUTPUT_MIX,
2476 sessionId,
2477 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002478 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002479 if (chain.get() != nullptr) {
2480 audio_output_flags_t old = *flags;
2481 chain->checkOutputFlagCompatibility(flags);
2482 if (old != *flags) {
2483 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2484 (int)session, (int)old, (int)*flags);
2485 }
Eric Laurent4c415062016-06-17 16:14:16 -07002486 }
2487 }
2488 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002489 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002490 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2491 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002492 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002493 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002494 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002495 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002496 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002497 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002498 audio_is_linear_pcm(format), channelMask, sampleRate,
2499 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002500 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002501 }
2502 }
Eric Laurent21da6472017-11-09 16:29:26 -08002503
2504 if (!audio_has_proportional_frames(format)) {
2505 if (sharedBuffer != 0) {
2506 // Same comment as below about ignoring frameCount parameter for set()
2507 frameCount = sharedBuffer->size();
2508 } else if (frameCount == 0) {
2509 frameCount = mNormalFrameCount;
2510 }
2511 if (notificationFrameCount != frameCount) {
2512 notificationFrameCount = frameCount;
2513 }
2514 } else if (sharedBuffer != 0) {
2515 // FIXME: Ensure client side memory buffers need
2516 // not have additional alignment beyond sample
2517 // (e.g. 16 bit stereo accessed as 32 bit frame).
2518 size_t alignment = audio_bytes_per_sample(format);
2519 if (alignment & 1) {
2520 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2521 alignment = 1;
2522 }
2523 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2524 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2525 if (channelCount > 1) {
2526 // More than 2 channels does not require stronger alignment than stereo
2527 alignment <<= 1;
2528 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002529 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002530 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002531 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002532 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002533 goto Exit;
2534 }
Eric Laurent21da6472017-11-09 16:29:26 -08002535
2536 // When initializing a shared buffer AudioTrack via constructors,
2537 // there's no frameCount parameter.
2538 // But when initializing a shared buffer AudioTrack via set(),
2539 // there _is_ a frameCount parameter. We silently ignore it.
2540 frameCount = sharedBuffer->size() / frameSize;
2541 } else {
2542 size_t minFrameCount = 0;
2543 // For fast tracks we try to respect the application's request for notifications per buffer.
2544 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2545 if (notificationsPerBuffer > 0) {
2546 // Avoid possible arithmetic overflow during multiplication.
2547 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2548 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2549 notificationsPerBuffer, mFrameCount);
2550 } else {
2551 minFrameCount = mFrameCount * notificationsPerBuffer;
2552 }
2553 }
2554 } else {
2555 // For normal PCM streaming tracks, update minimum frame count.
2556 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2557 // cover audio hardware latency.
2558 // This is probably too conservative, but legacy application code may depend on it.
2559 // If you change this calculation, also review the start threshold which is related.
2560 uint32_t latencyMs = latency_l();
2561 if (latencyMs == 0) {
2562 ALOGE("Error when retrieving output stream latency");
2563 lStatus = UNKNOWN_ERROR;
2564 goto Exit;
2565 }
2566
2567 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2568 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2569
Eric Laurent81784c32012-11-19 14:55:58 -08002570 }
Eric Laurent21da6472017-11-09 16:29:26 -08002571 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002572 frameCount = minFrameCount;
2573 }
Eric Laurent81784c32012-11-19 14:55:58 -08002574 }
Eric Laurent21da6472017-11-09 16:29:26 -08002575
2576 // Make sure that application is notified with sufficient margin before underrun.
2577 // The client can divide the AudioTrack buffer into sub-buffers,
2578 // and expresses its desire to server as the notification frame count.
2579 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2580 size_t maxNotificationFrames;
2581 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2582 // notify every HAL buffer, regardless of the size of the track buffer
2583 maxNotificationFrames = mFrameCount;
2584 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002585 // Triple buffer the notification period for a triple buffered mixer period;
2586 // otherwise, double buffering for the notification period is fine.
2587 //
2588 // TODO: This should be moved to AudioTrack to modify the notification period
2589 // on AudioTrack::setBufferSizeInFrames() changes.
2590 const int nBuffering =
2591 (uint64_t{frameCount} * mSampleRate)
2592 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2593
Eric Laurent21da6472017-11-09 16:29:26 -08002594 maxNotificationFrames = frameCount / nBuffering;
2595 // If client requested a fast track but this was denied, then use the smaller maximum.
2596 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2597 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2598 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2599 maxNotificationFrames = maxNotificationFramesFastDenied;
2600 }
2601 }
2602 }
2603 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2604 if (notificationFrameCount == 0) {
2605 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2606 maxNotificationFrames, frameCount);
2607 } else {
2608 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2609 notificationFrameCount, maxNotificationFrames, frameCount);
2610 }
2611 notificationFrameCount = maxNotificationFrames;
2612 }
2613 }
2614
Glenn Kasten74935e42013-12-19 08:56:45 -08002615 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002616 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002617
Glenn Kastenc3df8382014-03-13 15:05:25 -07002618 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002619 case BIT_PERFECT:
2620 if (isBitPerfect) {
2621 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2622 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2623 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2624 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2625 mChannelMask);
2626 lStatus = BAD_VALUE;
2627 goto Exit;
2628 }
2629 }
2630 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002631
2632 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002633 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002634 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002635 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2636 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002637 sampleRate, format, channelMask, mOutput, mFormat);
2638 lStatus = BAD_VALUE;
2639 goto Exit;
2640 }
2641 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002642 break;
2643
2644 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002646 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2647 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 sampleRate, format, channelMask, mOutput, mFormat);
2649 lStatus = BAD_VALUE;
2650 goto Exit;
2651 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002652 break;
2653
2654 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002655 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002656 ALOGE("createTrack_l() Bad parameter: format %#x \""
2657 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 format, mOutput, mFormat);
2659 lStatus = BAD_VALUE;
2660 goto Exit;
2661 }
Andy Hungcd044842014-08-07 11:04:34 -07002662 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002663 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2664 lStatus = BAD_VALUE;
2665 goto Exit;
2666 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002667 break;
2668
Eric Laurent81784c32012-11-19 14:55:58 -08002669 }
2670
2671 lStatus = initCheck();
2672 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002673 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002674 goto Exit;
2675 }
2676
Andy Hungb17d24b2023-08-29 14:26:09 -07002677 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002678 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002679
2680 // all tracks in same audio session must share the same routing strategy otherwise
2681 // conflicts will happen when tracks are moved from one output to another by audio policy
2682 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002683 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002684 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002685 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002686 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002687 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002688 if (sessionId == t->sessionId() && strategy != actual) {
2689 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2690 strategy, actual);
2691 lStatus = BAD_VALUE;
2692 goto Exit;
2693 }
2694 }
2695 }
2696
Deeraj Soman2b515232024-05-14 12:58:24 +05302697 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2698 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002699 // dynamic audio policy.
2700 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302701 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002702 audio_output_flags_t trackFlags = *flags;
2703 if (mType == DIRECT) {
2704 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302705 } else if (mType == OFFLOAD) {
2706 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2707 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002708 }
jiabin94ed47c2023-07-27 23:34:20 +00002709 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002710
Andy Hung11e74242023-06-26 19:20:57 -07002711 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002712 channelMask, frameCount,
2713 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002714 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002715 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002716 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002717
Glenn Kasten03003332013-08-06 15:40:54 -07002718 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2719 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002720 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002721 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002722 goto Exit;
2723 }
2724 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002725 {
Andy Hungf8635b62023-08-31 16:13:39 -07002726 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002727 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002728 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002729 }
2730 }
Eric Laurent81784c32012-11-19 14:55:58 -08002731
Andy Hung116bc262023-06-20 18:56:17 -07002732 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002733 if (chain != 0) {
2734 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2735 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002736 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002737 chain->incTrackCnt();
2738 }
2739
Eric Laurent05067782016-06-01 18:27:28 -07002740 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002741 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2742 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2743 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002744 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002745 }
2746 }
2747
2748 lStatus = NO_ERROR;
2749
2750Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002751 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002752 return track;
2753}
2754
Andy Hung1bc088a2018-02-09 15:57:31 -08002755template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002756ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002757{
Andy Hungc0691382018-09-12 18:01:57 -07002758 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002759 const ssize_t index = mTracks.remove(track);
2760 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002761 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002762 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002763 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002764 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002765 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002766 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002767 }
2768 return index;
2769}
2770
Andy Hung4b17e882023-07-07 13:47:37 -07002771uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002772{
2773 return latency;
2774}
2775
Andy Hung4b17e882023-07-07 13:47:37 -07002776uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002777{
Andy Hungf8635b62023-08-31 16:13:39 -07002778 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002779 return latency_l();
2780}
Andy Hung4b17e882023-07-07 13:47:37 -07002781uint32_t PlaybackThread::latency_l() const
Andy Hung94dfbb42023-09-06 19:41:47 -07002782NO_THREAD_SAFETY_ANALYSIS
2783// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002784{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002785 uint32_t latency;
2786 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2787 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002788 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002789 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002790}
2791
Andy Hung4b17e882023-07-07 13:47:37 -07002792void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
Andy Hungf8635b62023-08-31 16:13:39 -07002794 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002795 // Don't apply master volume in SW if our HAL can do it for us.
2796 if (mOutput && mOutput->audioHwDev &&
2797 mOutput->audioHwDev->canSetMasterVolume()) {
2798 mMasterVolume = 1.0;
2799 } else {
2800 mMasterVolume = value;
2801 }
2802}
2803
Andy Hung4b17e882023-07-07 13:47:37 -07002804void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002805{
2806 mMasterBalance.store(balance);
2807}
2808
Andy Hung4b17e882023-07-07 13:47:37 -07002809void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002810{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002811 if (isDuplicating()) {
2812 return;
2813 }
Andy Hungf8635b62023-08-31 16:13:39 -07002814 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002815 // Don't apply master mute in SW if our HAL can do it for us.
2816 if (mOutput && mOutput->audioHwDev &&
2817 mOutput->audioHwDev->canSetMasterMute()) {
2818 mMasterMute = false;
2819 } else {
2820 mMasterMute = muted;
2821 }
2822}
2823
Andy Hung4b17e882023-07-07 13:47:37 -07002824void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002825{
Andy Hungf8635b62023-08-31 16:13:39 -07002826 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002827 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002828 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002829}
2830
Andy Hung4b17e882023-07-07 13:47:37 -07002831void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002832{
Andy Hungf8635b62023-08-31 16:13:39 -07002833 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002834 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002835 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002836}
2837
Andy Hung4b17e882023-07-07 13:47:37 -07002838float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002839{
Andy Hungf8635b62023-08-31 16:13:39 -07002840 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002841 return mStreamTypes[stream].volume;
2842}
2843
Andy Hung4b17e882023-07-07 13:47:37 -07002844void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002845{
2846 mOutput->stream->setVolume(left, right);
2847}
2848
Andy Hungb17d24b2023-08-29 14:26:09 -07002849// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002850status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002851{
2852 status_t status = ALREADY_EXISTS;
2853
Eric Laurent81784c32012-11-19 14:55:58 -08002854 if (mActiveTracks.indexOf(track) < 0) {
2855 // the track is newly added, make sure it fills up all its
2856 // buffers before playing. This is to ensure the client will
2857 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002858 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002859 IAfTrackBase::track_state state = track->state();
Andy Hunga7187712023-12-05 17:28:17 -08002860 // Because the track is not on the ActiveTracks,
2861 // at this point, only the TrackHandle will be adding the track.
Andy Hungb17d24b2023-08-29 14:26:09 -07002862 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002863 status = AudioSystem::startOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002864 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002865 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002866 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002867 if (status == NO_ERROR) {
Andy Hungb17d24b2023-08-29 14:26:09 -07002868 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002869 AudioSystem::stopOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002870 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871 }
2872 return INVALID_OPERATION;
2873 }
2874 // abort if start is rejected by audio policy manager
2875 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002876 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2877 // current playback thread is reopened, which may happen when clients set preferred
2878 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2879 // immediately.
2880 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881 }
2882#ifdef ADD_BATTERY_DATA
2883 // to track the speaker usage
2884 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2885#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002886 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 }
2888
Eric Laurent51716182016-02-29 18:00:56 -08002889 // set retry count for buffer fill
2890 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002891 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002892 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002893 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002894 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002895 }
Andy Hung11e74242023-06-26 19:20:57 -07002896 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002897 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002898 track->retryCount() = kMaxTrackStartupRetries;
2899 track->fillingStatus() =
2900 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002901 }
2902
Andy Hung116bc262023-06-20 18:56:17 -07002903 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002904 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2905 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2906 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002907 // Unlock due to VibratorService will lock for this call and will
2908 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungb17d24b2023-08-29 14:26:09 -07002909 mutex().unlock();
Andy Hung76cb9152023-07-20 21:23:42 -07002910 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002911 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002912 std::optional<media::AudioVibratorInfo> vibratorInfo;
2913 {
2914 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2915 // used to play this track.
Andy Hungf8635b62023-08-31 16:13:39 -07002916 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung7535ed92023-07-17 17:05:00 -07002917 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002918 }
Andy Hungb17d24b2023-08-29 14:26:09 -07002919 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002920 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002921 if (vibratorInfo) {
2922 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2923 }
2924
jiabin57303cc2018-12-18 15:45:57 -08002925 // Haptic playback should be enabled by vibrator service.
2926 if (track->getHapticPlaybackEnabled()) {
2927 // Disable haptic playback of all active track to ensure only
2928 // one track playing haptic if current track should play haptic.
2929 for (const auto &t : mActiveTracks) {
2930 t->setHapticPlaybackEnabled(false);
2931 }
jiabin245cdd92018-12-07 17:55:15 -08002932 }
jiabine70bc7f2020-06-30 22:07:55 -07002933
2934 // Set haptic intensity for effect
2935 if (chain != nullptr) {
2936 chain->setHapticIntensity_l(track->id(), intensity);
2937 }
jiabin245cdd92018-12-07 17:55:15 -08002938 }
2939
Andy Hung11e74242023-06-26 19:20:57 -07002940 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002941 track->resetPresentationComplete();
Andy Hunga7187712023-12-05 17:28:17 -08002942
2943 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2944 // all key changes are complete. It is possible that the threadLoop will begin
2945 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002946 mActiveTracks.add(track);
Andy Hunga7187712023-12-05 17:28:17 -08002947
Eric Laurentd0107bc2013-06-11 14:38:48 -07002948 if (chain != 0) {
2949 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2950 track->sessionId());
2951 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002952 }
2953
Andy Hungc2b11cb2020-04-22 09:04:01 -07002954 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002955 status = NO_ERROR;
2956 }
2957
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002958 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002959 return status;
2960}
2961
Andy Hung4b17e882023-07-07 13:47:37 -07002962bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002963{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002964 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002965 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002966 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002967 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002968 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002969 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002970 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002971 if (track->isPausePending()) {
2972 track->pauseAck();
2973 }
Andy Hung11e74242023-06-26 19:20:57 -07002974 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002975 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002976
2977 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002978}
2979
Andy Hung4b17e882023-07-07 13:47:37 -07002980void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002981{
2982 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002983
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002984 String8 result;
2985 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002986 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002987
Eric Laurent81784c32012-11-19 14:55:58 -08002988 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002989 {
Andy Hungf8635b62023-08-31 16:13:39 -07002990 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002991 mAudioTrackCallbacks.erase(track);
2992 }
Eric Laurent81784c32012-11-19 14:55:58 -08002993 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002994 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002995 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002996 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2997 mFastTrackAvailMask |= 1 << index;
2998 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07002999 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003000 }
Andy Hung116bc262023-06-20 18:56:17 -07003001 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003002 if (chain != 0) {
3003 chain->decTrackCnt();
3004 }
3005}
3006
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003007std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3008{
3009 std::set<int32_t> result;
3010 for (const auto& t : mTracks) {
3011 if (t->isExternalTrack()) {
3012 result.insert(t->portId());
3013 }
3014 }
3015 return result;
3016}
3017
3018std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3019{
3020 audio_utils::lock_guard _l(mutex());
3021 return getTrackPortIds_l();
3022}
3023
Andy Hung4b17e882023-07-07 13:47:37 -07003024String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003025{
Andy Hungf8635b62023-08-31 16:13:39 -07003026 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003027 String8 out_s8;
3028 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3029 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003030 }
Andy Hung920f6572022-10-06 12:09:49 -07003031 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003032}
3033
Andy Hung4b17e882023-07-07 13:47:37 -07003034status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hungf8635b62023-08-31 16:13:39 -07003035 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003036 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003037 return NO_INIT;
3038 }
3039 return mOutput->stream->selectPresentation(presentationId, programId);
3040}
3041
Andy Hung94dfbb42023-09-06 19:41:47 -07003042void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003043 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003044 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003045 sp<AudioIoDescriptor> desc;
3046 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003047 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003048 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003049 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003050 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003051 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3052 mSampleRate, mFormat, mChannelMask,
3053 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3054 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003055 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003056 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003057 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003058 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003059 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003060 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003061 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003062 break;
3063 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003064 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003065}
3066
Andy Hung4b17e882023-07-07 13:47:37 -07003067void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003068{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003069 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003070}
3071
Andy Hung4b17e882023-07-07 13:47:37 -07003072void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003073{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003074 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003075}
3076
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003077void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003078{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003079 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003080}
3081
Andy Hung4b17e882023-07-07 13:47:37 -07003082void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003083 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003084{
Andy Hung4b17e882023-07-07 13:47:37 -07003085 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003086 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07003087 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003088 if (playbackThread == nullptr) {
3089 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3090 return;
3091 }
3092
jiabinf6eb4c32020-02-25 14:06:25 -08003093 audio_utils::metadata::Data metadata =
3094 audio_utils::metadata::dataFromByteString(metadataBs);
3095 if (metadata.empty()) {
3096 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3097 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3098 (int)metadataBs.size());
3099 return;
3100 }
3101
3102 audio_utils::metadata::ByteString metaDataStr =
3103 audio_utils::metadata::byteStringFromData(metadata);
3104 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hungf8635b62023-08-31 16:13:39 -07003105 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003106 for (const auto& callbackPair : mAudioTrackCallbacks) {
3107 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003108 }
3109 }).detach();
3110}
3111
Andy Hung4b17e882023-07-07 13:47:37 -07003112void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003113{
Andy Hungf8635b62023-08-31 16:13:39 -07003114 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003115 // reject out of sequence requests
3116 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3117 mWriteAckSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003118 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119 }
3120}
3121
Andy Hung4b17e882023-07-07 13:47:37 -07003122void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003123{
Andy Hungf8635b62023-08-31 16:13:39 -07003124 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003125 // reject out of sequence requests
3126 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003127 // Register discontinuity when HW drain is completed because that can cause
3128 // the timestamp frame position to reset to 0 for direct and offload threads.
3129 // (Out of sequence requests are ignored, since the discontinuity would be handled
3130 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003131 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003132 mDrainSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003133 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 }
3135}
3136
Andy Hung4b17e882023-07-07 13:47:37 -07003137void PlaybackThread::readOutputParameters_l()
Andy Hungf8635b62023-08-31 16:13:39 -07003138NO_THREAD_SAFETY_ANALYSIS
3139// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003140{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003141 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003142 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3143 mSampleRate = audioConfig.sample_rate;
3144 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003145 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003146 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003147 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003148 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003149 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3150 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003151 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003152
3153 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3154 mMixerChannelMask = mChannelMask;
3155 }
3156
Andy Hunge5412692014-05-16 11:25:07 -07003157 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003158 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003159
Eric Laurentf1f22e72021-07-13 14:04:14 +02003160 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3161
Phil Burkca5e6142015-07-14 09:42:29 -07003162 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003163 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003164 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003165 // Get format from the shim, which will be different than the HAL format
3166 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003167 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003168 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003169 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003170 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003171 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003172 LOG_FATAL("HAL format %#x not supported for mixed output",
3173 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003174 }
Phil Burk062e67a2015-02-11 13:40:50 -08003175 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003176 result = mOutput->stream->getBufferSize(&mBufferSize);
3177 LOG_ALWAYS_FATAL_IF(result != OK,
3178 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003179 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003180 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003181 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003182 mFrameCount);
3183 }
3184
Eric Laurentd1f69b02014-12-15 14:33:13 -08003185 mHwSupportsPause = false;
3186 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003187 bool supportsPause = false, supportsResume = false;
3188 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3189 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003190 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003191 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003192 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003193 } else if (supportsResume) {
3194 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003195 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003196 }
3197 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003198 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3199 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3200 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003201
Andy Hungfbfc3952015-01-15 13:33:51 -08003202 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3203 // For best precision, we use float instead of the associated output
3204 // device format (typically PCM 16 bit).
3205
3206 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3207 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3208 mBufferSize = mFrameSize * mFrameCount;
3209
3210 // TODO: We currently use the associated output device channel mask and sample rate.
3211 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3212 // (if a valid mask) to avoid premature downmix.
3213 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3214 // instead of the output device sample rate to avoid loss of high frequency information.
3215 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3216 }
3217
Andy Hung09a50072014-02-27 14:30:47 -08003218 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003219 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003220 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003221 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3222 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003223 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3224 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003225
Eric Laurent81784c32012-11-19 14:55:58 -08003226 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3227 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3228 maxNormalFrameCount = maxNormalFrameCount & ~15;
3229 if (maxNormalFrameCount < minNormalFrameCount) {
3230 maxNormalFrameCount = minNormalFrameCount;
3231 }
3232 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3233 if (multiplier <= 1.0) {
3234 multiplier = 1.0;
3235 } else if (multiplier <= 2.0) {
3236 if (2 * mFrameCount <= maxNormalFrameCount) {
3237 multiplier = 2.0;
3238 } else {
3239 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3240 }
3241 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003242 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003243 }
3244 }
3245 mNormalFrameCount = multiplier * mFrameCount;
3246 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003247 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003248 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3249 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003250 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3251 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003252
Andy Hung08fb1742015-05-31 23:22:10 -07003253 // Check if we want to throttle the processing to no more than 2x normal rate
3254 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003255 mThreadThrottleTimeMs = 0;
3256 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003257 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3258
Andy Hung010a1a12014-03-13 13:57:33 -07003259 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3260 // Originally this was int16_t[] array, need to remove legacy implications.
3261 free(mSinkBuffer);
3262 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003263
Andy Hung5b10a202014-03-13 13:59:29 -07003264 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3265 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3266 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003267 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003268
Andy Hung69aed5f2014-02-25 17:24:40 -08003269 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3270 // drives the output.
3271 free(mMixerBuffer);
3272 mMixerBuffer = NULL;
3273 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003274 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003275 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003276 * audio_bytes_per_sample(mMixerBufferFormat);
3277 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3278 }
Andy Hung98ef9782014-03-04 14:46:50 -08003279 free(mEffectBuffer);
3280 mEffectBuffer = NULL;
3281 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003282 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003283 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003284 * audio_bytes_per_sample(mEffectBufferFormat);
3285 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3286 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003287
Eric Laurentb62d0362021-10-26 17:40:18 +02003288 if (mType == SPATIALIZER) {
3289 free(mPostSpatializerBuffer);
3290 mPostSpatializerBuffer = nullptr;
3291 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3292 * audio_bytes_per_sample(mEffectBufferFormat);
3293 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3294 }
3295
Mikhail Naganov55773032020-10-01 15:08:13 -07003296 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3297 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003298 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3299 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003300 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003301
Eric Laurent81784c32012-11-19 14:55:58 -08003302 // force reconfiguration of effect chains and engines to take new buffer size and audio
3303 // parameters into account
Andy Hungb17d24b2023-08-29 14:26:09 -07003304 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003305 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3306 // matter.
Andy Hungf8635b62023-08-31 16:13:39 -07003307 // create a copy of mEffectChains as calling moveEffectChain_ll()
3308 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003309 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003310 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hungf8635b62023-08-31 16:13:39 -07003311 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003312 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003313 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003314
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003315 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003316 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003317 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07003318 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003319 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3320 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3321 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3322 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3323 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3324 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3325 (int32_t)mHapticChannelMask)
3326 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3327 (int32_t)mHapticChannelCount)
3328 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -07003329 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003330 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3331 (int32_t)mFrameCount) // sic - added HAL
3332 ;
3333 uint32_t latencyMs;
3334 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3335 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3336 }
3337 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003338}
3339
Andy Hung4b17e882023-07-07 13:47:37 -07003340ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003341{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003342 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003343 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003344 }
3345 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003346 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07003347 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003348 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003349 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003350 }
Kevin Rocard12381092018-04-11 09:19:59 -07003351 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003352 MetadataUpdate change;
3353 change.playbackMetadataUpdate = metadata.tracks;
3354 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003355}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003356
Andy Hung4b17e882023-07-07 13:47:37 -07003357void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003358 const StreamOutHalInterface::SourceMetadata& metadata)
3359{
3360 mOutput->stream->updateSourceMetadata(metadata);
3361};
3362
Andy Hung4b17e882023-07-07 13:47:37 -07003363status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003364 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003365{
3366 if (halFrames == NULL || dspFrames == NULL) {
3367 return BAD_VALUE;
3368 }
Andy Hungf8635b62023-08-31 16:13:39 -07003369 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003370 if (initCheck() != NO_ERROR) {
3371 return INVALID_OPERATION;
3372 }
Andy Hung818e7a32016-02-16 18:08:07 -08003373 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003374 *halFrames = framesWritten;
3375
3376 if (isSuspended()) {
3377 // return an estimation of rendered frames when the output is suspended
3378 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003379 *dspFrames = (uint32_t)
3380 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003381 return NO_ERROR;
3382 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003383 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003384 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003385 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003386 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003387 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003388 }
3389}
3390
Andy Hung4b17e882023-07-07 13:47:37 -07003391product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003392{
3393 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3394 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3395 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003396 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003397 }
3398 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003399 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003400 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003401 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003402 }
3403 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003404 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003405}
3406
3407
Andy Hung4b17e882023-07-07 13:47:37 -07003408AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003409{
Andy Hungf8635b62023-08-31 16:13:39 -07003410 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003411 return mOutput;
3412}
3413
Andy Hung4b17e882023-07-07 13:47:37 -07003414AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003415{
Andy Hungf8635b62023-08-31 16:13:39 -07003416 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003417 AudioStreamOut *output = mOutput;
3418 mOutput = NULL;
3419 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3420 // must push a NULL and wait for ack
3421 mOutputSink.clear();
3422 mPipeSink.clear();
3423 mNormalSink.clear();
3424 return output;
3425}
3426
Andy Hungb17d24b2023-08-29 14:26:09 -07003427// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003428sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003429{
3430 if (mOutput == NULL) {
3431 return NULL;
3432 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003433 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003434}
3435
Andy Hung4b17e882023-07-07 13:47:37 -07003436uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003437{
3438 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3439}
3440
Andy Hung4b17e882023-07-07 13:47:37 -07003441status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003442{
3443 if (!isValidSyncEvent(event)) {
3444 return BAD_VALUE;
3445 }
3446
Andy Hungf8635b62023-08-31 16:13:39 -07003447 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003448
3449 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003450 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003451 if (event->triggerSession() == track->sessionId()) {
3452 (void) track->setSyncEvent(event);
3453 return NO_ERROR;
3454 }
3455 }
3456
3457 return NAME_NOT_FOUND;
3458}
3459
Andy Hung4b17e882023-07-07 13:47:37 -07003460bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003461{
3462 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3463}
3464
Andy Hung4b17e882023-07-07 13:47:37 -07003465void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003466 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003467{
Andy Hungfe726a62018-09-27 15:17:25 -07003468 // Miscellaneous track cleanup when removed from the active list,
3469 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003470#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003471 for (const auto& track : tracksToRemove) {
3472 if (track->isExternalTrack()) {
3473 // to track the speaker usage
3474 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003475 }
3476 }
Andy Hungfe726a62018-09-27 15:17:25 -07003477#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003478}
3479
Andy Hung4b17e882023-07-07 13:47:37 -07003480void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003481{
3482 if (!mMasterMute) {
3483 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003484 if (mOutDeviceTypeAddrs.empty()) {
3485 ALOGD("ro.audio.silent is ignored since no output device is set");
3486 return;
3487 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003488 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003489 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3490 return;
3491 }
Eric Laurent81784c32012-11-19 14:55:58 -08003492 if (property_get("ro.audio.silent", value, "0") > 0) {
3493 char *endptr;
3494 unsigned long ul = strtoul(value, &endptr, 0);
3495 if (*endptr == '\0' && ul != 0) {
3496 ALOGD("Silence is golden");
3497 // The setprop command will not allow a property to be changed after
3498 // the first time it is set, so we don't have to worry about un-muting.
3499 setMasterMute_l(true);
3500 }
3501 }
3502 }
3503}
3504
3505// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003506ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003507{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003508 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003509 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003511 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003512
3513 // If an NBAIO sink is present, use it to write the normal mixer's submix
3514 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003515
Andy Hung010a1a12014-03-13 13:57:33 -07003516 const size_t count = mBytesRemaining / mFrameSize;
3517
Simon Wilson2d590962012-11-29 15:18:50 -08003518 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003519 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003520 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003521 if (screenState != mScreenState) {
3522 mScreenState = screenState;
3523 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3524 if (pipe != NULL) {
3525 pipe->setAvgFrames((mScreenState & 1) ?
3526 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3527 }
3528 }
Andy Hung010a1a12014-03-13 13:57:33 -07003529 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003530 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003531
Eric Laurent81784c32012-11-19 14:55:58 -08003532 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003533 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003534
Andy Hung8946a282018-04-19 20:04:56 -07003535#ifdef TEE_SINK
3536 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3537#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003538 } else {
3539 bytesWritten = framesWritten;
3540 }
3541 // otherwise use the HAL / AudioStreamOut directly
3542 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003543 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003544
Eric Laurentbfb1b832013-01-07 09:53:42 -08003545 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003546 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3547 mWriteAckSequence += 2;
3548 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003550 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003551 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003552 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003553 // FIXME We should have an implementation of timestamps for direct output threads.
3554 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003555 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003556 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003557
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558 if (mUseAsyncWrite &&
3559 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3560 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003561 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003562 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003563 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003564 }
Eric Laurent81784c32012-11-19 14:55:58 -08003565 }
3566
Eric Laurent81784c32012-11-19 14:55:58 -08003567 mNumWrites++;
3568 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003569 if (mStandby) {
3570 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003571 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003572 mStandby = false;
3573 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 return bytesWritten;
3575}
3576
Andy Hungb17d24b2023-08-29 14:26:09 -07003577// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003578void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003579 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003580{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003581 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003582 if (outputSink != nullptr) {
3583 outputSink->startMelComputation(processor);
3584 }
Vlad Popab042ee62022-10-20 18:05:00 +02003585}
3586
Andy Hungb17d24b2023-08-29 14:26:09 -07003587// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003588void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003589{
3590 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003591 if (outputSink != nullptr) {
3592 outputSink->stopMelComputation();
3593 }
Vlad Popab042ee62022-10-20 18:05:00 +02003594}
3595
Andy Hung4b17e882023-07-07 13:47:37 -07003596void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003597{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003598 bool supportsDrain = false;
3599 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003600 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3601 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003602 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3603 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003604 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003605 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003606 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003607 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003608 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003609 }
3610}
3611
Andy Hung4b17e882023-07-07 13:47:37 -07003612void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003613{
Eric Laurent275e8e92014-11-30 15:14:47 -08003614 {
Andy Hungf8635b62023-08-31 16:13:39 -07003615 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003616 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003617 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003618 track->invalidate();
3619 }
Andy Hungdae27702016-10-31 14:01:16 -07003620 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3621 // After we exit there are no more track changes sent to BatteryNotifier
3622 // because that requires an active threadLoop.
3623 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3624 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003625 }
Eric Laurent81784c32012-11-19 14:55:58 -08003626}
3627
3628/*
3629The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003630 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003631 - mActiveSleepTimeUs from activeSleepTimeUs()
3632 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003633 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3634 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003635 - maxPeriod from frame count and sample rate (MIXER only)
3636
3637The parameters that affect these derived values are:
3638 - frame count
3639 - frame size
3640 - sample rate
3641 - device type: A2DP or not
3642 - device latency
3643 - format: PCM or not
3644 - active sleep time
3645 - idle sleep time
3646*/
3647
Andy Hung4b17e882023-07-07 13:47:37 -07003648void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003649{
Andy Hung25c2dac2014-02-27 14:56:00 -08003650 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003651 mActiveSleepTimeUs = activeSleepTimeUs();
3652 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003653
Andy Hungd58c4732023-07-20 21:31:38 -07003654 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003655
Eric Laurent42537be2016-01-08 17:16:42 -08003656 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3657 // truncating audio when going to standby.
Andy Hung94dfbb42023-09-06 19:41:47 -07003658 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003659 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3660 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3661 }
3662 }
Eric Laurent81784c32012-11-19 14:55:58 -08003663}
3664
Andy Hung4b17e882023-07-07 13:47:37 -07003665bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003666{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003667 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003668 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003669 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003670 size_t size = mTracks.size();
3671 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003672 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003673 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003674 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003675 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003676 }
3677 }
Eric Laurent13084622016-05-17 10:51:49 -07003678 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003679}
3680
Andy Hung4b17e882023-07-07 13:47:37 -07003681void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003682{
Andy Hungf8635b62023-08-31 16:13:39 -07003683 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003684 invalidateTracks_l(streamType);
3685}
3686
Andy Hung4b17e882023-07-07 13:47:37 -07003687void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07003688 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003689 invalidateTracks_l(portIds);
3690}
3691
Andy Hung4b17e882023-07-07 13:47:37 -07003692bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003693 bool trackMatch = false;
3694 const size_t size = mTracks.size();
3695 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003696 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003697 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3698 t->invalidate();
3699 portIds.erase(t->portId());
3700 trackMatch = true;
3701 }
3702 if (portIds.empty()) {
3703 break;
3704 }
3705 }
3706 return trackMatch;
3707}
3708
jiabinf042b9b2021-05-07 23:46:28 +00003709// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003710IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003711 audio_port_handle_t trackPortId) {
3712 for (size_t i = 0; i < mTracks.size(); i++) {
3713 if (mTracks[i]->portId() == trackPortId) {
3714 return mTracks[i].get();
3715 }
3716 }
3717 return nullptr;
3718}
3719
Andy Hung4b17e882023-07-07 13:47:37 -07003720status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003721{
Glenn Kastend848eb42016-03-08 13:42:11 -08003722 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003723 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003724 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003725
Andy Hungd3639922022-04-28 18:00:49 -07003726 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003727 if (!audio_is_global_session(session)) {
3728 // player sessions on a spatializer output will use a dedicated input buffer and
3729 // will either output multi channel to mEffectBuffer if the track is spatilaized
3730 // or stereo to mPostSpatializerBuffer if not spatialized.
3731 uint32_t channelMask;
3732 bool isSessionSpatialized =
3733 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3734 if (isSessionSpatialized) {
3735 channelMask = mMixerChannelMask;
3736 } else {
3737 channelMask = mChannelMask;
3738 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003739 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003740 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003741 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003742 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003743 &halInBuffer);
3744 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003745
Andy Hung7535ed92023-07-17 17:05:00 -07003746 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003747 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3748 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3749 &halOutBuffer);
3750 if (result != OK) return result;
3751
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003752 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003753
Mikhail Naganov022b9952017-01-04 16:36:51 -08003754 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3755 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003756 } else {
3757 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3758 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3759 // mPostSpatializerBuffer as output buffer
3760 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003761 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003762 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3763 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003764 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003765 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3766 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003767
Eric Laurentb62d0362021-10-26 17:40:18 +02003768 if (session == AUDIO_SESSION_DEVICE) {
3769 halInBuffer = halOutBuffer;
3770 }
3771 }
3772 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003773 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003774 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3775 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3776 &halInBuffer);
3777 if (result != OK) return result;
3778 halOutBuffer = halInBuffer;
3779 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3780 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003781 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003782 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003783 // Only one effect chain can be present in direct output thread and it uses
3784 // the sink buffer as input
3785 if (mType != DIRECT) {
3786 size_t numSamples = mNormalFrameCount
3787 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3788 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003789 const status_t allocateStatus =
3790 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003791 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003792 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003793 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003794
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003795 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003796 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3797 buffer, session);
3798 }
3799 }
3800 }
3801
3802 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003803 // Attach all tracks with same session ID to this chain.
3804 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003805 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003806 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003807 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3808 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003809 track->setMainBuffer(buffer);
3810 chain->incTrackCnt();
3811 }
3812 }
3813
3814 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003815 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003816 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003817 ALOGV("addEffectChain_l() activating track %p on session %d",
3818 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003819 chain->incActiveTrackCnt();
3820 }
3821 }
3822 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003823
Eric Laurentaaa44472014-09-12 17:41:50 -07003824 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003825 chain->setInBuffer(halInBuffer);
3826 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003827 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3828 // chains list in order to be processed last as it contains output device effects.
3829 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3830 // processing effects specific to an output stream before effects applied to all streams
3831 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003832 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3833 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003834 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003835 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003836 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003837 // Effect chain for other sessions are inserted at beginning of effect
3838 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003839 // sessions is not important.
3840 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003841 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3842 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003843 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003844 size_t size = mEffectChains.size();
3845 size_t i = 0;
3846 for (i = 0; i < size; i++) {
3847 if (mEffectChains[i]->sessionId() < session) {
3848 break;
3849 }
3850 }
3851 mEffectChains.insertAt(chain, i);
3852 checkSuspendOnAddEffectChain_l(chain);
3853
3854 return NO_ERROR;
3855}
3856
Andy Hung4b17e882023-07-07 13:47:37 -07003857size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003858{
Glenn Kastend848eb42016-03-08 13:42:11 -08003859 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003860
3861 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3862
3863 for (size_t i = 0; i < mEffectChains.size(); i++) {
3864 if (chain == mEffectChains[i]) {
3865 mEffectChains.removeAt(i);
3866 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003867 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003868 if (session == track->sessionId()) {
3869 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3870 chain.get(), session);
3871 chain->decActiveTrackCnt();
3872 }
3873 }
3874
3875 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003876 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003877 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003878 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003879 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003880 chain->decTrackCnt();
3881 }
3882 }
3883 break;
3884 }
3885 }
3886 return mEffectChains.size();
3887}
3888
Andy Hung4b17e882023-07-07 13:47:37 -07003889status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003890 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003891{
Andy Hungf8635b62023-08-31 16:13:39 -07003892 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003893 return attachAuxEffect_l(track, EffectId);
3894}
3895
Andy Hung4b17e882023-07-07 13:47:37 -07003896status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003897 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003898{
3899 status_t status = NO_ERROR;
3900
3901 if (EffectId == 0) {
3902 track->setAuxBuffer(0, NULL);
3903 } else {
3904 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003905 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003906 if (effect != 0) {
3907 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3908 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3909 } else {
3910 status = INVALID_OPERATION;
3911 }
3912 } else {
3913 status = BAD_VALUE;
3914 }
3915 }
3916 return status;
3917}
3918
Andy Hung4b17e882023-07-07 13:47:37 -07003919void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003920{
3921 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003922 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003923 if (track->auxEffectId() == effectId) {
3924 attachAuxEffect_l(track, 0);
3925 }
3926 }
3927}
3928
Andy Hung4b17e882023-07-07 13:47:37 -07003929bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003930NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003931{
Andy Hung78d8d952023-05-30 18:10:23 -07003932 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003933
Andy Hung45a38f22023-10-03 10:49:34 -07003934 if (mType == SPATIALIZER) {
3935 const pid_t tid = getTid();
3936 if (tid == -1) { // odd: we are here, we must be a running thread.
3937 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3938 } else {
3939 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3940 if (priorityBoost > 0) {
3941 stream()->setHalThreadPriority(priorityBoost);
3942 }
3943 }
3944 }
3945
Andy Hung11e74242023-06-26 19:20:57 -07003946 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003947
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003948 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003949 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003950
3951 // MIXER
3952 nsecs_t lastWarning = 0;
3953
3954 // DUPLICATING
3955 // FIXME could this be made local to while loop?
3956 writeFrames = 0;
3957
3958 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003959 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003960
Andy Hungd3639922022-04-28 18:00:49 -07003961 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003962 sleepTimeShift = 0;
3963 }
3964
3965 CpuStats cpuStats;
3966 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3967
3968 acquireWakeLock();
3969
Glenn Kasteneef598c2017-04-03 14:41:13 -07003970 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3971 // thread associated with this PlaybackThread.
3972 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3973 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003974 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3975 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003976 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003977 const char *logString = NULL;
3978
rago1bb90822017-05-02 18:31:48 -07003979 // Estimated time for next buffer to be written to hal. This is used only on
3980 // suspended mode (for now) to help schedule the wait time until next iteration.
3981 nsecs_t timeLoopNextNs = 0;
3982
Eric Laurent664539d2013-09-23 18:24:31 -07003983 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003984
Andy Hung2dbffc22018-08-08 18:50:41 -07003985 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003986
Eric Laurentb3f315a2021-07-13 15:09:05 +02003987 sendCheckOutputStageEffectsEvent();
3988
Andy Hung446f4df2019-02-21 12:26:41 -08003989 // loopCount is used for statistics and diagnostics.
3990 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003991 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003992 // Log merge requests are performed during AudioFlinger binder transactions, but
3993 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07003994 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003995
Eric Laurent81784c32012-11-19 14:55:58 -08003996 cpuStats.sample(myName);
3997
Andy Hung116bc262023-06-20 18:56:17 -07003998 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003999 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004000 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07004001 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004002
Andy Hung2dbffc22018-08-08 18:50:41 -07004003 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4004 //
Andy Hungb17d24b2023-08-29 14:26:09 -07004005 // Note: we access outDeviceTypes() outside of mutex().
Andy Hung94dfbb42023-09-06 19:41:47 -07004006 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004007 // Here, we try for the AF lock, but do not block on it as the latency
4008 // is more informational.
Andy Hung85a07452023-08-28 18:36:53 -07004009 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd25fe392023-07-13 16:52:46 -07004010 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004011 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004012 status_t status = INVALID_OPERATION;
4013 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07004014 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07004015 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004016 && swPatches.size() > 0) {
4017 status = swPatches[0].getLatencyMs_l(&latencyMs);
4018 downstreamPatchHandle = swPatches[0].getPatchHandle();
4019 }
4020 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004021 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004022 lastDownstreamPatchHandle = downstreamPatchHandle;
4023 }
4024 if (status == OK) {
4025 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004026 // latency of 5 seconds).
4027 const double minLatency = 0., maxLatency = 5000.;
4028 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004029 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004030 } else {
4031 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004032 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004033 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004034 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004035 }
Andy Hung7535ed92023-07-17 17:05:00 -07004036 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004037 }
4038 } else {
4039 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4040 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004041 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004042 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4043 }
4044 }
4045
Eric Laurentb3f315a2021-07-13 15:09:05 +02004046 if (mCheckOutputStageEffects.exchange(false)) {
4047 checkOutputStageEffects();
4048 }
4049
Vlad Popa7e81cea2023-01-19 16:34:16 +01004050 MetadataUpdate metadataUpdate;
Andy Hungb17d24b2023-08-29 14:26:09 -07004051 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004052
Andy Hungb17d24b2023-08-29 14:26:09 -07004053 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004054
Eric Laurent021cf962014-05-13 10:18:14 -07004055 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004056 if (mCheckOutputStageEffects.load()) {
4057 continue;
4058 }
Eric Laurent10351942014-05-08 18:49:52 -07004059
Andy Hungb17d24b2023-08-29 14:26:09 -07004060 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004061 if (logString != NULL) {
4062 mNBLogWriter->logTimestamp();
4063 mNBLogWriter->log(logString);
4064 logString = NULL;
4065 }
4066
Dean Wheatley12473e92021-03-18 23:00:55 +11004067 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004068
Eric Laurent81784c32012-11-19 14:55:58 -08004069 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004070 if (mSignalPending) {
4071 // A signal was raised while we were unlocked
4072 mSignalPending = false;
4073 } else if (waitingAsyncCallback_l()) {
4074 if (exitPending()) {
4075 break;
4076 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004077 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004078 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004079 releaseWakeLock_l();
4080 released = true;
4081 }
Andy Hung10cbff12017-02-21 17:30:14 -08004082
4083 const int64_t waitNs = computeWaitTimeNs_l();
4084 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungb17d24b2023-08-29 14:26:09 -07004085 std::cv_status cvstatus =
4086 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4087 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004088 mSignalPending = true; // if timeout recheck everything
4089 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004090 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004091 if (released) {
4092 acquireWakeLock_l();
4093 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004094 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4095 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004096
4097 continue;
4098 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004099 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004100 isSuspended()) {
4101 // put audio hardware into standby after short delay
4102 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004103
4104 threadLoop_standby();
4105
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004106 // This is where we go into standby
4107 if (!mStandby) {
4108 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004109 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004110 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004111 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004112 }
Andy Hungd0979812019-02-21 15:51:44 -08004113 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004114 }
4115
Eric Tan39ec8d62018-07-24 09:49:29 -07004116 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004117 // we're about to wait, flush the binder command buffer
4118 IPCThreadState::self()->flushCommands();
4119
4120 clearOutputTracks();
4121
4122 if (exitPending()) {
4123 break;
4124 }
4125
4126 releaseWakeLock_l();
4127 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004128 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -07004129 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004130 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004131 acquireWakeLock_l();
4132
4133 mMixerStatus = MIXER_IDLE;
4134 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4135 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004136 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004137 checkSilentMode_l();
4138
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004139 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4140 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004141 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004142 sleepTimeShift = 0;
4143 }
4144
4145 continue;
4146 }
4147 }
Eric Laurent81784c32012-11-19 14:55:58 -08004148 // mMixerStatusIgnoringFastTracks is also updated internally
4149 mMixerStatus = prepareTracks_l(&tracksToRemove);
4150
Andy Hung94dfbb42023-09-06 19:41:47 -07004151 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004152
Vlad Popa7e81cea2023-01-19 16:34:16 +01004153 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004154
Eric Laurent81784c32012-11-19 14:55:58 -08004155 // prevent any changes in effect chain list and in each effect chain
4156 // during mixing and effect process as the audio buffers could be deleted
4157 // or modified if an effect is created or deleted
4158 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004159
4160 // Determine which session to pick up haptic data.
4161 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004162 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004163 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004164 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004165 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004166 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004167 if (effectChain != nullptr
4168 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004169 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004170 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004171 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004172 break;
4173 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004174 if (activeHapticSessionId == AUDIO_SESSION_NONE
4175 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004176 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004177 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004178 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004179 }
4180 }
4181 }
4182
Andy Hungc1646382019-04-30 16:12:10 -07004183 // Acquire a local copy of active tracks with lock (release w/o lock).
4184 //
4185 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4186 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4187 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4188 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004189
4190 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004191
Jiabin Huangfb476842022-12-06 03:18:10 +00004192 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004193 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004194 }
4195
Eric Laurent19952e12023-04-20 10:08:29 +02004196 // signal actual start of output stream when the render position reported by the kernel
4197 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004198 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4199 && (mKernelPositionOnStandby
4200 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004201 mHalStarted = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07004202 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004203 }
Andy Hungb17d24b2023-08-29 14:26:09 -07004204 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004205
Eric Laurentbfb1b832013-01-07 09:53:42 -08004206 if (mBytesRemaining == 0) {
4207 mCurrentWriteLength = 0;
4208 if (mMixerStatus == MIXER_TRACKS_READY) {
4209 // threadLoop_mix() sets mCurrentWriteLength
4210 threadLoop_mix();
4211 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4212 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004213 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004214 // must be written to HAL
4215 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004216 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004217 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004218
4219 // Tally underrun frames as we are inserting 0s here.
4220 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004221 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004222 && !track->isStopped()
4223 && !track->isPaused()
4224 && !track->isTerminated()) {
4225 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4226 __func__, track->id(), track->getTrackStateAsString(),
4227 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004228 track->audioTrackServerProxy()->tallyUnderrunFrames(
4229 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004230 }
4231 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004232 }
4233 }
Andy Hung98ef9782014-03-04 14:46:50 -08004234 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004235 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004236 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004237 // or mSinkBuffer (if there are no effects and there is no data already copied to
4238 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004239 //
4240 // This is done pre-effects computation; if effects change to
4241 // support higher precision, this needs to move.
4242 //
4243 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004244 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004245 uint32_t mixerChannelCount = mEffectBufferValid ?
4246 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004247 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004248 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4249 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4250
David Li88ee0902022-06-22 10:01:21 +08004251 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4252 // do these processes after effects are applied.
4253 if (!mEffectBufferValid) {
4254 // mono blend occurs for mixer threads only (not direct or offloaded)
4255 // and is handled here if we're going directly to the sink.
4256 if (requireMonoBlend()) {
4257 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4258 mNormalFrameCount, true /*limit*/);
4259 }
Andy Hung2ddee192015-12-18 17:34:44 -08004260
David Li88ee0902022-06-22 10:01:21 +08004261 if (!hasFastMixer()) {
4262 // Balance must take effect after mono conversion.
4263 // We do it here if there is no FastMixer.
4264 // mBalance detects zero balance within the class for speed
4265 // (not needed here).
4266 mBalance.setBalance(mMasterBalance.load());
4267 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4268 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004269 }
4270
Andy Hung98ef9782014-03-04 14:46:50 -08004271 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004272 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004273
4274 // If we're going directly to the sink and there are haptic channels,
4275 // we should adjust channels as the sample data is partially interleaved
4276 // in this case.
4277 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4278 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4279 mChannelCount + mHapticChannelCount,
4280 audio_bytes_per_sample(format),
4281 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4282 }
Andy Hung98ef9782014-03-04 14:46:50 -08004283 }
4284
Eric Laurentbfb1b832013-01-07 09:53:42 -08004285 mBytesRemaining = mCurrentWriteLength;
4286 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004287 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4288 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4289 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4290 mBytesWritten += mBytesRemaining;
4291 mFramesWritten += framesRemaining;
4292 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004293 mBytesRemaining = 0;
4294 }
Eric Laurent81784c32012-11-19 14:55:58 -08004295
Eric Laurentbfb1b832013-01-07 09:53:42 -08004296 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004297 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004298 for (size_t i = 0; i < effectChains.size(); i ++) {
4299 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004300 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004301 if (activeHapticSessionId != AUDIO_SESSION_NONE
4302 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004303 // Haptic data is active in this case, copy it directly from
4304 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004305 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4306 audio_channel_count_from_out_mask(mMixerChannelMask) :
4307 mChannelCount;
4308 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4309 hapticSessionChannelCount = mChannelCount;
4310 }
4311
jiabin47affe52019-04-04 18:02:07 -07004312 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004313 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004314 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004315 memcpy_by_audio_format(
4316 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004317 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004318 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004319 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004320 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004321 }
Eric Laurent81784c32012-11-19 14:55:58 -08004322 }
4323 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004324 // Process effect chains for offloaded thread even if no audio
4325 // was read from audio track: process only updates effect state
4326 // and thus does have to be synchronized with audio writes but may have
4327 // to be called while waiting for async write callback
4328 if (mType == OFFLOAD) {
4329 for (size_t i = 0; i < effectChains.size(); i ++) {
4330 effectChains[i]->process_l();
4331 }
4332 }
Eric Laurent81784c32012-11-19 14:55:58 -08004333
Andy Hung98ef9782014-03-04 14:46:50 -08004334 // Only if the Effects buffer is enabled and there is data in the
4335 // Effects buffer (buffer valid), we need to
4336 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004337 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004338 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004339 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004340 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004341 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004342 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004343 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004344 }
4345
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004346 if (!hasFastMixer()) {
4347 // Balance must take effect after mono conversion.
4348 // We do it here if there is no FastMixer.
4349 // mBalance detects zero balance within the class for speed (not needed here).
4350 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004351 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004352 }
4353
Eric Laurentb62d0362021-10-26 17:40:18 +02004354 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4355 // mPostSpatializerBuffer if the haptics track is spatialized.
4356 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4357 // For other thread types, the haptics channels are already in mEffectBuffer.
4358 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4359 const size_t srcBufferSize = mNormalFrameCount *
4360 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4361 mEffectBufferFormat);
4362 const size_t dstBufferSize = mNormalFrameCount
4363 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4364
4365 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4366 mEffectBufferFormat,
4367 (uint8_t*)mEffectBuffer + srcBufferSize,
4368 mEffectBufferFormat,
4369 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004370 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004371 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4372 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4373 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4374 // Clamp PCM float values more than this distance from 0 to insulate
4375 // a HAL which doesn't handle NaN correctly.
4376 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4377 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4378 static_cast<const float*>(effectBuffer),
4379 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4380 } else {
4381 memcpy_by_audio_format(mSinkBuffer, mFormat,
4382 effectBuffer, mEffectBufferFormat, framesToCopy);
4383 }
jiabin245cdd92018-12-07 17:55:15 -08004384 // The sample data is partially interleaved when haptic channels exist,
4385 // we need to adjust channels here.
4386 if (mHapticChannelCount > 0) {
4387 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4388 mChannelCount + mHapticChannelCount,
4389 audio_bytes_per_sample(mFormat),
4390 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4391 }
Andy Hung98ef9782014-03-04 14:46:50 -08004392 }
4393
Eric Laurent81784c32012-11-19 14:55:58 -08004394 // enable changes in effect chain
4395 unlockEffectChains(effectChains);
4396
Vlad Popafce10862023-02-03 10:37:07 +01004397 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004398 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004399 metadataUpdate.playbackMetadataUpdate);
4400 }
4401
Eric Laurentbfb1b832013-01-07 09:53:42 -08004402 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004403 // mSleepTimeUs == 0 means we must write to audio hardware
4404 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004405 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004406 // writePeriodNs is updated >= 0 when ret > 0.
4407 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004408 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004409 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004410 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004411 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004412 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004413 if (ret < 0) {
4414 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004415 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004416 mBytesWritten += ret;
4417 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004418 const int64_t frames = ret / mFrameSize;
4419 mFramesWritten += frames;
4420
4421 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4422 // process information relating to write time.
4423 if (audio_has_proportional_frames(mFormat)) {
4424 // we are in a continuous mixing cycle
4425 if (mMixerStatus == MIXER_TRACKS_READY &&
4426 loopCount == lastLoopCountWritten + 1) {
4427
4428 const double jitterMs =
4429 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4430 {frames, writePeriodNs},
4431 {0, 0} /* lastTimestamp */, mSampleRate);
4432 const double processMs =
4433 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4434
Andy Hungf8635b62023-08-31 16:13:39 -07004435 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004436 mIoJitterMs.add(jitterMs);
4437 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004438
4439 if (mPipeSink.get() != nullptr) {
4440 // Using the Monopipe availableToWrite, we estimate the current
4441 // buffer size.
4442 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4443 const ssize_t
4444 availableToWrite = mPipeSink->availableToWrite();
4445 const size_t pipeFrames = monoPipe->maxFrames();
4446 const size_t
4447 remainingFrames = pipeFrames - max(availableToWrite, 0);
4448 mMonopipePipeDepthStats.add(remainingFrames);
4449 }
Andy Hung446f4df2019-02-21 12:26:41 -08004450 }
4451
4452 // write blocked detection
4453 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004454 if ((mType == MIXER || mType == SPATIALIZER)
4455 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004456 mNumDelayedWrites++;
4457 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4458 ATRACE_NAME("underrun");
4459 ALOGW("write blocked for %lld msecs, "
4460 "%d delayed writes, thread %d",
4461 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4462 mNumDelayedWrites, mId);
4463 lastWarning = lastIoEndNs;
4464 }
4465 }
4466 }
4467 // update timing info.
4468 mLastIoBeginNs = lastIoBeginNs;
4469 mLastIoEndNs = lastIoEndNs;
4470 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471 }
4472 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4473 (mMixerStatus == MIXER_DRAIN_ALL)) {
4474 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004475 }
Andy Hungd3639922022-04-28 18:00:49 -07004476 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004477
4478 if (mThreadThrottle
4479 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004480 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004481 // Limit MixerThread data processing to no more than twice the
4482 // expected processing rate.
4483 //
4484 // This helps prevent underruns with NuPlayer and other applications
4485 // which may set up buffers that are close to the minimum size, or use
4486 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4487 //
4488 // The throttle smooths out sudden large data drains from the device,
4489 // e.g. when it comes out of standby, which often causes problems with
4490 // (1) mixer threads without a fast mixer (which has its own warm-up)
4491 // (2) minimum buffer sized tracks (even if the track is full,
4492 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004493 //
4494 // Total time spent in last processing cycle equals time spent in
4495 // 1. threadLoop_write, as well as time spent in
4496 // 2. threadLoop_mix (significant for heavy mixing, especially
4497 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004498
Andy Hung446f4df2019-02-21 12:26:41 -08004499 // it's OK if deltaMs is an overestimate.
4500
4501 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004502
Ivan Lozanoea04d392017-11-07 14:37:07 -08004503 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004504 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004505 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004506
Andy Hung08fb1742015-05-31 23:22:10 -07004507 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004508 // notify of throttle start on verbose log
4509 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4510 "mixer(%p) throttle begin:"
4511 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004512 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004513 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004514 // Throttle must be attributed to the previous mixer loop's write time
4515 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004516 // This also ensures proper timing statistics.
4517 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004518 } else {
4519 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4520 if (diff > 0) {
4521 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004522 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004523 ALOGD_IF(!isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004524 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004525 !isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004526 outDeviceTypes_l(),
4527 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004528 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004529 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4530 }
Andy Hung08fb1742015-05-31 23:22:10 -07004531 }
4532 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004533 }
Eric Laurent81784c32012-11-19 14:55:58 -08004534
Eric Laurentbfb1b832013-01-07 09:53:42 -08004535 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004536 ATRACE_BEGIN("sleep");
Andy Hungb17d24b2023-08-29 14:26:09 -07004537 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004538 // suspended requires accurate metering of sleep time.
4539 if (isSuspended()) {
4540 // advance by expected sleepTime
4541 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4542 const nsecs_t nowNs = systemTime();
4543
4544 // compute expected next time vs current time.
4545 // (negative deltas are treated as delays).
4546 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4547 if (deltaNs < -kMaxNextBufferDelayNs) {
4548 // Delays longer than the max allowed trigger a reset.
4549 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4550 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4551 timeLoopNextNs = nowNs + deltaNs;
4552 } else if (deltaNs < 0) {
4553 // Delays within the max delay allowed: zero the delta/sleepTime
4554 // to help the system catch up in the next iteration(s)
4555 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4556 deltaNs = 0;
4557 }
4558 // update sleep time (which is >= 0)
4559 mSleepTimeUs = deltaNs / 1000;
4560 }
Eric Laurente93cc032016-05-05 10:15:10 -07004561 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004562 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004563 }
Glenn Kastene7754022014-10-31 12:11:26 -07004564 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004565 }
Eric Laurent81784c32012-11-19 14:55:58 -08004566 }
4567
4568 // Finally let go of removed track(s), without the lock held
4569 // since we can't guarantee the destructors won't acquire that
4570 // same lock. This will also mutate and push a new fast mixer state.
4571 threadLoop_removeTracks(tracksToRemove);
4572 tracksToRemove.clear();
4573
4574 // FIXME I don't understand the need for this here;
4575 // it was in the original code but maybe the
4576 // assignment in saveOutputTracks() makes this unnecessary?
4577 clearOutputTracks();
4578
4579 // Effect chains will be actually deleted here if they were removed from
4580 // mEffectChains list during mixing or effects processing
4581 effectChains.clear();
4582
4583 // FIXME Note that the above .clear() is no longer necessary since effectChains
4584 // is now local to this block, but will keep it for now (at least until merge done).
4585 }
4586
Eric Laurentbfb1b832013-01-07 09:53:42 -08004587 threadLoop_exit();
4588
Eric Laurentcf817a22014-08-04 20:36:31 -07004589 if (!mStandby) {
4590 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004591 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004592 }
4593
4594 releaseWakeLock();
4595
4596 ALOGV("Thread %p type %d exiting", this, mType);
4597 return false;
4598}
4599
Andy Hung4b17e882023-07-07 13:47:37 -07004600void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004601{
Dean Wheatley12473e92021-03-18 23:00:55 +11004602 if (mStandby) {
4603 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4604 return;
4605 } else if (mHwPaused) {
4606 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4607 return;
4608 }
4609
4610 // Gather the framesReleased counters for all active tracks,
4611 // and associate with the sink frames written out. We need
4612 // this to convert the sink timestamp to the track timestamp.
4613 bool kernelLocationUpdate = false;
4614 ExtendedTimestamp timestamp; // use private copy to fetch
4615
4616 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4617 // HAL may be draining some small duration buffered data for fade out.
4618 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4619 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4620 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4621 mSampleRate);
4622
Andy Hung94dfbb42023-09-06 19:41:47 -07004623 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004624 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4625 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4626 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4627 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4628 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4629 = correctedTimestamp.mFrames;
4630 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4631 = correctedTimestamp.mTimeNs;
4632 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4633 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4634 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4635
4636 // Note: Downstream latency only added if timestamp correction enabled.
4637 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4638 const int64_t newPosition =
4639 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4640 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4641 // prevent retrograde
4642 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4643 newPosition,
4644 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4645 - mSuspendedFrames));
4646 }
4647 }
4648
4649 // We always fetch the timestamp here because often the downstream
4650 // sink will block while writing.
4651
4652 // We keep track of the last valid kernel position in case we are in underrun
4653 // and the normal mixer period is the same as the fast mixer period, or there
4654 // is some error from the HAL.
4655 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4656 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4657 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4658 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4659 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4660
4661 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4662 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4663 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4664 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4665 }
4666
4667 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4668 kernelLocationUpdate = true;
4669 } else {
4670 ALOGVV("getTimestamp error - no valid kernel position");
4671 }
4672
4673 // copy over kernel info
4674 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4675 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4676 + mSuspendedFrames; // add frames discarded when suspended
4677 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4678 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4679 } else {
4680 mTimestampVerifier.error();
4681 }
4682
4683 // mFramesWritten for non-offloaded tracks are contiguous
4684 // even after standby() is called. This is useful for the track frame
4685 // to sink frame mapping.
4686 bool serverLocationUpdate = false;
4687 if (mFramesWritten != mLastFramesWritten) {
4688 serverLocationUpdate = true;
4689 mLastFramesWritten = mFramesWritten;
4690 }
4691 // Only update timestamps if there is a meaningful change.
4692 // Either the kernel timestamp must be valid or we have written something.
4693 if (kernelLocationUpdate || serverLocationUpdate) {
4694 if (serverLocationUpdate) {
4695 // use the time before we called the HAL write - it is a bit more accurate
4696 // to when the server last read data than the current time here.
4697 //
4698 // If we haven't written anything, mLastIoBeginNs will be -1
4699 // and we use systemTime().
4700 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4701 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung160664b2023-09-15 18:19:28 -07004702 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004703 }
4704
Andy Hung11e74242023-06-26 19:20:57 -07004705 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004706 if (!t->isFastTrack()) {
4707 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004708 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004709 mFramesWritten,
4710 mSampleRate,
4711 mTimestamp);
4712 }
4713 }
4714 }
4715
4716 if (audio_has_proportional_frames(mFormat)) {
4717 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4718 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4719 mLatencyMs.add(latencyMs);
4720 }
4721 }
4722#if 0
4723 // logFormat example
4724 if (z % 100 == 0) {
4725 timespec ts;
4726 clock_gettime(CLOCK_MONOTONIC, &ts);
4727 LOGT("This is an integer %d, this is a float %f, this is my "
4728 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4729 LOGT("A deceptive null-terminated string %\0");
4730 }
4731 ++z;
4732#endif
4733}
4734
Andy Hungb17d24b2023-08-29 14:26:09 -07004735// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07004736void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungb17d24b2023-08-29 14:26:09 -07004737NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738{
Andy Hunga7187712023-12-05 17:28:17 -08004739 if (tracksToRemove.empty()) return;
4740
4741 // Block all incoming TrackHandle requests until we are finished with the release.
4742 setThreadBusy_l(true);
4743
Andy Hungfe726a62018-09-27 15:17:25 -07004744 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004745 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004746 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004747 if (chain != 0) {
4748 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4749 __func__, track->id(), chain.get(), track->sessionId());
4750 chain->decActiveTrackCnt();
4751 }
Andy Hunga7187712023-12-05 17:28:17 -08004752
Andy Hungfe726a62018-09-27 15:17:25 -07004753 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hunga7187712023-12-05 17:28:17 -08004754 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004755 if (track->isExternalTrack()) {
Andy Hunga7187712023-12-05 17:28:17 -08004756 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004757 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004759 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004760 }
Andy Hunga7187712023-12-05 17:28:17 -08004761 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004762 }
jiabineb3bda02020-06-30 14:07:03 -07004763 if (mHapticChannelCount > 0 &&
4764 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4765 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004766 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004767 // Unlock due to VibratorService will lock for this call and will
4768 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004769 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungb17d24b2023-08-29 14:26:09 -07004770 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004771
4772 // When the track is stop, set the haptic intensity as MUTE
4773 // for the HapticGenerator effect.
4774 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004775 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004776 }
jiabin245cdd92018-12-07 17:55:15 -08004777 }
Andy Hunga7187712023-12-05 17:28:17 -08004778
4779 // Under lock, the track is removed from the active tracks list.
4780 //
4781 // Once the track is no longer active, the TrackHandle may directly
4782 // modify it as the threadLoop() is no longer responsible for its maintenance.
4783 // Do not modify the track from threadLoop after the mutex is unlocked
4784 // if it is not active.
4785 mActiveTracks.remove(track);
4786
4787 if (track->isTerminated()) {
4788 // remove from our tracks vector
4789 removeTrack_l(track);
4790 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004791 }
Andy Hunga7187712023-12-05 17:28:17 -08004792
4793 // Allow incoming TrackHandle requests. We still hold the mutex,
4794 // so pending TrackHandle requests will occur after we unlock it.
4795 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004796}
Eric Laurent81784c32012-11-19 14:55:58 -08004797
Andy Hung4b17e882023-07-07 13:47:37 -07004798status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004799{
4800 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004801 ExtendedTimestamp ets;
4802 status_t status = mNormalSink->getTimestamp(ets);
4803 if (status == NO_ERROR) {
4804 status = ets.getBestTimestamp(&timestamp);
4805 }
4806 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004807 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004808 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004809 collectTimestamps_l();
4810 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4811 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004812 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004813 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4814 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4815 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4816 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4817 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004818 }
4819 return INVALID_OPERATION;
4820}
Eric Laurent1c333e22014-05-20 10:48:17 -07004821
Eric Laurenteab90452019-06-24 15:17:46 -07004822// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4823// still applied by the mixer.
4824// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4825// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4826// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004827status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004828{
4829 status_t result = NO_ERROR;
4830 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4831 if (*volume != mLeftVolFloat) {
4832 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004833 // HAL can return INVALID_OPERATION if operation is not supported.
4834 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004835 "Error when setting output stream volume: %d", result);
4836 if (result == NO_ERROR) {
4837 mLeftVolFloat = *volume;
4838 }
4839 }
4840 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4841 // remove stream volume contribution from software volume.
4842 if (mLeftVolFloat == *volume) {
4843 *volume = 1.0f;
4844 }
4845 }
4846 return result;
4847}
4848
Andy Hung4b17e882023-07-07 13:47:37 -07004849status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004850 audio_patch_handle_t *handle)
4851{
Andy Hungf60abce2016-08-26 11:37:54 -07004852 status_t status;
4853 if (property_get_bool("af.patch_park", false /* default_value */)) {
4854 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4855 // or if HAL does not properly lock against access.
4856 AutoPark<FastMixer> park(mFastMixer);
4857 status = PlaybackThread::createAudioPatch_l(patch, handle);
4858 } else {
4859 status = PlaybackThread::createAudioPatch_l(patch, handle);
4860 }
Eric Laurentb0463942022-12-20 16:31:10 +01004861
4862 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004863 return status;
4864}
4865
Andy Hung4b17e882023-07-07 13:47:37 -07004866status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004867 audio_patch_handle_t *handle)
4868{
4869 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004870
4871 // store new device and send to effects
4872 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004873 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004874 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004875 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4876 && !mOutput->audioHwDev->supportsAudioPatches(),
4877 "Enumerated device type(%#x) must not be used "
4878 "as it does not support audio patches",
4879 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004880 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004881 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4882 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004883 }
4884
François Gaffie0c280aa2018-07-25 10:02:15 +02004885 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004886#ifdef ADD_BATTERY_DATA
4887 // when changing the audio output device, call addBatteryData to notify
4888 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004889 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004890 uint32_t params = 0;
4891 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004892 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004893 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004894 }
4895
Eric Laurent054d9d32015-04-24 08:48:48 -07004896 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004897 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004898 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4899 }
4900
4901 if (params != 0) {
4902 addBatteryData(params);
4903 }
4904 }
4905#endif
4906
4907 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004908 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004909 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004910
jiabinc52b1ff2019-10-31 17:20:42 -07004911 // mPatch.num_sinks is not set when the thread is created so that
4912 // the first patch creation triggers an ioConfigChanged callback
4913 bool configChanged = (mPatch.num_sinks == 0) ||
4914 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004915 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004916 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004917 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004918
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004919 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004920 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4921 status = hwDevice->createAudioPatch(patch->num_sources,
4922 patch->sources,
4923 patch->num_sinks,
4924 patch->sinks,
4925 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004926 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004927 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004928 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004929 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004930 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004931
4932 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004933 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004934 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004935 // also dispatch to active AudioTracks for MediaMetrics
4936 for (const auto &track : mActiveTracks) {
4937 track->logEndInterval();
4938 track->logBeginInterval(patchSinksAsString);
4939 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004940
Eric Laurente8726fe2015-06-26 09:39:24 -07004941 if (configChanged) {
4942 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4943 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004944 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004945 mActiveTracks.setHasChanged();
4946
Eric Laurent1c333e22014-05-20 10:48:17 -07004947 return status;
4948}
4949
Andy Hung4b17e882023-07-07 13:47:37 -07004950status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004951{
Andy Hungf60abce2016-08-26 11:37:54 -07004952 status_t status;
4953 if (property_get_bool("af.patch_park", false /* default_value */)) {
4954 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4955 // or if HAL does not properly lock against access.
4956 AutoPark<FastMixer> park(mFastMixer);
4957 status = PlaybackThread::releaseAudioPatch_l(handle);
4958 } else {
4959 status = PlaybackThread::releaseAudioPatch_l(handle);
4960 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004961 return status;
4962}
4963
Andy Hung4b17e882023-07-07 13:47:37 -07004964status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004965{
4966 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004967
jiabinc52b1ff2019-10-31 17:20:42 -07004968 mPatch = audio_patch{};
4969 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004970
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004971 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004972 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4973 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004974 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004975 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004976 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004977 // Force meteadata update after a route change
4978 mActiveTracks.setHasChanged();
4979
Eric Laurent1c333e22014-05-20 10:48:17 -07004980 return status;
4981}
4982
Andy Hung4b17e882023-07-07 13:47:37 -07004983void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004984{
Andy Hungf8635b62023-08-31 16:13:39 -07004985 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004986 mTracks.add(track);
4987}
4988
Andy Hung4b17e882023-07-07 13:47:37 -07004989void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004990{
Andy Hungf8635b62023-08-31 16:13:39 -07004991 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004992 destroyTrack_l(track);
4993}
4994
Andy Hung4b17e882023-07-07 13:47:37 -07004995void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004996{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004997 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004998 config->role = AUDIO_PORT_ROLE_SOURCE;
4999 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5000 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005001 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5002 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5003 config->flags.output = mOutput->flags;
5004 }
Eric Laurent83b88082014-06-20 18:31:16 -07005005}
5006
Eric Laurent81784c32012-11-19 14:55:58 -08005007// ----------------------------------------------------------------------------
5008
Andy Hung4b17e882023-07-07 13:47:37 -07005009/* static */
5010sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07005011 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07005012 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07005013 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07005014}
5015
Andy Hung7535ed92023-07-17 17:05:00 -07005016MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005017 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07005018 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005019 // mAudioMixer below
5020 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005021 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005022 mFastMixerFutex(0),
5023 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005024 // mOutputSink below
5025 // mPipeSink below
5026 // mNormalSink below
5027{
Andy Hung7535ed92023-07-17 17:05:00 -07005028 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005029 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005030 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005031 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005032 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5033 mNormalFrameCount);
5034 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5035
Andy Hungfbfc3952015-01-15 13:33:51 -08005036 if (type == DUPLICATING) {
5037 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5038 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5039 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5040 return;
5041 }
Eric Laurent81784c32012-11-19 14:55:58 -08005042 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005043 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005044 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005045 const NBAIO_Format offers[1] = {Format_from_SR_C(
5046 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005047#if !LOG_NDEBUG
5048 ssize_t index =
5049#else
5050 (void)
5051#endif
5052 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005053 ALOG_ASSERT(index == 0);
5054
5055 // initialize fast mixer depending on configuration
5056 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005057 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005058 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005059 } else {
5060 switch (kUseFastMixer) {
5061 case FastMixer_Never:
5062 initFastMixer = false;
5063 break;
5064 case FastMixer_Always:
5065 initFastMixer = true;
5066 break;
5067 case FastMixer_Static:
5068 case FastMixer_Dynamic:
5069 initFastMixer = mFrameCount < mNormalFrameCount;
5070 break;
5071 }
5072 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5073 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5074 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005075 }
5076 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005077 audio_format_t fastMixerFormat;
5078 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5079 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5080 } else {
5081 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5082 }
5083 if (mFormat != fastMixerFormat) {
5084 // change our Sink format to accept our intermediate precision
5085 mFormat = fastMixerFormat;
5086 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005087 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005088 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5089 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5090 }
Eric Laurent81784c32012-11-19 14:55:58 -08005091
5092 // create a MonoPipe to connect our submix to FastMixer
5093 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005094
Andy Hung1258c1a2014-05-23 21:22:17 -07005095 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005096 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005097 format.mFormat = fastMixerFormat;
5098 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5099
Eric Laurent81784c32012-11-19 14:55:58 -08005100 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5101 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5102 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5103 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005104 const NBAIO_Format offersFast[1] = {format};
5105 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005106#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005107 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005108#else
5109 (void)
5110#endif
Andy Hung920f6572022-10-06 12:09:49 -07005111 monoPipe->negotiate(offersFast, std::size(offersFast),
5112 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005113 ALOG_ASSERT(index == 0);
5114 monoPipe->setAvgFrames((mScreenState & 1) ?
5115 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5116 mPipeSink = monoPipe;
5117
Eric Laurent81784c32012-11-19 14:55:58 -08005118 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005119 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005120 FastMixerStateQueue *sq = mFastMixer->sq();
5121#ifdef STATE_QUEUE_DUMP
5122 sq->setObserverDump(&mStateQueueObserverDump);
5123 sq->setMutatorDump(&mStateQueueMutatorDump);
5124#endif
5125 FastMixerState *state = sq->begin();
5126 FastTrack *fastTrack = &state->mFastTracks[0];
5127 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5128 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5129 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005130 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5131 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5132 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005133 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005134 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005135 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005136 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005137 fastTrack->mGeneration++;
5138 state->mFastTracksGen++;
5139 state->mTrackMask = 1;
5140 // fast mixer will use the HAL output sink
5141 state->mOutputSink = mOutputSink.get();
5142 state->mOutputSinkGen++;
5143 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005144 // specify sink channel mask when haptic channel mask present as it can not
5145 // be calculated directly from channel count
5146 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005147 ? AUDIO_CHANNEL_NONE
5148 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005149 state->mCommand = FastMixerState::COLD_IDLE;
5150 // already done in constructor initialization list
5151 //mFastMixerFutex = 0;
5152 state->mColdFutexAddr = &mFastMixerFutex;
5153 state->mColdGen++;
5154 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005155 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005156 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005157 sq->end();
5158 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5159
Eric Tan0513b5d2018-09-17 10:32:48 -07005160 NBLog::thread_info_t info;
5161 info.id = mId;
5162 info.type = NBLog::FASTMIXER;
5163 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5164
Eric Laurent81784c32012-11-19 14:55:58 -08005165 // start the fast mixer
5166 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5167 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005168 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005169 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005170
5171#ifdef AUDIO_WATCHDOG
5172 // create and start the watchdog
5173 mAudioWatchdog = new AudioWatchdog();
5174 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5175 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5176 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005177 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005178#endif
Andy Hung8946a282018-04-19 20:04:56 -07005179 } else {
5180#ifdef TEE_SINK
5181 // Only use the MixerThread tee if there is no FastMixer.
5182 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5183 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5184#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005185 }
5186
5187 switch (kUseFastMixer) {
5188 case FastMixer_Never:
5189 case FastMixer_Dynamic:
5190 mNormalSink = mOutputSink;
5191 break;
5192 case FastMixer_Always:
5193 mNormalSink = mPipeSink;
5194 break;
5195 case FastMixer_Static:
5196 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5197 break;
5198 }
5199}
5200
Andy Hung4b17e882023-07-07 13:47:37 -07005201MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005202{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005203 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005204 FastMixerStateQueue *sq = mFastMixer->sq();
5205 FastMixerState *state = sq->begin();
5206 if (state->mCommand == FastMixerState::COLD_IDLE) {
5207 int32_t old = android_atomic_inc(&mFastMixerFutex);
5208 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005209 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005210 }
5211 }
5212 state->mCommand = FastMixerState::EXIT;
5213 sq->end();
5214 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5215 mFastMixer->join();
5216 // Though the fast mixer thread has exited, it's state queue is still valid.
5217 // We'll use that extract the final state which contains one remaining fast track
5218 // corresponding to our sub-mix.
5219 state = sq->begin();
5220 ALOG_ASSERT(state->mTrackMask == 1);
5221 FastTrack *fastTrack = &state->mFastTracks[0];
5222 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5223 delete fastTrack->mBufferProvider;
5224 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005225 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005226#ifdef AUDIO_WATCHDOG
5227 if (mAudioWatchdog != 0) {
5228 mAudioWatchdog->requestExit();
5229 mAudioWatchdog->requestExitAndWait();
5230 mAudioWatchdog.clear();
5231 }
5232#endif
5233 }
Andy Hung7535ed92023-07-17 17:05:00 -07005234 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005235 delete mAudioMixer;
5236}
5237
Andy Hung4b17e882023-07-07 13:47:37 -07005238void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005239 PlaybackThread::onFirstRef();
5240
Andy Hungf8635b62023-08-31 16:13:39 -07005241 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005242 if (mOutput != nullptr && mOutput->stream != nullptr) {
5243 status_t status = mOutput->stream->setLatencyModeCallback(this);
5244 if (status != INVALID_OPERATION) {
5245 updateHalSupportedLatencyModes_l();
5246 }
5247 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5248 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5249 mBluetoothLatencyModesEnabled.store(
5250 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5251 }
5252}
Eric Laurent81784c32012-11-19 14:55:58 -08005253
Andy Hung4b17e882023-07-07 13:47:37 -07005254uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005255{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005256 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005257 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5258 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5259 }
5260 return latency;
5261}
5262
Andy Hung4b17e882023-07-07 13:47:37 -07005263ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005264{
5265 // FIXME we should only do one push per cycle; confirm this is true
5266 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005267 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005268 FastMixerStateQueue *sq = mFastMixer->sq();
5269 FastMixerState *state = sq->begin();
5270 if (state->mCommand != FastMixerState::MIX_WRITE &&
5271 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5272 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005273
5274 // FIXME workaround for first HAL write being CPU bound on some devices
5275 ATRACE_BEGIN("write");
5276 mOutput->write((char *)mSinkBuffer, 0);
5277 ATRACE_END();
5278
Eric Laurent81784c32012-11-19 14:55:58 -08005279 int32_t old = android_atomic_inc(&mFastMixerFutex);
5280 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005281 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005282 }
5283#ifdef AUDIO_WATCHDOG
5284 if (mAudioWatchdog != 0) {
5285 mAudioWatchdog->resume();
5286 }
5287#endif
5288 }
5289 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005290#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005291 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005292 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005293#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005294 sq->end();
5295 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5296 if (kUseFastMixer == FastMixer_Dynamic) {
5297 mNormalSink = mPipeSink;
5298 }
5299 } else {
5300 sq->end(false /*didModify*/);
5301 }
5302 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005304}
5305
Andy Hung4b17e882023-07-07 13:47:37 -07005306void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005307{
5308 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005309 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005310 FastMixerStateQueue *sq = mFastMixer->sq();
5311 FastMixerState *state = sq->begin();
5312 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005313 // Report any frames trapped in the Monopipe
5314 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5315 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5316 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5317 "monoPipeWritten:%lld monoPipeLeft:%lld",
5318 (long long)mFramesWritten, (long long)mSuspendedFrames,
5319 (long long)mPipeSink->framesWritten(), pipeFrames);
5320 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5321
Eric Laurent81784c32012-11-19 14:55:58 -08005322 state->mCommand = FastMixerState::COLD_IDLE;
5323 state->mColdFutexAddr = &mFastMixerFutex;
5324 state->mColdGen++;
5325 mFastMixerFutex = 0;
5326 sq->end();
5327 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5328 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5329 if (kUseFastMixer == FastMixer_Dynamic) {
5330 mNormalSink = mOutputSink;
5331 }
5332#ifdef AUDIO_WATCHDOG
5333 if (mAudioWatchdog != 0) {
5334 mAudioWatchdog->pause();
5335 }
5336#endif
5337 } else {
5338 sq->end(false /*didModify*/);
5339 }
5340 }
5341 PlaybackThread::threadLoop_standby();
5342}
5343
Andy Hung4b17e882023-07-07 13:47:37 -07005344bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345{
5346 return false;
5347}
5348
Andy Hung4b17e882023-07-07 13:47:37 -07005349bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005350{
5351 return !mStandby;
5352}
5353
Andy Hung4b17e882023-07-07 13:47:37 -07005354bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005355{
Andy Hungf8635b62023-08-31 16:13:39 -07005356 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005357 return waitingAsyncCallback_l();
5358}
5359
Eric Laurent81784c32012-11-19 14:55:58 -08005360// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005361void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005362{
Andy Hung160664b2023-09-15 18:19:28 -07005363 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5364 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005365 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005367 // discard any pending drain or write ack by incrementing sequence
5368 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5369 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005370 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005371 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5372 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005373 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005374 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005375 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005376}
5377
Andy Hung4b17e882023-07-07 13:47:37 -07005378void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005379{
5380 ALOGV("signal playback thread");
5381 broadcast_l();
5382}
5383
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005384void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005385{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005386 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005387 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5388 invalidateTracks((audio_stream_type_t)i);
5389 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005390 if (isHardError) {
5391 mAfThreadCallback->onHardError(allTrackPortIds);
5392 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005393}
5394
Andy Hung4b17e882023-07-07 13:47:37 -07005395void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005396{
Eric Laurent81784c32012-11-19 14:55:58 -08005397 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005398 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005399 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005400 // increase sleep time progressively when application underrun condition clears.
5401 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5402 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5403 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005404 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005405 sleepTimeShift--;
5406 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005407 mSleepTimeUs = 0;
5408 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005409 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005410
Eric Laurent81784c32012-11-19 14:55:58 -08005411}
5412
Andy Hung4b17e882023-07-07 13:47:37 -07005413void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005414{
5415 // If no tracks are ready, sleep once for the duration of an output
5416 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005417 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005418 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005419 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5420 // Using the Monopipe availableToWrite, we estimate the
5421 // sleep time to retry for more data (before we underrun).
5422 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5423 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5424 const size_t pipeFrames = monoPipe->maxFrames();
5425 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5426 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5427 const size_t framesDelay = std::min(
5428 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5429 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5430 pipeFrames, framesLeft, framesDelay);
5431 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5432 } else {
5433 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5434 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5435 mSleepTimeUs = kMinThreadSleepTimeUs;
5436 }
5437 // reduce sleep time in case of consecutive application underruns to avoid
5438 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5439 // duration we would end up writing less data than needed by the audio HAL if
5440 // the condition persists.
5441 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5442 sleepTimeShift++;
5443 }
Eric Laurent81784c32012-11-19 14:55:58 -08005444 }
5445 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005446 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005447 }
5448 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005449 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5450 // before effects processing or output.
5451 if (mMixerBufferValid) {
5452 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005453 if (mType == SPATIALIZER) {
5454 memset(mSinkBuffer, 0, mSinkBufferSize);
5455 }
Andy Hung98ef9782014-03-04 14:46:50 -08005456 } else {
5457 memset(mSinkBuffer, 0, mSinkBufferSize);
5458 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005459 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005460 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5461 "anticipated start");
5462 }
5463 // TODO add standby time extension fct of effect tail
5464}
5465
Andy Hungb17d24b2023-08-29 14:26:09 -07005466// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07005467PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005468 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005469{
Andy Hungc0691382018-09-12 18:01:57 -07005470 // clean up deleted track ids in AudioMixer before allocating new tracks
5471 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5472 // for each trackId, destroy it in the AudioMixer
5473 if (mAudioMixer->exists(trackId)) {
5474 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005475 }
5476 });
Andy Hungc0691382018-09-12 18:01:57 -07005477 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005478
5479 mixer_state mixerStatus = MIXER_IDLE;
5480 // find out which tracks need to be processed
5481 size_t count = mActiveTracks.size();
5482 size_t mixedTracks = 0;
5483 size_t tracksWithEffect = 0;
5484 // counts only _active_ fast tracks
5485 size_t fastTracks = 0;
5486 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5487
5488 float masterVolume = mMasterVolume;
5489 bool masterMute = mMasterMute;
5490
5491 if (masterMute) {
5492 masterVolume = 0;
5493 }
5494 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005495 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005496 if (chain != 0) {
5497 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5498 chain->setVolume_l(&v, &v);
5499 masterVolume = (float)((v + (1 << 23)) >> 24);
5500 chain.clear();
5501 }
5502
5503 // prepare a new state to push
5504 FastMixerStateQueue *sq = NULL;
5505 FastMixerState *state = NULL;
5506 bool didModify = false;
5507 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005508 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005509 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005510 sq = mFastMixer->sq();
5511 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005512 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005513 }
5514
Andy Hung69aed5f2014-02-25 17:24:40 -08005515 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005516 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005517
Andy Hungbd3b2b02018-05-21 10:53:11 -07005518 // DeferredOperations handles statistics after setting mixerStatus.
5519 class DeferredOperations {
5520 public:
Andy Hungea840382020-05-05 21:50:17 -07005521 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5522 : mMixerStatus(mixerStatus)
5523 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005524
5525 // when leaving scope, tally frames properly.
5526 ~DeferredOperations() {
5527 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5528 // because that is when the underrun occurs.
5529 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005530 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005531 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005532 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005533 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005534 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005535 }
5536 }
Andy Hungea840382020-05-05 21:50:17 -07005537 // send the max underrun frames for this mixer period
5538 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005539 }
5540
5541 // tallyUnderrunFrames() is called to update the track counters
5542 // with the number of underrun frames for a particular mixer period.
5543 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005544 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005545 mUnderrunFrames.emplace_back(track, underrunFrames);
5546 }
5547
5548 private:
5549 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005550 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005551 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005552 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005553 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005554
jiabin245cdd92018-12-07 17:55:15 -08005555 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005556 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005557 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005558
5559 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005560 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005561
5562 // process fast tracks
5563 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005564 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5565 "%s(%d): FastTrack(%d) present without FastMixer",
5566 __func__, id(), track->id());
5567
jiabin245cdd92018-12-07 17:55:15 -08005568 if (track->getHapticPlaybackEnabled()) {
5569 noFastHapticTrack = false;
5570 }
Eric Laurent81784c32012-11-19 14:55:58 -08005571
5572 // It's theoretically possible (though unlikely) for a fast track to be created
5573 // and then removed within the same normal mix cycle. This is not a problem, as
5574 // the track never becomes active so it's fast mixer slot is never touched.
5575 // The converse, of removing an (active) track and then creating a new track
5576 // at the identical fast mixer slot within the same normal mix cycle,
5577 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005578 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005579 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005580 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5581 FastTrack *fastTrack = &state->mFastTracks[j];
5582
5583 // Determine whether the track is currently in underrun condition,
5584 // and whether it had a recent underrun.
5585 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5586 FastTrackUnderruns underruns = ftDump->mUnderruns;
5587 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005588 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005589 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005590 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005591 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005592 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005593 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005594 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005595 // don't count underruns that occur while stopping or pausing
5596 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005597 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005598 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5599 recentUnderruns > 0) {
5600 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005601 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005602 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005603 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005604 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005605
5606 // This is similar to the state machine for normal tracks,
5607 // with a few modifications for fast tracks.
5608 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005609 switch (track->state()) {
5610 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005611 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005612 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005613 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005614 }
5615 break;
Andy Hung11e74242023-06-26 19:20:57 -07005616 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005617 // ramp down is not yet implemented
5618 track->setPaused();
5619 break;
Andy Hung11e74242023-06-26 19:20:57 -07005620 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005621 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005622 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005623 break;
Andy Hung11e74242023-06-26 19:20:57 -07005624 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005625 if (recentFull > 0 || recentPartial > 0) {
5626 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005627 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005628 }
5629 if (recentUnderruns == 0) {
5630 // no recent underruns: stay active
5631 break;
5632 }
5633 // there has recently been an underrun of some kind
5634 if (track->sharedBuffer() == 0) {
5635 // were any of the recent underruns "empty" (no frames available)?
5636 if (recentEmpty == 0) {
5637 // no, then ignore the partial underruns as they are allowed indefinitely
5638 break;
5639 }
5640 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005641 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005642 break;
5643 }
5644 // indicate to client process that the track was disabled because of underrun;
5645 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005646 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005647 // remove from active list, but state remains ACTIVE [confusing but true]
5648 isActive = false;
5649 break;
5650 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005651 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005652 case IAfTrackBase::STOPPING_2:
5653 case IAfTrackBase::PAUSED:
5654 case IAfTrackBase::STOPPED:
5655 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005656 // Check for presentation complete if track is inactive
5657 // We have consumed all the buffers of this track.
5658 // This would be incomplete if we auto-paused on underrun
5659 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005660 uint32_t latency = 0;
5661 status_t result = mOutput->stream->getLatency(&latency);
5662 ALOGE_IF(result != OK,
5663 "Error when retrieving output stream latency: %d", result);
5664 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005665 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005666 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5667 // track stays in active list until presentation is complete
5668 break;
5669 }
5670 }
5671 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005672 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005673 }
5674 if (track->isStopped()) {
5675 // Can't reset directly, as fast mixer is still polling this track
5676 // track->reset();
5677 // So instead mark this track as needing to be reset after push with ack
5678 resetMask |= 1 << i;
5679 }
5680 isActive = false;
5681 break;
Andy Hung11e74242023-06-26 19:20:57 -07005682 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005683 default:
Andy Hung11e74242023-06-26 19:20:57 -07005684 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005685 }
5686
5687 if (isActive) {
5688 // was it previously inactive?
5689 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005690 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5691 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005692 fastTrack->mBufferProvider = eabp;
5693 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005694 fastTrack->mChannelMask = track->channelMask();
5695 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005696 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005697 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005698 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005699 fastTrack->mGeneration++;
5700 state->mTrackMask |= 1 << j;
5701 didModify = true;
5702 // no acknowledgement required for newly active tracks
5703 }
Andy Hung11e74242023-06-26 19:20:57 -07005704 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005705 float volume;
5706 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5707 volume = 0.f;
5708 } else {
5709 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5710 }
5711
5712 handleVoipVolume_l(&volume);
5713
Eric Laurent81784c32012-11-19 14:55:58 -08005714 // cache the combined master volume and stream type volume for fast mixer; this
5715 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005716 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005717 proxy->framesReleased()).first;
5718 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005719 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005720 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005721 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5722 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5723
Andy Hung7535ed92023-07-17 17:05:00 -07005724 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005725 /*muteState=*/{masterVolume == 0.f,
5726 mStreamTypes[track->streamType()].volume == 0.f,
5727 mStreamTypes[track->streamType()].mute,
5728 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005729 vlf == 0.f && vrf == 0.f,
5730 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005731
5732 vlf *= volume;
5733 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005734
jiabin76d94692022-12-15 21:51:21 +00005735 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005736 ++fastTracks;
5737 } else {
5738 // was it previously active?
5739 if (state->mTrackMask & (1 << j)) {
5740 fastTrack->mBufferProvider = NULL;
5741 fastTrack->mGeneration++;
5742 state->mTrackMask &= ~(1 << j);
5743 didModify = true;
5744 // If any fast tracks were removed, we must wait for acknowledgement
5745 // because we're about to decrement the last sp<> on those tracks.
5746 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5747 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005748 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5749 // AudioTrack may start (which may not be with a start() but with a write()
5750 // after underrun) and immediately paused or released. In that case the
5751 // FastTrack state hasn't had time to update.
5752 // TODO Remove the ALOGW when this theory is confirmed.
5753 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005754 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005755 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005756 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005757 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005758 }
5759 tracksToRemove->add(track);
5760 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005761 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005762 }
jiabin245cdd92018-12-07 17:55:15 -08005763 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5764 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5765 didModify = true;
5766 }
Eric Laurent81784c32012-11-19 14:55:58 -08005767 continue;
5768 }
5769
5770 { // local variable scope to avoid goto warning
5771
5772 audio_track_cblk_t* cblk = track->cblk();
5773
5774 // The first time a track is added we wait
5775 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005776 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005777
5778 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005779 // use the trackId as the AudioMixer name.
5780 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005781 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005782 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005783 track->channelMask(),
5784 track->format(),
5785 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005786 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005787 ALOGW("%s(): AudioMixer cannot create track(%d)"
5788 " mask %#x, format %#x, sessionId %d",
5789 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005790 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005791 tracksToRemove->add(track);
5792 track->invalidate(); // consider it dead.
5793 continue;
5794 }
5795 }
5796
Eric Laurent81784c32012-11-19 14:55:58 -08005797 // make sure that we have enough frames to mix one full buffer.
5798 // enforce this condition only once to enable draining the buffer in case the client
5799 // app does not call stop() and relies on underrun to stop:
5800 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5801 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005802 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005803 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5804 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005805
5806 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005807 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005808 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5809 // add frames already consumed but not yet released by the resampler
5810 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005811 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005812
Eric Laurent81784c32012-11-19 14:55:58 -08005813 uint32_t minFrames = 1;
5814 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5815 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005816 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005817 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005818
5819 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005820 if (ATRACE_ENABLED()) {
5821 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005822 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005823 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005824 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005825 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005826 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005827 !track->isPaused() && !track->isTerminated())
5828 {
Andy Hungc0691382018-09-12 18:01:57 -07005829 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005830
5831 mixedTracks++;
5832
Andy Hung69aed5f2014-02-25 17:24:40 -08005833 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5834 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005835 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005836 if (track->mainBuffer() != mSinkBuffer &&
5837 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005838 if (mEffectBufferEnabled) {
5839 mEffectBufferValid = true; // Later can set directly.
5840 }
Eric Laurent81784c32012-11-19 14:55:58 -08005841 chain = getEffectChain_l(track->sessionId());
5842 // Delegate volume control to effect in track effect chain if needed
5843 if (chain != 0) {
5844 tracksWithEffect++;
5845 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005846 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005847 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005848 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005849 }
5850 }
5851
5852
5853 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005854 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005855 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005856 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5857 if (track->state() == IAfTrackBase::RESUMING) {
5858 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005859 // If a new track is paused immediately after start, do not ramp on resume.
5860 if (cblk->mServer != 0) {
5861 param = AudioMixer::RAMP_VOLUME;
5862 }
Eric Laurent81784c32012-11-19 14:55:58 -08005863 }
Andy Hungc0691382018-09-12 18:01:57 -07005864 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005865 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005866 // FIXME should not make a decision based on mServer
5867 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005868 // If the track is stopped before the first frame was mixed,
5869 // do not apply ramp
5870 param = AudioMixer::RAMP_VOLUME;
5871 }
5872
5873 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005874 uint32_t vl, vr; // in U8.24 integer format
5875 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005876 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005877 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005878 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005879 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005880 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005881 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005882
Eric Laurenteab90452019-06-24 15:17:46 -07005883 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5884 v = 0;
5885 }
5886
5887 handleVoipVolume_l(&v);
5888
5889 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005890 vl = vr = 0;
5891 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005892 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005893 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005894 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005895 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5896 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005897 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005898 if (vlf > GAIN_FLOAT_UNITY) {
5899 ALOGV("Track left volume out of range: %.3g", vlf);
5900 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005901 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005902 if (vrf > GAIN_FLOAT_UNITY) {
5903 ALOGV("Track right volume out of range: %.3g", vrf);
5904 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005905 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005906
Andy Hung7535ed92023-07-17 17:05:00 -07005907 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005908 /*muteState=*/{masterVolume == 0.f,
5909 mStreamTypes[track->streamType()].volume == 0.f,
5910 mStreamTypes[track->streamType()].mute,
5911 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005912 vlf == 0.f && vrf == 0.f,
5913 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005914
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005915 // now apply the master volume and stream type volume and shaper volume
5916 vlf *= v * vh;
5917 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005918 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005919 // then derive vl and vr as U8.24 versions for the effect chain
5920 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5921 vl = (uint32_t) (scaleto8_24 * vlf);
5922 vr = (uint32_t) (scaleto8_24 * vrf);
5923 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005924 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005925 // send level comes from shared memory and so may be corrupt
5926 if (sendLevel > MAX_GAIN_INT) {
5927 ALOGV("Track send level out of range: %04X", sendLevel);
5928 sendLevel = MAX_GAIN_INT;
5929 }
Andy Hung6be49402014-05-30 10:42:03 -07005930 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5931 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005932 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005933
Jiabin Huang66aa1e32024-05-13 20:33:29 +00005934 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07005935
Eric Laurent81784c32012-11-19 14:55:58 -08005936 // Delegate volume control to effect in track effect chain if needed
5937 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5938 // Do not ramp volume if volume is controlled by effect
5939 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005940 // Update remaining floating point volume levels
5941 vlf = (float)vl / (1 << 24);
5942 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07005943 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005944 } else {
5945 // force no volume ramp when volume controller was just disabled or removed
5946 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07005947 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005948 param = AudioMixer::VOLUME;
5949 }
Andy Hung11e74242023-06-26 19:20:57 -07005950 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005951 }
5952
Eric Laurent81784c32012-11-19 14:55:58 -08005953 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07005954 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005955 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005956
Andy Hungc0691382018-09-12 18:01:57 -07005957 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5958 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5959 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005960 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005961 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005962 AudioMixer::TRACK,
5963 AudioMixer::FORMAT, (void *)track->format());
5964 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005965 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005966 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005967 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005968
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005969 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005970 mAudioMixer->setParameter(
5971 trackId,
5972 AudioMixer::TRACK,
5973 AudioMixer::MIXER_CHANNEL_MASK,
5974 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5975 } else {
5976 mAudioMixer->setParameter(
5977 trackId,
5978 AudioMixer::TRACK,
5979 AudioMixer::MIXER_CHANNEL_MASK,
5980 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5981 }
5982
Glenn Kastene3aa6592012-12-04 12:22:46 -08005983 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005984 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005985 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005986 if (reqSampleRate == 0) {
5987 reqSampleRate = mSampleRate;
5988 } else if (reqSampleRate > maxSampleRate) {
5989 reqSampleRate = maxSampleRate;
5990 }
Eric Laurent81784c32012-11-19 14:55:58 -08005991 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005992 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005993 AudioMixer::RESAMPLE,
5994 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005995 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005996
Andy Hung8edb8dc2015-03-26 19:13:55 -07005997 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005998 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005999 AudioMixer::TIMESTRETCH,
6000 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006001 // cast away constness for this generic API.
6002 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006003
Andy Hung69aed5f2014-02-25 17:24:40 -08006004 /*
6005 * Select the appropriate output buffer for the track.
6006 *
Andy Hung98ef9782014-03-04 14:46:50 -08006007 * Tracks with effects go into their own effects chain buffer
6008 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006009 *
6010 * Other tracks can use mMixerBuffer for higher precision
6011 * channel accumulation. If this buffer is enabled
6012 * (mMixerBufferEnabled true), then selected tracks will accumulate
6013 * into it.
6014 *
6015 */
6016 if (mMixerBufferEnabled
6017 && (track->mainBuffer() == mSinkBuffer
6018 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006019 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006020 mAudioMixer->setParameter(
6021 trackId,
6022 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006023 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006024 mAudioMixer->setParameter(
6025 trackId,
6026 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006027 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006028 } else {
6029 mAudioMixer->setParameter(
6030 trackId,
6031 AudioMixer::TRACK,
6032 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6033 mAudioMixer->setParameter(
6034 trackId,
6035 AudioMixer::TRACK,
6036 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6037 // TODO: override track->mainBuffer()?
6038 mMixerBufferValid = true;
6039 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006040 } else {
6041 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006042 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006043 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006044 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006045 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006046 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006047 AudioMixer::TRACK,
6048 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6049 }
Eric Laurent81784c32012-11-19 14:55:58 -08006050 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006051 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006052 AudioMixer::TRACK,
6053 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006054 mAudioMixer->setParameter(
6055 trackId,
6056 AudioMixer::TRACK,
6057 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006058 mAudioMixer->setParameter(
6059 trackId,
6060 AudioMixer::TRACK,
6061 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung11e74242023-06-26 19:20:57 -07006062 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006063 mAudioMixer->setParameter(
6064 trackId,
6065 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07006066 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006067
6068 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006069 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006070
6071 // If one track is ready, set the mixer ready if:
6072 // - the mixer was not ready during previous round OR
6073 // - no other track is not ready
6074 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6075 mixerStatus != MIXER_TRACKS_ENABLED) {
6076 mixerStatus = MIXER_TRACKS_READY;
6077 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006078
6079 // Enable the next few lines to instrument a test for underrun log handling.
6080 // TODO: Remove when we have a better way of testing the underrun log.
6081#if 0
6082 static int i;
6083 if ((++i & 0xf) == 0) {
6084 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6085 }
6086#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006087 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006088 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006089 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006090 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6091 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006092 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006093 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006094 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006095
Eric Laurent81784c32012-11-19 14:55:58 -08006096 // clear effect chain input buffer if an active track underruns to avoid sending
6097 // previous audio buffer again to effects
6098 chain = getEffectChain_l(track->sessionId());
6099 if (chain != 0) {
6100 chain->clearInputBuffer();
6101 }
6102
Andy Hungc0691382018-09-12 18:01:57 -07006103 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006104 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6105 track->isStopped() || track->isPaused()) {
6106 // We have consumed all the buffers of this track.
6107 // Remove it from the list of active tracks.
6108 // TODO: use actual buffer filling status instead of latency when available from
6109 // audio HAL
6110 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006111 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006112 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6113 if (track->isStopped()) {
6114 track->reset();
6115 }
6116 tracksToRemove->add(track);
6117 }
6118 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006119 // No buffers for this track. Give it a few chances to
6120 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07006121 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006122 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6123 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006124 tracksToRemove->add(track);
6125 // indicate to client process that the track was disabled because of underrun;
6126 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006127 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006128 // If one track is not ready, mark the mixer also not ready if:
6129 // - the mixer was ready during previous round OR
6130 // - no other track is ready
6131 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6132 mixerStatus != MIXER_TRACKS_READY) {
6133 mixerStatus = MIXER_TRACKS_ENABLED;
6134 }
6135 }
Andy Hungc0691382018-09-12 18:01:57 -07006136 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006137 }
6138
6139 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006140
6141 }
6142
jiabin245cdd92018-12-07 17:55:15 -08006143 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6144 // When there is no fast track playing haptic and FastMixer exists,
6145 // enabling the first FastTrack, which provides mixed data from normal
6146 // tracks, to play haptic data.
6147 FastTrack *fastTrack = &state->mFastTracks[0];
6148 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6149 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6150 didModify = true;
6151 }
6152 }
6153
Eric Laurent81784c32012-11-19 14:55:58 -08006154 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006155 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006156 if (didModify) {
6157 state->mFastTracksGen++;
6158 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6159 if (kUseFastMixer == FastMixer_Dynamic &&
6160 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6161 state->mCommand = FastMixerState::COLD_IDLE;
6162 state->mColdFutexAddr = &mFastMixerFutex;
6163 state->mColdGen++;
6164 mFastMixerFutex = 0;
6165 if (kUseFastMixer == FastMixer_Dynamic) {
6166 mNormalSink = mOutputSink;
6167 }
6168 // If we go into cold idle, need to wait for acknowledgement
6169 // so that fast mixer stops doing I/O.
6170 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6171 pauseAudioWatchdog = true;
6172 }
Eric Laurent81784c32012-11-19 14:55:58 -08006173 }
6174 if (sq != NULL) {
6175 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006176 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6177 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6178 // when bringing the output sink into standby.)
6179 //
6180 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6181 //
6182 // This occurs with BT suspend when we idle the FastMixer with
6183 // active tracks, which may be added or removed.
6184 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006185 }
6186#ifdef AUDIO_WATCHDOG
6187 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6188 mAudioWatchdog->pause();
6189 }
6190#endif
6191
6192 // Now perform the deferred reset on fast tracks that have stopped
6193 while (resetMask != 0) {
6194 size_t i = __builtin_ctz(resetMask);
6195 ALOG_ASSERT(i < count);
6196 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006197 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006198 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6199 track->reset();
6200 }
6201
Andy Hung80d03d22018-04-10 10:32:11 -07006202 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6203 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6204 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6205 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6206 // See also the implementation of destroyTrack_l().
6207 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006208 const int trackId = track->id();
6209 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6210 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006211 }
6212 }
6213
Eric Laurent81784c32012-11-19 14:55:58 -08006214 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006215 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006216
Eric Laurentb3f315a2021-07-13 15:09:05 +02006217 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6218 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006219 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006220 }
6221
6222 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006223 // as long as there are effects we should clear the effects buffer, to avoid
6224 // passing a non-clean buffer to the effect chain
6225 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006226 if (mType == SPATIALIZER) {
6227 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6228 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006229 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006230 // sink or mix buffer must be cleared if all tracks are connected to an
6231 // effect chain as in this case the mixer will not write to the sink or mix buffer
6232 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006233 // always clear sink buffer for spatializer output as the output of the spatializer
6234 // effect will be accumulated into it
6235 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6236 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006237 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006238 if (mMixerBufferValid) {
6239 memset(mMixerBuffer, 0, mMixerBufferSize);
6240 // TODO: In testing, mSinkBuffer below need not be cleared because
6241 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6242 // after mixing.
6243 //
6244 // To enforce this guarantee:
6245 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6246 // (mixedTracks == 0 && fastTracks > 0))
6247 // must imply MIXER_TRACKS_READY.
6248 // Later, we may clear buffers regardless, and skip much of this logic.
6249 }
Andy Hung98ef9782014-03-04 14:46:50 -08006250 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006251 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006252 }
6253
6254 // if any fast tracks, then status is ready
6255 mMixerStatusIgnoringFastTracks = mixerStatus;
6256 if (fastTracks > 0) {
6257 mixerStatus = MIXER_TRACKS_READY;
6258 }
6259 return mixerStatus;
6260}
6261
Andy Hungb17d24b2023-08-29 14:26:09 -07006262// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006263uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006264{
6265 uint32_t trackCount = 0;
6266 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006267 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006268 trackCount++;
6269 }
6270 }
6271 return trackCount;
6272}
6273
Andy Hung4b17e882023-07-07 13:47:37 -07006274bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006275{
Brian Lindahl65e90012022-07-27 18:01:07 +02006276 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6277 // could falsely detect that the frame position has stalled due to underrun because we haven't
6278 // given the Audio HAL enough time to update.
6279 const nsecs_t nowNs = systemTime();
6280 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6281 return mLatchedValue;
6282 }
6283 mPreviousNs = nowNs;
6284 mLatchedValue = false;
6285 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006286 uint64_t position = 0;
6287 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006288 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006289 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006290 if (position != mPreviousPosition) {
6291 mPreviousPosition = position;
6292 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006293 }
6294 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006295 return mLatchedValue;
6296}
6297
Andy Hung4b17e882023-07-07 13:47:37 -07006298void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006299{
6300 mLatchedValue = true;
6301 mPreviousPosition = 0;
6302 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006303}
6304
Andy Hungb17d24b2023-08-29 14:26:09 -07006305// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006306bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006307 audio_channel_mask_t channelMask, audio_format_t format,
6308 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006309{
Andy Hung1bc088a2018-02-09 15:57:31 -08006310 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6311 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006312 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006313 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006314 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006315 ALOGW("%s: invalid format: %#x", __func__, format);
6316 return false;
6317 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006318 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006319 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6320 return false;
6321 }
6322 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006323}
6324
Andy Hungb17d24b2023-08-29 14:26:09 -07006325// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006326bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006327 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006328{
Eric Laurent81784c32012-11-19 14:55:58 -08006329 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006330 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006331
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006332 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006333
Eric Laurent10351942014-05-08 18:49:52 -07006334 AudioParameter param = AudioParameter(keyValuePair);
6335 int value;
6336 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6337 reconfig = true;
6338 }
6339 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006340 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006341 status = BAD_VALUE;
6342 } else {
6343 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006344 reconfig = true;
6345 }
Eric Laurent10351942014-05-08 18:49:52 -07006346 }
6347 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006348 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006349 status = BAD_VALUE;
6350 } else {
6351 // no need to save value, since it's constant
6352 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006353 }
Eric Laurent10351942014-05-08 18:49:52 -07006354 }
6355 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6356 // do not accept frame count changes if tracks are open as the track buffer
6357 // size depends on frame count and correct behavior would not be guaranteed
6358 // if frame count is changed after track creation
6359 if (!mTracks.isEmpty()) {
6360 status = INVALID_OPERATION;
6361 } else {
6362 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006363 }
Eric Laurent10351942014-05-08 18:49:52 -07006364 }
6365 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006366 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006367 }
Eric Laurent81784c32012-11-19 14:55:58 -08006368
Eric Laurent10351942014-05-08 18:49:52 -07006369 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006370 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006371 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006372 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6373 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006374 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006375 mThreadMetrics.logEndInterval();
6376 mThreadSnapshot.onEnd();
6377 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006378 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006379 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006380 }
Eric Laurent10351942014-05-08 18:49:52 -07006381 if (status == NO_ERROR && reconfig) {
6382 readOutputParameters_l();
6383 delete mAudioMixer;
6384 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006385 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006386 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006387 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006388 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006389 track->channelMask(),
6390 track->format(),
6391 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006392 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006393 "%s(): AudioMixer cannot create track(%d)"
6394 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006395 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006396 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006397 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006398 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006399 }
Eric Laurent81784c32012-11-19 14:55:58 -08006400 }
6401
Dean Wheatley68918102021-03-19 22:09:19 +11006402 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006403}
6404
6405
Andy Hung4b17e882023-07-07 13:47:37 -07006406void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006407{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006408 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung160664b2023-09-15 18:19:28 -07006409 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006410 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006411 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006412 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6413 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6414 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006415 if (hasFastMixer()) {
6416 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6417
6418 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6419 // while we are dumping it. It may be inconsistent, but it won't mutate!
6420 // This is a large object so we place it on the heap.
6421 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006422 const std::unique_ptr<FastMixerDumpState> copy =
6423 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006424 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006425
6426#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006427 // Similar for state queue
6428 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6429 observerCopy.dump(fd);
6430 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6431 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006432#endif
6433
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006434#ifdef AUDIO_WATCHDOG
6435 if (mAudioWatchdog != 0) {
6436 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6437 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6438 wdCopy.dump(fd);
6439 }
6440#endif
6441
6442 } else {
6443 dprintf(fd, " No FastMixer\n");
6444 }
Eric Laurent90cea102023-05-15 15:08:27 +02006445
6446 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6447 mBluetoothLatencyModesEnabled ? "" : "not ");
6448 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6449 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6450 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006451}
6452
Andy Hung4b17e882023-07-07 13:47:37 -07006453uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006454{
6455 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6456}
6457
Andy Hung4b17e882023-07-07 13:47:37 -07006458uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006459{
6460 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6461}
6462
Andy Hung4b17e882023-07-07 13:47:37 -07006463void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006464{
6465 PlaybackThread::cacheParameters_l();
6466
6467 // FIXME: Relaxed timing because of a certain device that can't meet latency
6468 // Should be reduced to 2x after the vendor fixes the driver issue
6469 // increase threshold again due to low power audio mode. The way this warning
6470 // threshold is calculated and its usefulness should be reconsidered anyway.
6471 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6472}
6473
Andy Hung4b17e882023-07-07 13:47:37 -07006474void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006475 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006476}
6477
Andy Hung4b17e882023-07-07 13:47:37 -07006478void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006479 // Only handle latency mode if:
6480 // - mBluetoothLatencyModesEnabled is true
6481 // - the HAL supports latency modes
6482 // - the selected device is Bluetooth LE or A2DP
6483 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6484 return;
6485 }
6486 if (mOutDeviceTypeAddrs.size() != 1
6487 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6488 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6489 return;
6490 }
6491
6492 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6493 if (mSupportedLatencyModes.size() == 1) {
6494 // If the HAL only support one latency mode currently, confirm the choice
6495 latencyMode = mSupportedLatencyModes[0];
6496 } else if (mSupportedLatencyModes.size() > 1) {
6497 // Request low latency if:
6498 // - At least one active track is either:
6499 // - a fast track with gaming usage or
6500 // - a track with acessibility usage
6501 for (const auto& track : mActiveTracks) {
6502 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6503 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6504 latencyMode = AUDIO_LATENCY_MODE_LOW;
6505 break;
6506 }
6507 }
6508 }
6509
6510 if (latencyMode != mSetLatencyMode) {
6511 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6512 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6513 __func__, mId, toString(latencyMode).c_str(), status);
6514 if (status == NO_ERROR) {
6515 mSetLatencyMode = latencyMode;
6516 }
6517 }
6518}
6519
Andy Hung4b17e882023-07-07 13:47:37 -07006520void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006521
6522 if (mOutput == nullptr || mOutput->stream == nullptr) {
6523 return;
6524 }
6525 std::vector<audio_latency_mode_t> latencyModes;
6526 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6527 if (status != NO_ERROR) {
6528 latencyModes.clear();
6529 }
6530 if (latencyModes != mSupportedLatencyModes) {
6531 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6532 __func__, mId, status, toString(latencyModes).c_str());
6533 mSupportedLatencyModes.swap(latencyModes);
6534 sendHalLatencyModesChangedEvent_l();
6535 }
6536}
6537
Andy Hung4b17e882023-07-07 13:47:37 -07006538status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006539 std::vector<audio_latency_mode_t>* modes) {
6540 if (modes == nullptr) {
6541 return BAD_VALUE;
6542 }
Andy Hungf8635b62023-08-31 16:13:39 -07006543 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006544 *modes = mSupportedLatencyModes;
6545 return NO_ERROR;
6546}
6547
Andy Hung4b17e882023-07-07 13:47:37 -07006548void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006549 std::vector<audio_latency_mode_t> modes) {
Andy Hungf8635b62023-08-31 16:13:39 -07006550 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006551 if (modes != mSupportedLatencyModes) {
6552 ALOGD("%s: thread(%d) supported latency modes: %s",
6553 __func__, mId, toString(modes).c_str());
6554 mSupportedLatencyModes.swap(modes);
6555 sendHalLatencyModesChangedEvent_l();
6556 }
6557}
6558
Andy Hung4b17e882023-07-07 13:47:37 -07006559status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006560 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6561 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6562 return INVALID_OPERATION;
6563 }
6564 mBluetoothLatencyModesEnabled.store(enabled);
6565 return NO_ERROR;
6566}
6567
Eric Laurent81784c32012-11-19 14:55:58 -08006568// ----------------------------------------------------------------------------
6569
Andy Hung4b17e882023-07-07 13:47:37 -07006570/* static */
6571sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006572 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006573 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6574 const audio_offload_info_t& offloadInfo) {
6575 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006576 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006577}
6578
Andy Hung7535ed92023-07-17 17:05:00 -07006579DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006580 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6581 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006582 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006583 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006584{
Andy Hung7535ed92023-07-17 17:05:00 -07006585 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006586}
6587
Andy Hung4b17e882023-07-07 13:47:37 -07006588DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006589{
6590}
6591
Andy Hung4b17e882023-07-07 13:47:37 -07006592void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006593{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006594 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006595 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6596 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6597}
6598
Andy Hung4b17e882023-07-07 13:47:37 -07006599void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006600{
Andy Hungf8635b62023-08-31 16:13:39 -07006601 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006602 if (mMasterBalance != balance) {
6603 mMasterBalance.store(balance);
6604 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6605 broadcast_l();
6606 }
6607}
6608
Andy Hung4b17e882023-07-07 13:47:37 -07006609void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006610{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006611 float left, right;
6612
Andy Hung333ab962019-05-28 20:23:35 -07006613 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006614 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006615
Andy Hung398ffa22022-12-13 19:19:53 -08006616 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6617 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6618
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006619 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6620 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006621
6622 const int64_t volumeShaperFrames =
6623 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6624 const auto [shaperVolume, shaperActive] =
6625 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006626 mVolumeShaperActive = shaperActive;
6627
Vlad Popae2f5aef2022-07-25 16:00:20 +02006628 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6629 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6630 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6631
6632 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6633
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006634 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006635 left = right = 0;
6636 } else {
6637 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006638 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006639
Glenn Kastenc56f3422014-03-21 17:53:17 -07006640 if (left > GAIN_FLOAT_UNITY) {
6641 left = GAIN_FLOAT_UNITY;
6642 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006643 if (right > GAIN_FLOAT_UNITY) {
6644 right = GAIN_FLOAT_UNITY;
6645 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006646 left *= v;
6647 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006648 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006649 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6650 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6651 right *= mMasterBalanceRight;
6652 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006653 }
6654
Andy Hung7535ed92023-07-17 17:05:00 -07006655 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006656 /*muteState=*/{mMasterMute,
6657 mStreamTypes[track->streamType()].volume == 0.f,
6658 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006659 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006660 clientVolumeMute,
6661 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006662
Eric Laurentbfb1b832013-01-07 09:53:42 -08006663 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006664 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006665 if (left != mLeftVolFloat || right != mRightVolFloat) {
6666 mLeftVolFloat = left;
6667 mRightVolFloat = right;
6668
Eric Laurentbfb1b832013-01-07 09:53:42 -08006669 // Delegate volume control to effect in track effect chain if needed
6670 // only one effect chain can be present on DirectOutputThread, so if
6671 // there is one, the track is connected to it
6672 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006673 // if effect chain exists, volume is handled by it.
6674 // Convert volumes from float to 8.24
6675 uint32_t vl = (uint32_t)(left * (1 << 24));
6676 uint32_t vr = (uint32_t)(right * (1 << 24));
6677 // Direct/Offload effect chains set output volume in setVolume_l().
6678 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6679 } else {
6680 // otherwise we directly set the volume.
6681 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006682 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006683 }
6684 }
6685}
6686
Andy Hung4b17e882023-07-07 13:47:37 -07006687void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006688{
Andy Hung11e74242023-06-26 19:20:57 -07006689 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6690 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006691
Eric Laurent0f0631e2015-07-06 18:01:25 -07006692 if (previousTrack != 0 && latestTrack != 0) {
6693 if (mType == DIRECT) {
6694 if (previousTrack.get() != latestTrack.get()) {
6695 mFlushPending = true;
6696 }
6697 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006698 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6699 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006700 mFlushPending = true;
6701 }
6702 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006703 } else if (previousTrack == 0) {
6704 // there could be an old track added back during track transition for direct
6705 // output, so always issues flush to flush data of the previous track if it
6706 // was already destroyed with HAL paused, then flush can resume the playback
6707 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006708 }
6709 PlaybackThread::onAddNewTrack_l();
6710}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006711
Andy Hung4b17e882023-07-07 13:47:37 -07006712PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006713 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006714)
6715{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006716 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006717 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006718 bool doHwPause = false;
6719 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006720
6721 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006722 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006723 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006724 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006725 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006726 continue;
6727 }
6728
Andy Hung11e74242023-06-26 19:20:57 -07006729 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006730#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006731 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006732#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006733 // Only consider last track started for volume and mixer state control.
6734 // In theory an older track could underrun and restart after the new one starts
6735 // but as we only care about the transition phase between two tracks on a
6736 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006737 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006738 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006739
Kuowei Li23666472021-01-20 10:23:25 +08006740 if (track->isPausePending()) {
6741 track->pauseAck();
6742 // It is possible a track might have been flushed or stopped.
6743 // Other operations such as flush pending might occur on the next prepare.
6744 if (track->isPausing()) {
6745 track->setPaused();
6746 }
6747 // Always perform pause, as an immediate flush will change
6748 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006749 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006750 doHwPause = true;
6751 mHwPaused = true;
6752 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006753 } else if (track->isFlushPending()) {
6754 track->flushAck();
6755 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006756 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006757 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006758 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006759 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006760 if (last) {
6761 mLeftVolFloat = mRightVolFloat = -1.0;
6762 if (mHwPaused) {
6763 doHwResume = true;
6764 mHwPaused = false;
6765 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006766 }
6767 }
6768
Eric Laurent81784c32012-11-19 14:55:58 -08006769 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006770 // for all its buffers to be filled before processing it.
6771 // Allow draining the buffer in case the client
6772 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006773 // hence the test on (track->retryCount() > 1).
6774 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006775 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6776 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006777 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006778
6779 // target retry count that we will use is based on the time we wait for retries.
6780 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6781 // the retry threshold is when we accept any size for PCM data. This is slightly
6782 // smaller than the retry count so we can push small bits of data without a glitch.
6783 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006784 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006785 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006786 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006787 minFrames = mNormalFrameCount;
6788 } else {
6789 minFrames = 1;
6790 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006791
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006792 const size_t framesReady = track->framesReady();
6793 const int trackId = track->id();
6794 if (ATRACE_ENABLED()) {
6795 std::string traceName("nRdy");
6796 traceName += std::to_string(trackId);
6797 ATRACE_INT(traceName.c_str(), framesReady);
6798 }
6799 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006800 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006801 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006802 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006803
Andy Hung11e74242023-06-26 19:20:57 -07006804 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6805 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006806 if (last) {
6807 // make sure processVolume_l() will apply new volume even if 0
6808 mLeftVolFloat = mRightVolFloat = -1.0;
6809 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006810 if (!mHwSupportsPause) {
6811 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006812 }
6813 }
6814
6815 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006816 processVolume_l(track, last);
6817 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006818 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006819 if (previousTrack != 0) {
6820 if (track != previousTrack.get()) {
6821 // Flush any data still being written from last track
6822 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006823 // Invalidate previous track to force a seek when resuming.
6824 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006825 }
6826 }
6827 mPreviousTrack = track;
6828
Eric Laurentd595b7c2013-04-03 17:27:56 -07006829 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006830 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006831 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006832 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006833 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006834 doHwResume = true;
6835 mHwPaused = false;
6836 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006837 }
Eric Laurent81784c32012-11-19 14:55:58 -08006838 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006839 // clear effect chain input buffer if the last active track started underruns
6840 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006841 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006842 mEffectChains[0]->clearInputBuffer();
6843 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006844 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006845 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006846 if (last && mHwPaused) {
6847 doHwResume = true;
6848 mHwPaused = false;
6849 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006850 }
6851 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6852 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006853 // We have consumed all the buffers of this track.
6854 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006855 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006856 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006857 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006858 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006859 if (presComplete) {
6860 mOutput->presentationComplete();
6861 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006862 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006863 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006864 }
Eric Laurent81784c32012-11-19 14:55:58 -08006865 if (track->isStopped()) {
6866 track->reset();
6867 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006868 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006869 }
6870 } else {
6871 // No buffers for this track. Give it a few chances to
6872 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006873 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006874 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006875 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006876 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006877 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006878 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006879 } else {
6880 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6881 tracksToRemove->add(track);
6882 // indicate to client process that the track was disabled because of
6883 // underrun; it will then automatically call start() when data is available
6884 track->disable();
6885 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6886 // unlike mixerthread, HAL can be paused for direct output
6887 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6888 "minFrames = %u, mFormat = %#x",
6889 framesReady, minFrames, mFormat);
6890 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6891 doHwPause = true;
6892 mHwPaused = true;
6893 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006894 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006895 } else if (last) {
6896 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006897 }
6898 }
6899 }
6900 }
6901
Eric Laurentd1f69b02014-12-15 14:33:13 -08006902 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006903 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006904 for (size_t i = 0; i < mTracks.size(); i++) {
6905 if (mTracks[i]->isFlushPending()) {
6906 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006907 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006908 }
6909 }
6910 }
6911
6912 // make sure the pause/flush/resume sequence is executed in the right order.
6913 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6914 // before flush and then resume HW. This can happen in case of pause/flush/resume
6915 // if resume is received before pause is executed.
6916 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006917 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006918 status_t result = mOutput->stream->pause();
6919 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006920 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006921 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006922 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006923 flushHw_l();
6924 }
6925 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006926 status_t result = mOutput->stream->resume();
6927 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006928 }
Eric Laurent81784c32012-11-19 14:55:58 -08006929 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006930 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006931
6932 return mixerStatus;
6933}
6934
Andy Hung4b17e882023-07-07 13:47:37 -07006935void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006936{
Eric Laurent81784c32012-11-19 14:55:58 -08006937 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006938 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006939 // output audio to hardware
6940 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006941 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006942 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006943 status_t status = mActiveTrack->getNextBuffer(&buffer);
6944 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006945 // no need to pad with 0 for compressed audio
6946 if (audio_has_proportional_frames(mFormat)) {
6947 memset(curBuf, 0, frameCount * mFrameSize);
6948 }
Eric Laurent81784c32012-11-19 14:55:58 -08006949 break;
6950 }
6951 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6952 frameCount -= buffer.frameCount;
6953 curBuf += buffer.frameCount * mFrameSize;
6954 mActiveTrack->releaseBuffer(&buffer);
6955 }
Andy Hung2098f272014-02-27 14:00:06 -08006956 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006957 mSleepTimeUs = 0;
6958 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006959 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006960}
6961
Andy Hung4b17e882023-07-07 13:47:37 -07006962void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006963{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006964 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006965 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006966 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006967 return;
6968 }
Andy Hung85ba3332021-04-27 17:40:26 -07006969 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6970 mSleepTimeUs = mActiveSleepTimeUs;
6971 } else {
6972 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006973 }
Andy Hung85ba3332021-04-27 17:40:26 -07006974 // Note: In S or later, we do not write zeroes for
6975 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006976}
6977
Andy Hung4b17e882023-07-07 13:47:37 -07006978void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006979{
6980 {
Andy Hungf8635b62023-08-31 16:13:39 -07006981 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006982 for (size_t i = 0; i < mTracks.size(); i++) {
6983 if (mTracks[i]->isFlushPending()) {
6984 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006985 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006986 }
6987 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006988 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006989 flushHw_l();
6990 }
6991 }
6992 PlaybackThread::threadLoop_exit();
6993}
6994
6995// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07006996bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006997{
6998 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006999 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007000
7001 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
7002 // after a timeout and we will enter standby then.
7003 if (mTracks.size() > 0) {
7004 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07007005 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07007006 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007007 }
7008
Eric Laurent5cff4032015-05-26 13:49:58 -07007009 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08007010}
7011
Andy Hungb17d24b2023-08-29 14:26:09 -07007012// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07007013bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007014 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007015{
7016 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007017 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007018
Eric Laurent10351942014-05-08 18:49:52 -07007019 AudioParameter param = AudioParameter(keyValuePair);
7020 int value;
7021 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007022 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007023 }
Eric Laurent10351942014-05-08 18:49:52 -07007024 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7025 // do not accept frame count changes if tracks are open as the track buffer
7026 // size depends on frame count and correct behavior would not be garantied
7027 // if frame count is changed after track creation
7028 if (!mTracks.isEmpty()) {
7029 status = INVALID_OPERATION;
7030 } else {
7031 reconfig = true;
7032 }
7033 }
7034 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007035 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007036 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007037 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007038 if (!mStandby) {
7039 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007040 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007041 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007042 }
Eric Laurent10351942014-05-08 18:49:52 -07007043 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007044 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007045 }
7046 if (status == NO_ERROR && reconfig) {
7047 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007048 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007049 }
7050 }
7051
Dean Wheatley68918102021-03-19 22:09:19 +11007052 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007053}
7054
Andy Hung4b17e882023-07-07 13:47:37 -07007055uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007056{
7057 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007058 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007059 time = PlaybackThread::activeSleepTimeUs();
7060 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007061 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007062 }
7063 return time;
7064}
7065
Andy Hung4b17e882023-07-07 13:47:37 -07007066uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007067{
7068 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007069 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007070 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7071 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007072 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007073 }
7074 return time;
7075}
7076
Andy Hung4b17e882023-07-07 13:47:37 -07007077uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007078{
7079 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007080 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007081 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7082 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007083 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007084 }
7085 return time;
7086}
7087
Andy Hung4b17e882023-07-07 13:47:37 -07007088void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007089{
7090 PlaybackThread::cacheParameters_l();
7091
7092 // use shorter standby delay as on normal output to release
7093 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007094 // no delay on outputs with HW A/V sync
7095 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007096 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007097 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007098 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007099 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007100 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007101 }
Eric Laurent81784c32012-11-19 14:55:58 -08007102}
7103
Andy Hung4b17e882023-07-07 13:47:37 -07007104void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007105{
ziyangch8f194f12021-12-01 13:48:04 -08007106 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007107 mOutput->flush();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007108 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007109 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007110 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007111 mMonotonicFrameCounter.onFlush();
Gareth Fenn5db373e2024-06-06 15:38:23 +00007112 // We do not reset mHwPaused which is hidden from the Track client.
7113 // Note: the client track in Tracks.cpp and AudioTrack.cpp
7114 // has a FLUSHED state but the DirectOutputThread does not;
7115 // those tracks will continue to show isStopped().
Eric Laurente659ef42014-09-29 13:06:46 -07007116}
7117
Andy Hung4b17e882023-07-07 13:47:37 -07007118int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007119 // If a VolumeShaper is active, we must wake up periodically to update volume.
7120 const int64_t NS_PER_MS = 1000000;
7121 return mVolumeShaperActive ?
7122 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7123}
7124
Eric Laurent81784c32012-11-19 14:55:58 -08007125// ----------------------------------------------------------------------------
7126
Andy Hung4b17e882023-07-07 13:47:37 -07007127AsyncCallbackThread::AsyncCallbackThread(
7128 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007129 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007130 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007131 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007132 mDrainSequence(0),
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007133 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007134{
7135}
7136
Andy Hung4b17e882023-07-07 13:47:37 -07007137void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007138{
7139 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7140}
7141
Andy Hung4b17e882023-07-07 13:47:37 -07007142bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007143{
7144 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007145 uint32_t writeAckSequence;
7146 uint32_t drainSequence;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007147 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007148
7149 {
Andy Hungb17d24b2023-08-29 14:26:09 -07007150 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007151 while (!((mWriteAckSequence & 1) ||
7152 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007153 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007154 exitPending())) {
Andy Hungb17d24b2023-08-29 14:26:09 -07007155 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007156 }
7157
Eric Laurentbfb1b832013-01-07 09:53:42 -08007158 if (exitPending()) {
7159 break;
7160 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007161 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7162 mWriteAckSequence, mDrainSequence);
7163 writeAckSequence = mWriteAckSequence;
7164 mWriteAckSequence &= ~1;
7165 drainSequence = mDrainSequence;
7166 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007167 asyncError = mAsyncError;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007168 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007169 }
7170 {
Andy Hung4b17e882023-07-07 13:47:37 -07007171 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007172 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007173 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007174 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007175 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007176 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007177 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007178 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007179 if (asyncError != ASYNC_ERROR_NONE) {
7180 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007181 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007182 }
7183 }
7184 }
7185 return false;
7186}
7187
Andy Hung4b17e882023-07-07 13:47:37 -07007188void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007189{
7190 ALOGV("AsyncCallbackThread::exit");
Andy Hungf8635b62023-08-31 16:13:39 -07007191 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007192 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -07007193 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007194}
7195
Andy Hung4b17e882023-07-07 13:47:37 -07007196void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007197{
Andy Hungf8635b62023-08-31 16:13:39 -07007198 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007199 // bit 0 is cleared
7200 mWriteAckSequence = sequence << 1;
7201}
7202
Andy Hung4b17e882023-07-07 13:47:37 -07007203void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007204{
Andy Hungf8635b62023-08-31 16:13:39 -07007205 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007206 // ignore unexpected callbacks
7207 if (mWriteAckSequence & 2) {
7208 mWriteAckSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007209 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007210 }
7211}
7212
Andy Hung4b17e882023-07-07 13:47:37 -07007213void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007214{
Andy Hungf8635b62023-08-31 16:13:39 -07007215 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007216 // bit 0 is cleared
7217 mDrainSequence = sequence << 1;
7218}
7219
Andy Hung4b17e882023-07-07 13:47:37 -07007220void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007221{
Andy Hungf8635b62023-08-31 16:13:39 -07007222 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007223 // ignore unexpected callbacks
7224 if (mDrainSequence & 2) {
7225 mDrainSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007226 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007227 }
7228}
7229
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007230void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007231{
Andy Hungf8635b62023-08-31 16:13:39 -07007232 audio_utils::lock_guard _l(mutex());
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007233 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungb17d24b2023-08-29 14:26:09 -07007234 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007235}
7236
Eric Laurentbfb1b832013-01-07 09:53:42 -08007237
7238// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007239
7240/* static */
7241sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007242 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007243 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7244 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007245 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007246}
7247
Andy Hung7535ed92023-07-17 17:05:00 -07007248OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007249 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7250 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007251 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007252 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007253{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007254 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007255 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007256 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007257}
7258
Andy Hung4b17e882023-07-07 13:47:37 -07007259void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007260{
7261 if (mFlushPending || mHwPaused) {
7262 // If a flush is pending or track was paused, just discard buffered data
Andy Hung94dfbb42023-09-06 19:41:47 -07007263 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007264 flushHw_l();
7265 } else {
7266 mMixerStatus = MIXER_DRAIN_ALL;
7267 threadLoop_drain();
7268 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007269 if (mUseAsyncWrite) {
7270 ALOG_ASSERT(mCallbackThread != 0);
7271 mCallbackThread->exit();
7272 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007273 PlaybackThread::threadLoop_exit();
7274}
7275
Andy Hung4b17e882023-07-07 13:47:37 -07007276PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007277 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007278)
7279{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007280 size_t count = mActiveTracks.size();
7281
7282 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007283 bool doHwPause = false;
7284 bool doHwResume = false;
7285
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007286 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007287
Eric Laurentbfb1b832013-01-07 09:53:42 -08007288 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007289 for (const sp<IAfTrack>& t : mActiveTracks) {
7290 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007291#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007292 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007293#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007294 // Only consider last track started for volume and mixer state control.
7295 // In theory an older track could underrun and restart after the new one starts
7296 // but as we only care about the transition phase between two tracks on a
7297 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007298 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007299 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007300
Haynes Mathew George7844f672014-01-15 12:32:55 -08007301 if (track->isInvalid()) {
7302 ALOGW("An invalidated track shouldn't be in active list");
7303 tracksToRemove->add(track);
7304 continue;
7305 }
7306
Andy Hung11e74242023-06-26 19:20:57 -07007307 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007308 ALOGW("An idle track shouldn't be in active list");
7309 continue;
7310 }
7311
Kuowei Li23666472021-01-20 10:23:25 +08007312 if (track->isPausePending()) {
7313 track->pauseAck();
7314 // It is possible a track might have been flushed or stopped.
7315 // Other operations such as flush pending might occur on the next prepare.
7316 if (track->isPausing()) {
7317 track->setPaused();
7318 }
7319 // Always perform pause if last, as an immediate flush will change
7320 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007321 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007322 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007323 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007324 mHwPaused = true;
7325 }
7326 // If we were part way through writing the mixbuffer to
7327 // the HAL we must save this until we resume
7328 // BUG - this will be wrong if a different track is made active,
7329 // in that case we want to discard the pending data in the
7330 // mixbuffer and tell the client to present it again when the
7331 // track is resumed
7332 mPausedWriteLength = mCurrentWriteLength;
7333 mPausedBytesRemaining = mBytesRemaining;
7334 mBytesRemaining = 0; // stop writing
7335 }
7336 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007337 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007338 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007339 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007340 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007341 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007342 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007343 track->flushAck();
7344 if (last) {
7345 mFlushPending = true;
7346 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007347 } else if (track->isResumePending()){
7348 track->resumeAck();
7349 if (last) {
7350 if (mPausedBytesRemaining) {
7351 // Need to continue write that was interrupted
7352 mCurrentWriteLength = mPausedWriteLength;
7353 mBytesRemaining = mPausedBytesRemaining;
7354 mPausedBytesRemaining = 0;
7355 }
7356 if (mHwPaused) {
7357 doHwResume = true;
7358 mHwPaused = false;
7359 // threadLoop_mix() will handle the case that we need to
7360 // resume an interrupted write
7361 }
7362 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007363 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007364
Eric Laurent3df841a2016-07-15 15:15:40 -07007365 mLeftVolFloat = mRightVolFloat = -1.0;
7366
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007367 // Do not handle new data in this iteration even if track->framesReady()
7368 mixerStatus = MIXER_TRACKS_ENABLED;
7369 }
7370 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007371 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007372 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007373 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7374 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007375 if (last) {
7376 // make sure processVolume_l() will apply new volume even if 0
7377 mLeftVolFloat = mRightVolFloat = -1.0;
7378 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007379 }
7380
7381 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007382 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007383 if (previousTrack != 0) {
7384 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007385 // Flush any data still being written from last track
7386 mBytesRemaining = 0;
7387 if (mPausedBytesRemaining) {
7388 // Last track was paused so we also need to flush saved
7389 // mixbuffer state and invalidate track so that it will
7390 // re-submit that unwritten data when it is next resumed
7391 mPausedBytesRemaining = 0;
7392 // Invalidate is a bit drastic - would be more efficient
7393 // to have a flag to tell client that some of the
7394 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007395 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007396 }
7397 // flush data already sent to the DSP if changing audio session as audio
7398 // comes from a different source. Also invalidate previous track to force a
7399 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007400 if (previousTrack->sessionId() != track->sessionId()) {
7401 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007402 }
7403 }
7404 }
7405 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007406 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007407 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007408 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007409 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007410 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007411 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007412 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007413 mixerStatus = MIXER_TRACKS_READY;
7414 }
7415 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007416 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007417 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007418 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007419 // Hardware buffer can hold a large amount of audio so we must
7420 // wait for all current track's data to drain before we say
7421 // that the track is stopped.
7422 if (mBytesRemaining == 0) {
7423 // Only start draining when all data in mixbuffer
7424 // has been written
7425 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007426 track->setState(IAfTrackBase::STOPPING_2);
7427 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007428 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7429 if (last && !mStandby) {
7430 // do not modify drain sequence if we are already draining. This happens
7431 // when resuming from pause after drain.
7432 if ((mDrainSequence & 1) == 0) {
7433 mSleepTimeUs = 0;
7434 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7435 mixerStatus = MIXER_DRAIN_TRACK;
7436 mDrainSequence += 2;
7437 }
7438 if (mHwPaused) {
7439 // It is possible to move from PAUSED to STOPPING_1 without
7440 // a resume so we must ensure hardware is running
7441 doHwResume = true;
7442 mHwPaused = false;
7443 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007444 }
7445 }
Eric Laurente93cc032016-05-05 10:15:10 -07007446 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007447 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007448 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007449 }
7450 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007451 // Drain has completed or we are in standby, signal presentation complete
7452 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007453 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007454 mOutput->presentationComplete();
7455 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007456 track->reset();
7457 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007458 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007459 if (!mUseAsyncWrite) {
7460 // If we don't get explicit drain notification we must
7461 // register discontinuity regardless of whether this is
7462 // the previous (!last) or the upcoming (last) track
7463 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007464 mTimestampVerifier.discontinuity(
7465 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007466 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007467 }
7468 } else {
7469 // No buffers for this track. Give it a few chances to
7470 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007471 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007472 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007473 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007474 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007475 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007476 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007477 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7478 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007479 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007480 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007481 // it will then automatically call start() when data is available
7482 track->disable();
7483 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007484 } else if (last){
7485 mixerStatus = MIXER_TRACKS_ENABLED;
7486 }
7487 }
7488 }
7489 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007490 if (track->isReady()) { // check ready to prevent premature start.
7491 processVolume_l(track, last);
7492 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007493 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007494
Eric Laurentea0fade2013-10-04 16:23:48 -07007495 // make sure the pause/flush/resume sequence is executed in the right order.
7496 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7497 // before flush and then resume HW. This can happen in case of pause/flush/resume
7498 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007499 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007500 status_t result = mOutput->stream->pause();
7501 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007502 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007503 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007504 if (mFlushPending) {
7505 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007506 }
Eric Laurentfd477972013-10-25 18:10:40 -07007507 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007508 status_t result = mOutput->stream->resume();
7509 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007510 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007511
Eric Laurentbfb1b832013-01-07 09:53:42 -08007512 // remove all the tracks that need to be...
7513 removeTracks_l(*tracksToRemove);
7514
7515 return mixerStatus;
7516}
7517
Eric Laurentbfb1b832013-01-07 09:53:42 -08007518// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007519bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007520{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007521 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7522 mWriteAckSequence, mDrainSequence);
7523 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007524 return true;
7525 }
7526 return false;
7527}
7528
Andy Hung4b17e882023-07-07 13:47:37 -07007529bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007530{
Andy Hungf8635b62023-08-31 16:13:39 -07007531 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007532 return waitingAsyncCallback_l();
7533}
7534
Andy Hung4b17e882023-07-07 13:47:37 -07007535void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007536{
Eric Laurente659ef42014-09-29 13:06:46 -07007537 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007538 // Flush anything still waiting in the mixbuffer
7539 mCurrentWriteLength = 0;
7540 mBytesRemaining = 0;
7541 mPausedWriteLength = 0;
7542 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007543 // reset bytes written count to reflect that DSP buffers are empty after flush.
7544 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007545
Eric Laurentbfb1b832013-01-07 09:53:42 -08007546 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007547 // discard any pending drain or write ack by incrementing sequence
7548 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7549 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007550 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007551 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7552 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007553 }
7554}
7555
Andy Hung4b17e882023-07-07 13:47:37 -07007556void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007557{
Andy Hungf8635b62023-08-31 16:13:39 -07007558 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007559 if (PlaybackThread::invalidateTracks_l(streamType)) {
7560 mFlushPending = true;
7561 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007562}
7563
Andy Hung4b17e882023-07-07 13:47:37 -07007564void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07007565 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007566 if (PlaybackThread::invalidateTracks_l(portIds)) {
7567 mFlushPending = true;
7568 }
7569}
7570
Eric Laurentbfb1b832013-01-07 09:53:42 -08007571// ----------------------------------------------------------------------------
7572
Andy Hung4b17e882023-07-07 13:47:37 -07007573/* static */
7574sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007575 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007576 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007577 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007578}
7579
Andy Hung7535ed92023-07-17 17:05:00 -07007580DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007581 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007582 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007583 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007584 mWaitTimeMs(UINT_MAX)
7585{
7586 addOutputTrack(mainThread);
7587}
7588
Andy Hung4b17e882023-07-07 13:47:37 -07007589DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007590{
7591 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7592 mOutputTracks[i]->destroy();
7593 }
7594}
7595
Andy Hung4b17e882023-07-07 13:47:37 -07007596void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007597{
7598 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007599 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007600 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007601 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007602 if (mMixerBufferValid) {
7603 memset(mMixerBuffer, 0, mMixerBufferSize);
7604 } else {
7605 memset(mSinkBuffer, 0, mSinkBufferSize);
7606 }
Eric Laurent81784c32012-11-19 14:55:58 -08007607 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007608 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007609 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007610 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007611 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007612}
7613
Andy Hung4b17e882023-07-07 13:47:37 -07007614void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007615{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007616 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007617 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007618 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007619 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007620 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007621 }
7622 } else if (mBytesWritten != 0) {
7623 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7624 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007625 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007626 } else {
7627 // flush remaining overflow buffers in output tracks
7628 writeFrames = 0;
7629 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007630 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007631 }
7632}
7633
Andy Hung4b17e882023-07-07 13:47:37 -07007634ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007635{
7636 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007637 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7638
7639 // Consider the first OutputTrack for timestamp and frame counting.
7640
7641 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7642 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7643 // we always claim success.
7644 if (i == 0) {
7645 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7646 ALOGD_IF(correction != 0 && writeFrames != 0,
7647 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7648 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7649 mFramesWritten -= correction;
7650 }
7651
7652 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007653 }
Andy Hungcf10d742020-04-28 15:38:24 -07007654 if (mStandby) {
7655 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007656 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007657 mStandby = false;
7658 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007659 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007660}
7661
Andy Hung4b17e882023-07-07 13:47:37 -07007662void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007663{
7664 // DuplicatingThread implements standby by stopping all tracks
7665 for (size_t i = 0; i < outputTracks.size(); i++) {
7666 outputTracks[i]->stop();
7667 }
7668}
7669
Andy Hung8a5abfd2023-12-07 19:35:12 -08007670void DuplicatingThread::threadLoop_exit()
7671{
7672 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7673 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7674 // Do so here in the threadLoop_exit().
7675
7676 SortedVector <sp<IAfOutputTrack>> localTracks;
7677 {
7678 audio_utils::lock_guard l(mutex());
7679 localTracks = std::move(mOutputTracks);
7680 mOutputTracks.clear();
7681 }
7682 localTracks.clear();
7683 outputTracks.clear();
7684 PlaybackThread::threadLoop_exit();
7685}
7686
Andy Hung4b17e882023-07-07 13:47:37 -07007687void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007688{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007689 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007690
7691 std::stringstream ss;
7692 const size_t numTracks = mOutputTracks.size();
7693 ss << " " << numTracks << " OutputTracks";
7694 if (numTracks > 0) {
7695 ss << ":";
7696 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007697 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007698 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007699 if (thread.get() != nullptr) {
7700 ss << thread.get() << ", " << thread->id();
7701 } else {
7702 ss << "null";
7703 }
7704 ss << ")";
7705 }
7706 }
7707 ss << "\n";
7708 std::string result = ss.str();
7709 write(fd, result.c_str(), result.size());
7710}
7711
Andy Hung4b17e882023-07-07 13:47:37 -07007712void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007713{
7714 outputTracks = mOutputTracks;
7715}
7716
Andy Hung4b17e882023-07-07 13:47:37 -07007717void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007718{
7719 outputTracks.clear();
7720}
7721
Andy Hung4b17e882023-07-07 13:47:37 -07007722void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007723{
Andy Hungf8635b62023-08-31 16:13:39 -07007724 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007725 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7726 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7727 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7728 const size_t frameCount =
7729 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7730 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7731 // from different OutputTracks and their associated MixerThreads (e.g. one may
7732 // nearly empty and the other may be dropping data).
7733
Svet Ganov33761132021-05-13 22:51:08 +00007734 // TODO b/182392769: use attribution source util, move to server edge
7735 AttributionSourceState attributionSource = AttributionSourceState();
7736 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007737 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007738 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007739 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007740 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007741 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007742 this,
7743 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007744 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007745 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007746 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007747 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007748 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7749 if (status != NO_ERROR) {
7750 ALOGE("addOutputTrack() initCheck failed %d", status);
7751 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007752 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007753 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7754 mOutputTracks.add(outputTrack);
7755 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7756 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007757}
7758
Andy Hung4b17e882023-07-07 13:47:37 -07007759void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007760{
Andy Hungf8635b62023-08-31 16:13:39 -07007761 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007762 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7763 if (mOutputTracks[i]->thread() == thread) {
7764 mOutputTracks[i]->destroy();
7765 mOutputTracks.removeAt(i);
7766 updateWaitTime_l();
Andy Hung160664b2023-09-15 18:19:28 -07007767 // NO_THREAD_SAFETY_ANALYSIS
7768 // Lambda workaround: as thread != this
7769 // we can safely call the remote thread getOutput.
7770 const bool equalOutput =
7771 [&](){ return thread->getOutput() == mOutput; }();
7772 if (equalOutput) {
7773 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007774 }
Eric Laurent81784c32012-11-19 14:55:58 -08007775 return;
7776 }
7777 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007778 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007779}
7780
Andy Hungb17d24b2023-08-29 14:26:09 -07007781// caller must hold mutex()
Andy Hung4b17e882023-07-07 13:47:37 -07007782void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007783{
7784 mWaitTimeMs = UINT_MAX;
7785 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007786 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007787 if (strong != 0) {
7788 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7789 if (waitTimeMs < mWaitTimeMs) {
7790 mWaitTimeMs = waitTimeMs;
7791 }
7792 }
7793 }
7794}
7795
Andy Hung4b17e882023-07-07 13:47:37 -07007796bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007797{
7798 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007799 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007800 if (thread == 0) {
7801 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7802 outputTracks[i].get());
7803 return false;
7804 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007805 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007806 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007807 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007808 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7809 thread.get());
7810 return false;
7811 }
7812 }
7813 return true;
7814}
7815
Andy Hung4b17e882023-07-07 13:47:37 -07007816void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007817 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007818{
Kevin Rocard12381092018-04-11 09:19:59 -07007819 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7820 outputTrack->setMetadatas(metadata.tracks);
7821 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007822}
7823
Andy Hung4b17e882023-07-07 13:47:37 -07007824uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007825{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007826 // return half the wait time in microseconds.
7827 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007828}
7829
Andy Hung4b17e882023-07-07 13:47:37 -07007830void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007831{
7832 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7833 updateWaitTime_l();
7834
7835 MixerThread::cacheParameters_l();
7836}
7837
Eric Laurentb3f315a2021-07-13 15:09:05 +02007838// ----------------------------------------------------------------------------
7839
Andy Hung4b17e882023-07-07 13:47:37 -07007840/* static */
7841sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007842 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007843 AudioStreamOut* output,
7844 audio_io_handle_t id,
7845 bool systemReady,
7846 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007847 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007848}
7849
Andy Hung7535ed92023-07-17 17:05:00 -07007850SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007851 AudioStreamOut* output,
7852 audio_io_handle_t id,
7853 bool systemReady,
7854 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007855 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007856{
7857}
7858
Andy Hung4b17e882023-07-07 13:47:37 -07007859void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007860 // if mSupportedLatencyModes is empty, the HAL stream does not support
7861 // latency mode control and we can exit.
7862 if (mSupportedLatencyModes.empty()) {
7863 return;
7864 }
7865 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7866 if (mSupportedLatencyModes.size() == 1) {
7867 // If the HAL only support one latency mode currently, confirm the choice
7868 latencyMode = mSupportedLatencyModes[0];
7869 } else if (mSupportedLatencyModes.size() > 1) {
7870 // Request low latency if:
7871 // - The low latency mode is requested by the spatializer controller
7872 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7873 // AND
7874 // - At least one active track is spatialized
7875 bool hasSpatializedActiveTrack = false;
7876 for (const auto& track : mActiveTracks) {
7877 if (track->isSpatialized()) {
7878 hasSpatializedActiveTrack = true;
7879 break;
7880 }
7881 }
7882 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7883 latencyMode = AUDIO_LATENCY_MODE_LOW;
7884 }
7885 }
7886
7887 if (latencyMode != mSetLatencyMode) {
7888 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007889 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7890 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007891 if (status == NO_ERROR) {
7892 mSetLatencyMode = latencyMode;
7893 }
7894 }
7895}
7896
Andy Hung4b17e882023-07-07 13:47:37 -07007897status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007898 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7899 return BAD_VALUE;
7900 }
Andy Hungf8635b62023-08-31 16:13:39 -07007901 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007902 mRequestedLatencyMode = mode;
7903 return NO_ERROR;
7904}
7905
Andy Hung4b17e882023-07-07 13:47:37 -07007906void SpatializerThread::checkOutputStageEffects()
Andy Hungf8635b62023-08-31 16:13:39 -07007907NO_THREAD_SAFETY_ANALYSIS
7908// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007909{
7910 bool hasVirtualizer = false;
7911 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007912 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007913 {
Andy Hungf8635b62023-08-31 16:13:39 -07007914 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007915 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007916 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007917 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007918 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7919 }
7920
7921 finalDownMixer = mFinalDownMixer;
7922 mFinalDownMixer.clear();
7923 }
7924
7925 if (hasVirtualizer) {
7926 if (finalDownMixer != nullptr) {
7927 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007928 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007929 }
7930 finalDownMixer.clear();
7931 } else if (!hasDownMixer) {
7932 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07007933 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007934 EFFECT_UIID_DOWNMIX, &descriptors);
7935 if (status != NO_ERROR) {
7936 return;
7937 }
7938 ALOG_ASSERT(!descriptors.empty(),
7939 "%s getDescriptors() returned no error but empty list", __func__);
7940
7941 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7942 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007943 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007944
7945 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7946 ALOGW("%s error creating downmixer %d", __func__, status);
7947 finalDownMixer.clear();
7948 } else {
7949 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007950 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007951 }
7952 }
7953
7954 {
Andy Hungf8635b62023-08-31 16:13:39 -07007955 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007956 mFinalDownMixer = finalDownMixer;
7957 }
7958}
7959
Andy Hunge2514462023-12-06 14:59:24 -08007960void SpatializerThread::threadLoop_exit()
7961{
7962 // The Spatializer EffectHandle must be released on the PlaybackThread
7963 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
7964 mFinalDownMixer.clear();
7965
7966 PlaybackThread::threadLoop_exit();
7967}
7968
Eric Laurent81784c32012-11-19 14:55:58 -08007969// ----------------------------------------------------------------------------
7970// Record
7971// ----------------------------------------------------------------------------
7972
Andy Hung7535ed92023-07-17 17:05:00 -07007973sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007974 AudioStreamIn* input,
7975 audio_io_handle_t id,
7976 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007977 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07007978}
7979
Andy Hung7535ed92023-07-17 17:05:00 -07007980RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007981 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007982 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007983 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007984 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07007985 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007986 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007987 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007988 mActiveTracks(&this->mLocalLog),
7989 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007990 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007991 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007992 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7993 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007994 // mFastCapture below
7995 , mFastCaptureFutex(0)
7996 // mInputSource
7997 // mPipeSink
7998 // mPipeSource
7999 , mPipeFramesP2(0)
8000 // mPipeMemory
8001 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008002 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008003 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008004{
Glenn Kastend7dca052015-03-05 16:05:54 -08008005 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07008006 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008007
George Burgess IVa8f90c12020-05-14 11:27:19 -07008008 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008009 mIsMsdDevice = strcmp(
8010 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8011 }
8012
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008013 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008014
Andy Hungc8fddf32018-08-08 18:32:37 -07008015 // TODO: We may also match on address as well as device type for
8016 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008017 // TODO: This property should be ensure that only contains one single device type.
8018 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8019 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008020 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8021 : AUDIO_DEVICE_NONE));
8022
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008023 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008024 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008025 size_t numCounterOffers = 0;
8026 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008027#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008028 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008029#else
8030 (void)
8031#endif
8032 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008033 ALOG_ASSERT(index == 0);
8034
8035 // initialize fast capture depending on configuration
8036 bool initFastCapture;
8037 switch (kUseFastCapture) {
8038 case FastCapture_Never:
8039 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008040 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008041 break;
8042 case FastCapture_Always:
8043 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008044 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008045 break;
8046 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008047 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008048 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008049 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008050 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8051 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8052 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008053 break;
8054 // case FastCapture_Dynamic:
8055 }
8056
8057 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008058 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008059 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008060 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8061 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008062 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008063 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008064 const sp<MemoryDealer> roHeap(readOnlyHeap());
8065 sp<IMemory> pipeMemory;
8066 if ((roHeap == 0) ||
8067 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008068 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008069 ALOGE("not enough memory for pipe buffer size=%zu; "
8070 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8071 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8072 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008073 goto failed;
8074 }
8075 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8076 memset(pipeBuffer, 0, pipeSize);
8077 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008078 const NBAIO_Format offersFast[1] = {format};
8079 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008080 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008081 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008082 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008083 mPipeSink = pipe;
8084 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008085 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008086 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008087 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008088 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008089 mPipeSource = pipeReader;
8090 mPipeFramesP2 = pipeFramesP2;
8091 mPipeMemory = pipeMemory;
8092
8093 // create fast capture
8094 mFastCapture = new FastCapture();
8095 FastCaptureStateQueue *sq = mFastCapture->sq();
8096#ifdef STATE_QUEUE_DUMP
8097 // FIXME
8098#endif
8099 FastCaptureState *state = sq->begin();
8100 state->mCblk = NULL;
8101 state->mInputSource = mInputSource.get();
8102 state->mInputSourceGen++;
8103 state->mPipeSink = pipe;
8104 state->mPipeSinkGen++;
8105 state->mFrameCount = mFrameCount;
8106 state->mCommand = FastCaptureState::COLD_IDLE;
8107 // already done in constructor initialization list
8108 //mFastCaptureFutex = 0;
8109 state->mColdFutexAddr = &mFastCaptureFutex;
8110 state->mColdGen++;
8111 state->mDumpState = &mFastCaptureDumpState;
8112#ifdef TEE_SINK
8113 // FIXME
8114#endif
Andy Hung7535ed92023-07-17 17:05:00 -07008115 mFastCaptureNBLogWriter =
8116 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008117 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8118 sq->end();
8119 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8120
8121 // start the fast capture
8122 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8123 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008124 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008125 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008126#ifdef AUDIO_WATCHDOG
8127 // FIXME
8128#endif
8129
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008130 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008131 }
Andy Hung8946a282018-04-19 20:04:56 -07008132#ifdef TEE_SINK
8133 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8134 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8135#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008136failed: ;
8137
8138 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008139}
8140
Andy Hung4b17e882023-07-07 13:47:37 -07008141RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008142{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008143 if (mFastCapture != 0) {
8144 FastCaptureStateQueue *sq = mFastCapture->sq();
8145 FastCaptureState *state = sq->begin();
8146 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8147 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8148 if (old == -1) {
8149 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8150 }
8151 }
8152 state->mCommand = FastCaptureState::EXIT;
8153 sq->end();
8154 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8155 mFastCapture->join();
8156 mFastCapture.clear();
8157 }
Andy Hung7535ed92023-07-17 17:05:00 -07008158 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8159 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008160 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008161}
8162
Andy Hung4b17e882023-07-07 13:47:37 -07008163void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008164{
Glenn Kastend7dca052015-03-05 16:05:54 -08008165 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008166}
8167
Andy Hung4b17e882023-07-07 13:47:37 -07008168void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008169{
8170 ALOGV(" preExit()");
Andy Hungf8635b62023-08-31 16:13:39 -07008171 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008172 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008173 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008174 track->invalidate();
8175 }
8176 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008177 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008178}
8179
Andy Hung4b17e882023-07-07 13:47:37 -07008180bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008181{
Eric Laurent81784c32012-11-19 14:55:58 -08008182 nsecs_t lastWarning = 0;
8183
8184 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008185
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008186reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008187 {
Andy Hungf8635b62023-08-31 16:13:39 -07008188 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008189 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008190 }
8191
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008192 // used to request a deferred sleep, to be executed later while mutex is unlocked
8193 uint32_t sleepUs = 0;
8194
Andy Hung1381a072023-10-20 16:41:18 -07008195 // timestamp correction enable is determined under lock, used in processing step.
8196 bool timestampCorrectionEnabled = false;
8197
Andy Hung446f4df2019-02-21 12:26:41 -08008198 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8199
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008200 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008201 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungfdb84b92024-03-15 10:15:10 -07008202 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8203 sp<IAfRecordTrack> activeTrack;
Andy Hungb2b01c62024-04-23 13:56:19 -07008204 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008205 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008206
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008207 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008208 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008209
Glenn Kasten735f45f2014-08-18 15:51:59 -07008210 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008211 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008212
Glenn Kasten735f45f2014-08-18 15:51:59 -07008213 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008214 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008215
Eric Laurent33403f02020-05-29 18:35:06 -07008216 bool silenceFastCapture = false;
8217
Andy Hungb17d24b2023-08-29 14:26:09 -07008218 { // scope for mutex()
8219 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008220
Eric Laurent021cf962014-05-13 10:18:14 -07008221 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008222
Eric Laurent000a4192014-01-29 15:17:32 -08008223 // check exitPending here because checkForNewParameters_l() and
Andy Hungb17d24b2023-08-29 14:26:09 -07008224 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008225 if (exitPending()) {
8226 break;
8227 }
8228
Eric Laurent5c25d562016-07-13 17:17:45 -07008229 // sleep with mutex unlocked
8230 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008231 ATRACE_BEGIN("sleepC");
Andy Hungb17d24b2023-08-29 14:26:09 -07008232 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008233 ATRACE_END();
8234 sleepUs = 0;
8235 continue;
8236 }
8237
Glenn Kasten2b806402013-11-20 16:37:38 -08008238 // if no active track(s), then standby and release wakelock
8239 size_t size = mActiveTracks.size();
8240 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008241 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008242 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008243 releaseWakeLock_l();
8244 ALOGV("RecordThread: loop stopping");
8245 // go to sleep
Andy Hungb17d24b2023-08-29 14:26:09 -07008246 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008247 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008248 goto reacquire_wakelock;
8249 }
8250
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008251 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008252 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008253 for (size_t i = 0; i < size; ) {
Andy Hungb2b01c62024-04-23 13:56:19 -07008254 if (activeTrack) { // ensure track release is outside lock.
8255 oldActiveTracks.emplace_back(std::move(activeTrack));
8256 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008257 activeTrack = mActiveTracks[i];
8258 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008259 if (activeTrack->isFastTrack()) {
8260 ALOG_ASSERT(fastTrackToRemove == 0);
8261 fastTrackToRemove = activeTrack;
8262 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008263 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008264 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008265 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008266 continue;
8267 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008268
Andy Hung11e74242023-06-26 19:20:57 -07008269 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008270 switch (activeTrackState) {
8271
Andy Hung11e74242023-06-26 19:20:57 -07008272 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008273 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008274 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008275 if (activeTrack->isFastTrack()) {
8276 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8277 // Keep a ref on fast track to wait for FastCapture thread to get updated
8278 // state before potential track removal
8279 fastTrackToRemove = activeTrack;
8280 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008281 doBroadcast = true;
8282 size--;
8283 continue;
8284
Andy Hung11e74242023-06-26 19:20:57 -07008285 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008286 sleepUs = 10000;
8287 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008288 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008289 continue;
8290
Andy Hung11e74242023-06-26 19:20:57 -07008291 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008292 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008293 if (mStandby) {
8294 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008295 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008296 mStandby = false;
8297 }
Andy Hung11e74242023-06-26 19:20:57 -07008298 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008299 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008300 break;
8301
Andy Hung11e74242023-06-26 19:20:57 -07008302 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008303 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008304 break;
8305
Andy Hung11e74242023-06-26 19:20:57 -07008306 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8307 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8308 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008309 default:
Andy Hungce685402018-10-05 17:23:27 -07008310 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8311 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008312 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008313
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008314 if (activeTrack->isFastTrack()) {
8315 ALOG_ASSERT(!mFastTrackAvail);
8316 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008317 // if the active fast track is silenced either:
8318 // 1) silence the whole capture from fast capture buffer if this is
8319 // the only active track
8320 // 2) invalidate this track: this will cause the client to reconnect and possibly
8321 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008322 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008323 if (activeTrack->isSilenced()) {
8324 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008325 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008326 } else {
8327 silenceFastCapture = true;
8328 }
8329 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008330 // Invalidate fast tracks if access to audio history is required as this is not
8331 // possible with fast tracks. Once the fast track has been invalidated, no new
8332 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8333 if (mMaxSharedAudioHistoryMs != 0) {
8334 invalidate = true;
8335 }
8336 if (invalidate) {
8337 activeTrack->invalidate();
8338 ALOG_ASSERT(fastTrackToRemove == 0);
8339 fastTrackToRemove = activeTrack;
8340 removeTrack_l(activeTrack);
8341 mActiveTracks.remove(activeTrack);
8342 size--;
8343 continue;
8344 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008345 fastTrack = activeTrack;
8346 }
Eric Laurent33403f02020-05-29 18:35:06 -07008347
8348 activeTracks.add(activeTrack);
8349 i++;
8350
Glenn Kasten9e982352013-08-14 14:39:50 -07008351 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008352
Andy Hung94dfbb42023-09-06 19:41:47 -07008353 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008354
Kevin Rocard069c2712018-03-29 19:09:14 -07008355 updateMetadata_l();
8356
Eric Laurent5c25d562016-07-13 17:17:45 -07008357 if (allStopped) {
8358 standbyIfNotAlreadyInStandby();
8359 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008360 if (doBroadcast) {
Andy Hungb17d24b2023-08-29 14:26:09 -07008361 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008362 }
8363
8364 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008365 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008366 if (sleepUs == 0) {
8367 sleepUs = kRecordThreadSleepUs;
8368 }
8369 continue;
8370 }
8371 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008372
Andy Hung1381a072023-10-20 16:41:18 -07008373 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008374 lockEffectChains_l(effectChains);
8375 }
8376
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008377 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008378
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008379 size_t size = effectChains.size();
8380 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008381 // thread mutex is not locked, but effect chain is locked
8382 effectChains[i]->process_l();
8383 }
8384
Glenn Kasten735f45f2014-08-18 15:51:59 -07008385 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008386 if (mFastCapture != 0) {
8387 FastCaptureStateQueue *sq = mFastCapture->sq();
8388 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008389 bool didModify = false;
8390 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008391 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8392 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8393 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8394 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8395 if (old == -1) {
8396 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8397 }
8398 }
8399 state->mCommand = FastCaptureState::READ_WRITE;
8400#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008401 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008402 FastThreadDumpState::kSamplingNforLowRamDevice :
8403 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008404#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008405 didModify = true;
8406 }
8407 audio_track_cblk_t *cblkOld = state->mCblk;
8408 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8409 if (cblkNew != cblkOld) {
8410 state->mCblk = cblkNew;
8411 // block until acked if removing a fast track
8412 if (cblkOld != NULL) {
8413 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8414 }
8415 didModify = true;
8416 }
jiabin01c8f562018-07-19 17:47:28 -07008417 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8418 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8419 if (state->mFastPatchRecordBufferProvider != abp) {
8420 state->mFastPatchRecordBufferProvider = abp;
8421 state->mFastPatchRecordFormat = fastTrack == 0 ?
8422 AUDIO_FORMAT_INVALID : fastTrack->format();
8423 didModify = true;
8424 }
Eric Laurent33403f02020-05-29 18:35:06 -07008425 if (state->mSilenceCapture != silenceFastCapture) {
8426 state->mSilenceCapture = silenceFastCapture;
8427 didModify = true;
8428 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008429 sq->end(didModify);
8430 if (didModify) {
8431 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008432#if 0
8433 if (kUseFastCapture == FastCapture_Dynamic) {
8434 mNormalSource = mPipeSource;
8435 }
8436#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008437 }
8438 }
8439
Glenn Kasten735f45f2014-08-18 15:51:59 -07008440 // now run the fast track destructor with thread mutex unlocked
8441 fastTrackToRemove.clear();
8442
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008443 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8444 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8445 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8446 // If destination is non-contiguous, first read past the nominal end of buffer, then
8447 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008448
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008449 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008450 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008451 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008452
8453 // If an NBAIO source is present, use it to read the normal capture's data
8454 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008455 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008456
8457 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8458 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8459 // we immediately retry the read() to get data and prevent another overflow.
8460 for (int retries = 0; retries <= 2; ++retries) {
8461 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8462 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8463 framesToRead);
8464 if (framesRead != OVERRUN) break;
8465 }
8466
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008467 const ssize_t availableToRead = mPipeSource->availableToRead();
8468 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008469 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008470 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008471 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8472 "more frames to read than fifo size, %zd > %zu",
8473 availableToRead, mPipeFramesP2);
8474 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8475 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8476 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8477 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008478 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8479 }
8480 if (framesRead < 0) {
8481 status_t status = (status_t) framesRead;
8482 switch (status) {
8483 case OVERRUN:
8484 ALOGW("overrun on read from pipe");
8485 framesRead = 0;
8486 break;
8487 case NEGOTIATE:
8488 ALOGE("re-negotiation is needed");
8489 framesRead = -1; // Will cause an attempt to recover.
8490 break;
8491 default:
8492 ALOGE("unknown error %d on read from pipe", status);
8493 break;
8494 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008495 }
8496 // otherwise use the HAL / AudioStreamIn directly
8497 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008498 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008499 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008500 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008501 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008502 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008503 if (result < 0) {
8504 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008505 } else {
8506 framesRead = bytesRead / mFrameSize;
8507 }
8508 }
8509
Andy Hung446f4df2019-02-21 12:26:41 -08008510 const int64_t lastIoEndNs = systemTime(); // end IO timing
8511
Andy Hung3f0c9022016-01-15 17:49:46 -08008512 // Update server timestamp with server stats
8513 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008514 if (framesRead >= 0) {
8515 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8516 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8517 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008518
8519 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008520 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008521 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008522 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008523 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8524 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8525 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008526 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008527 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8528
8529 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hung94dfbb42023-09-06 19:41:47 -07008530 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008531 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008532 id(), (long long)time, (long long)position);
8533 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8534 position = correctedTimestamp.mFrames;
8535 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008536 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008537 id(), (long long)time, (long long)position);
8538 }
8539
Andy Hung3f0c9022016-01-15 17:49:46 -08008540 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8541 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8542 // Note: In general record buffers should tend to be empty in
8543 // a properly running pipeline.
8544 //
8545 // Also, it is not advantageous to call get_presentation_position during the read
8546 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008547 } else {
8548 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008549 }
8550 }
Andy Hunge6c37112019-02-26 17:38:10 -08008551
8552 // From the timestamp, input read latency is negative output write latency.
8553 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008554 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008555 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8556 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8557 mLatencyMs.add(latencyMs);
8558 }
8559
Andy Hung3f0c9022016-01-15 17:49:46 -08008560 // Use this to track timestamp information
8561 // ALOGD("%s", mTimestamp.toString().c_str());
8562
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008563 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008564 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008565 // Force input into standby so that it tries to recover at next read attempt
8566 inputStandBy();
8567 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008568 }
8569 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008570 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008571 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008572 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008573 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008574
Andy Hung8946a282018-04-19 20:04:56 -07008575#ifdef TEE_SINK
8576 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8577#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008578 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008579 {
8580 size_t part1 = mRsmpInFramesP2 - rear;
8581 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008582 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008583 (framesRead - part1) * mFrameSize);
8584 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008585 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008586 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008587
8588 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008589
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008590 // loop over each active track
8591 for (size_t i = 0; i < size; i++) {
8592 activeTrack = activeTracks[i];
8593
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008594 // skip fast tracks, as those are handled directly by FastCapture
8595 if (activeTrack->isFastTrack()) {
8596 continue;
8597 }
8598
Andy Hung73c02e42015-03-29 01:13:58 -07008599 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008600 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8601
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008602 enum {
8603 OVERRUN_UNKNOWN,
8604 OVERRUN_TRUE,
8605 OVERRUN_FALSE
8606 } overrun = OVERRUN_UNKNOWN;
8607
8608 // loop over getNextBuffer to handle circular sink
8609 for (;;) {
8610
Andy Hung11e74242023-06-26 19:20:57 -07008611 activeTrack->sinkBuffer().frameCount = ~0;
8612 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8613 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008614 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8615
Andy Hung73c02e42015-03-29 01:13:58 -07008616 // check available frames and handle overrun conditions
8617 // if the record track isn't draining fast enough.
8618 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008619 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008620 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008621 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008622 overrun = OVERRUN_TRUE;
8623 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008624 if (framesOut == 0 || framesIn == 0) {
8625 break;
8626 }
8627
Andy Hung6770c6f2015-04-07 13:43:36 -07008628 // Don't allow framesOut to be larger than what is possible with resampling
8629 // from framesIn.
8630 // This isn't strictly necessary but helps limit buffer resizing in
8631 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008632 if (audio_is_linear_pcm(activeTrack->format())) {
8633 framesOut = min(framesOut,
8634 destinationFramesPossible(
8635 framesIn, mSampleRate, activeTrack->sampleRate()));
8636 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008637
8638 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008639 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008640 // straight from RecordThread buffer to RecordTrack buffer.
8641 AudioBufferProvider::Buffer buffer;
8642 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008643 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008644 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008645 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008646 ALOGV_IF(buffer.frameCount != framesOut,
8647 "%s() read less than expected (%zu vs %zu)",
8648 __func__, buffer.frameCount, framesOut);
8649 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008650 memcpy(activeTrack->sinkBuffer().raw,
8651 buffer.raw, buffer.frameCount * mFrameSize);
8652 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008653 } else {
8654 framesOut = 0;
8655 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008656 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008657 }
8658 } else {
8659 // process frames from the RecordThread buffer provider to the RecordTrack
8660 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008661 framesOut = activeTrack->recordBufferConverter()->convert(
8662 activeTrack->sinkBuffer().raw,
8663 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008664 framesOut);
8665 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008666
8667 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8668 overrun = OVERRUN_FALSE;
8669 }
8670
Andy Hung93bb5732023-05-04 21:16:34 -07008671 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8672 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008673 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008674 if (framesToDrop == 0) {
8675 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008676 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008677 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008678 // Sanitize before releasing if the track has no access to the source data
8679 // An idle UID receives silence from non virtual devices until active
8680 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008681 memset(activeTrack->sinkBuffer().raw,
8682 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008683 }
Andy Hung11e74242023-06-26 19:20:57 -07008684 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008685 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008686 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008687 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008688 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008689 }
8690 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008691
8692 switch (overrun) {
8693 case OVERRUN_TRUE:
8694 // client isn't retrieving buffers fast enough
8695 if (!activeTrack->setOverflow()) {
8696 nsecs_t now = systemTime();
8697 // FIXME should lastWarning per track?
8698 if ((now - lastWarning) > kWarningThrottleNs) {
8699 ALOGW("RecordThread: buffer overflow");
8700 lastWarning = now;
8701 }
8702 }
8703 break;
8704 case OVERRUN_FALSE:
8705 activeTrack->clearOverflow();
8706 break;
8707 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008708 break;
8709 }
8710
Andy Hung3f0c9022016-01-15 17:49:46 -08008711 // update frame information and push timestamp out
8712 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008713 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008714 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8715 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008716 }
8717
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008718unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008719 // enable changes in effect chain
8720 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008721 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008722 if (audio_has_proportional_frames(mFormat)
8723 && loopCount == lastLoopCountRead + 1) {
8724 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8725 const double jitterMs =
8726 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8727 {framesRead, readPeriodNs},
8728 {0, 0} /* lastTimestamp */, mSampleRate);
8729 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8730
Andy Hungf8635b62023-08-31 16:13:39 -07008731 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008732 mIoJitterMs.add(jitterMs);
8733 mProcessTimeMs.add(processMs);
8734 }
8735 // update timing info.
8736 mLastIoBeginNs = lastIoBeginNs;
8737 mLastIoEndNs = lastIoEndNs;
8738 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008739 }
8740
Glenn Kasten93e471f2013-08-19 08:40:07 -07008741 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008742
8743 {
Andy Hungf8635b62023-08-31 16:13:39 -07008744 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008745 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008746 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008747 track->invalidate();
8748 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008749 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008750 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008751 }
8752
8753 releaseWakeLock();
8754
8755 ALOGV("RecordThread %p exiting", this);
8756 return false;
8757}
8758
Andy Hung4b17e882023-07-07 13:47:37 -07008759void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008760{
8761 if (!mStandby) {
8762 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008763 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008764 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008765 mStandby = true;
8766 }
8767}
8768
Andy Hung4b17e882023-07-07 13:47:37 -07008769void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008770{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008771 // Idle the fast capture if it's currently running
8772 if (mFastCapture != 0) {
8773 FastCaptureStateQueue *sq = mFastCapture->sq();
8774 FastCaptureState *state = sq->begin();
8775 if (!(state->mCommand & FastCaptureState::IDLE)) {
8776 state->mCommand = FastCaptureState::COLD_IDLE;
8777 state->mColdFutexAddr = &mFastCaptureFutex;
8778 state->mColdGen++;
8779 mFastCaptureFutex = 0;
8780 sq->end();
8781 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8782 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8783#if 0
8784 if (kUseFastCapture == FastCapture_Dynamic) {
8785 // FIXME
8786 }
8787#endif
8788#ifdef AUDIO_WATCHDOG
8789 // FIXME
8790#endif
8791 } else {
8792 sq->end(false /*didModify*/);
8793 }
8794 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008795 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008796 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008797
8798 // If going into standby, flush the pipe source.
8799 if (mPipeSource.get() != nullptr) {
8800 const ssize_t flushed = mPipeSource->flush();
8801 if (flushed > 0) {
8802 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8803 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8804 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8805 }
8806 }
Eric Laurent81784c32012-11-19 14:55:58 -08008807}
8808
Andy Hungb17d24b2023-08-29 14:26:09 -07008809// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07008810sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008811 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008812 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008813 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008814 audio_format_t format,
8815 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008816 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008817 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008818 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008819 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008820 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008821 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008822 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008823 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008824 audio_port_handle_t portId,
8825 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008826{
Glenn Kasten74935e42013-12-19 08:56:45 -08008827 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008828 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008829 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008830 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008831 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008832 audio_input_flags_t requestedFlags = *flags;
8833 uint32_t sampleRate;
8834
8835 lStatus = initCheck();
8836 if (lStatus != NO_ERROR) {
8837 ALOGE("createRecordTrack_l() audio driver not initialized");
8838 goto Exit;
8839 }
8840
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008841 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8842 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8843 lStatus = BAD_VALUE;
8844 goto Exit;
8845 }
8846
Eric Laurentec376dc2021-04-08 20:41:22 +02008847 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008848 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008849 lStatus = PERMISSION_DENIED;
8850 goto Exit;
8851 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008852 if (maxSharedAudioHistoryMs < 0
Andy Hung409572b2023-07-19 12:47:35 -07008853 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008854 lStatus = BAD_VALUE;
8855 goto Exit;
8856 }
8857 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008858 if (*pSampleRate == 0) {
8859 *pSampleRate = mSampleRate;
8860 }
8861 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008862
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008863 // special case for FAST flag considered OK if fast capture is present and access to
8864 // audio history is not required
8865 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008866 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8867 }
8868
Eric Laurentf14db3c2017-12-08 14:20:36 -08008869 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008870 if ((*flags & inputFlags) != *flags) {
8871 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8872 " input flags (%08x)",
8873 *flags, inputFlags);
8874 *flags = (audio_input_flags_t)(*flags & inputFlags);
8875 }
Eric Laurent81784c32012-11-19 14:55:58 -08008876
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008877 // client expresses a preference for FAST and no access to audio history,
8878 // but we get the final say
8879 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008880 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008881 // we formerly checked for a callback handler (non-0 tid),
8882 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008883 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008884 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008885 // Frame count is not specified (0), or is less than or equal the pipe depth.
8886 // It is OK to provide a higher capacity than requested.
8887 // We will force it to mPipeFramesP2 below.
8888 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008889 // PCM data
8890 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008891 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008892 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008893 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008894 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008895 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008896 hasFastCapture() &&
8897 // there are sufficient fast track slots available
8898 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008899 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008900 // check compatibility with audio effects.
Andy Hungf8635b62023-08-31 16:13:39 -07008901 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008902 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008903 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008904 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008905 audio_input_flags_t old = *flags;
8906 chain->checkInputFlagCompatibility(flags);
8907 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008908 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8909 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008910 }
8911 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008912 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008913 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8914 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008915 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008916 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8917 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008918 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008919 this, frameCount, mFrameCount, mPipeFramesP2,
8920 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008921 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008922 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008923 }
8924 }
8925
Eric Laurentf14db3c2017-12-08 14:20:36 -08008926 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8927 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8928 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8929 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8930 lStatus = BAD_TYPE;
8931 goto Exit;
8932 }
8933
Glenn Kasten74105912014-07-03 12:28:53 -07008934 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008935 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008936 // fast track: frame count is exactly the pipe depth
8937 frameCount = mPipeFramesP2;
8938 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008939 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008940 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008941 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8942 // or 20 ms if there is a fast capture
8943 // TODO This could be a roundupRatio inline, and const
8944 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8945 * sampleRate + mSampleRate - 1) / mSampleRate;
8946 // minimum number of notification periods is at least kMinNotifications,
8947 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8948 static const size_t kMinNotifications = 3;
8949 static const uint32_t kMinMs = 30;
8950 // TODO This could be a roundupRatio inline
8951 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8952 // TODO This could be a roundupRatio inline
8953 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8954 maxNotificationFrames;
8955 const size_t minFrameCount = maxNotificationFrames *
8956 max(kMinNotifications, minNotificationsByMs);
8957 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008958 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8959 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008960 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008961 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008962 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008963 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008964
Andy Hungb17d24b2023-08-29 14:26:09 -07008965 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07008966 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008967 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008968 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008969 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008970 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008971 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008972 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008973 }
Eric Laurent81784c32012-11-19 14:55:58 -08008974
Andy Hung11e74242023-06-26 19:20:57 -07008975 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008976 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008977 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07008978 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008979 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008980
Glenn Kasten03003332013-08-06 15:40:54 -07008981 lStatus = track->initCheck();
8982 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008983 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008984 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008985 goto Exit;
8986 }
8987 mTracks.add(track);
8988
Eric Laurent05067782016-06-01 18:27:28 -07008989 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008990 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8991 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8992 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008993 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008994 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008995
8996 if (maxSharedAudioHistoryMs != 0) {
8997 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8998 }
Eric Laurent81784c32012-11-19 14:55:58 -08008999 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009000
Eric Laurent81784c32012-11-19 14:55:58 -08009001 lStatus = NO_ERROR;
9002
9003Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009004 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009005 return track;
9006}
9007
Andy Hung4b17e882023-07-07 13:47:37 -07009008status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009009 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009010 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009011{
9012 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9013 sp<ThreadBase> strongMe = this;
9014 status_t status = NO_ERROR;
9015
9016 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009017 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009018 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07009019 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07009020 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009021 event, triggerSession,
9022 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009023 }
9024
9025 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009026 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hungf8635b62023-08-31 16:13:39 -07009027 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009028 if (recordTrack->isInvalid()) {
9029 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009030 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9031 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009032 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009033 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07009034 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009035 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9036 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009037 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07009038 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009039 } else {
Andy Hung11e74242023-06-26 19:20:57 -07009040 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009041 }
9042 return status;
9043 }
9044
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009045 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9046 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9047 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07009048 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009049 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009050 if (recordTrack->isExternalTrack()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009051 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009052 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07009053 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009054 if (recordTrack->isInvalid()) {
9055 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07009056 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9057 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009058 // STARTING_2 forces destroy to call stopInput.
9059 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009060 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9061 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009062 }
Andy Hung11e74242023-06-26 19:20:57 -07009063 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009064 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07009065 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009066 // Someone else has changed state, let them take over,
9067 // leave mState in the new state.
9068 recordTrack->clearSyncStartEvent();
9069 return INVALID_OPERATION;
9070 }
9071 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009072 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009073 ALOGW("%s(%d): startInput failed, status %d",
9074 __func__, recordTrack->id(), status);
9075 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9076 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009077 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009078 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009079 return status;
9080 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009081 sendIoConfigEvent_l(
9082 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009083 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009084
9085 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9086
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009087 // Catch up with current buffer indices if thread is already running.
9088 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9089 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9090 // see previously buffered data before it called start(), but with greater risk of overrun.
9091
Andy Hung11e74242023-06-26 19:20:57 -07009092 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009093 if (!recordTrack->isDirect()) {
9094 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07009095 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009096 }
Andy Hung11e74242023-06-26 19:20:57 -07009097 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009098 // signal thread to start
Andy Hungb17d24b2023-08-29 14:26:09 -07009099 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009100 return status;
9101 }
Eric Laurent81784c32012-11-19 14:55:58 -08009102}
9103
Andy Hung4b17e882023-07-07 13:47:37 -07009104void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009105{
Andy Hung4b17e882023-07-07 13:47:37 -07009106 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009107
9108 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07009109 sp<IAfTrackBase> ptr =
9110 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9111 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07009112 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07009113 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009114 }
Eric Laurent81784c32012-11-19 14:55:58 -08009115 }
9116}
9117
Andy Hung4b17e882023-07-07 13:47:37 -07009118bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009119 ALOGV("RecordThread::stop");
Andy Hungb17d24b2023-08-29 14:26:09 -07009120 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009121 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07009122 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009123 return false;
9124 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009125 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07009126 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009127
Andy Hungabfab202019-03-07 19:45:54 -08009128 // NOTE: Waiting here is important to keep stop synchronous.
9129 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07009130 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009131 mWaitWorkCV.notify_all(); // signal thread to stop
9132 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009133 }
Andy Hungce685402018-10-05 17:23:27 -07009134
Andy Hung11e74242023-06-26 19:20:57 -07009135 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009136 ALOGV("Record stopped OK");
9137 return true;
9138 }
Andy Hungce685402018-10-05 17:23:27 -07009139
9140 // don't handle anything - we've been invalidated or restarted and in a different state
9141 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07009142 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009143 return false;
9144}
9145
Andy Hung4b17e882023-07-07 13:47:37 -07009146bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009147{
9148 return false;
9149}
9150
Andy Hung4b17e882023-07-07 13:47:37 -07009151status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009152{
9153#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9154 if (!isValidSyncEvent(event)) {
9155 return BAD_VALUE;
9156 }
9157
Glenn Kastend848eb42016-03-08 13:42:11 -08009158 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009159 status_t ret = NAME_NOT_FOUND;
9160
Andy Hungf8635b62023-08-31 16:13:39 -07009161 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009162
9163 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009164 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009165 if (eventSession == track->sessionId()) {
9166 (void) track->setSyncEvent(event);
9167 ret = NO_ERROR;
9168 }
9169 }
9170 return ret;
9171#else
9172 return BAD_VALUE;
9173#endif
9174}
9175
Andy Hung4b17e882023-07-07 13:47:37 -07009176status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07009177 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009178{
9179 ALOGV("RecordThread::getActiveMicrophones");
Andy Hungf8635b62023-08-31 16:13:39 -07009180 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009181 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009182 return NO_INIT;
9183 }
jiabin9ff780e2018-03-19 18:19:52 -07009184 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9185 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009186}
9187
Andy Hung4b17e882023-07-07 13:47:37 -07009188status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009189 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009190{
Paul McLean12340082019-03-19 09:35:05 -06009191 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hungf8635b62023-08-31 16:13:39 -07009192 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009193 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009194 return NO_INIT;
9195 }
Paul McLean12340082019-03-19 09:35:05 -06009196 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009197}
9198
Andy Hung4b17e882023-07-07 13:47:37 -07009199status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009200{
Paul McLean12340082019-03-19 09:35:05 -06009201 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hungf8635b62023-08-31 16:13:39 -07009202 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009203 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009204 return NO_INIT;
9205 }
Paul McLean12340082019-03-19 09:35:05 -06009206 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009207}
9208
Andy Hung4b17e882023-07-07 13:47:37 -07009209status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009210 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9211 int64_t sharedAudioStartMs) {
Andy Hungf8635b62023-08-31 16:13:39 -07009212 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009213 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9214}
9215
Andy Hung4b17e882023-07-07 13:47:37 -07009216status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009217 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9218 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009219
Eric Laurentec376dc2021-04-08 20:41:22 +02009220 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9221 return BAD_VALUE;
9222 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009223
9224 if (sharedAudioStartMs < 0
9225 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009226 return BAD_VALUE;
9227 }
9228
Eric Laurent2407ce32021-04-26 14:56:03 +02009229 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9230 // As we cannot detect more than one wraparound, only accept values up current write position
9231 // after one wraparound
9232 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9233 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009234 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009235 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9236 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009237 // Bring the start frame position within the input buffer to match the documented
9238 // "best effort" behavior of the API.
9239 if (sharedOffset < 0) {
9240 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009241 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009242 sharedAudioStartFrames =
9243 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009244 }
9245
Eric Laurentec376dc2021-04-08 20:41:22 +02009246 mSharedAudioPackageName = sharedAudioPackageName;
9247 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009248 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009249 } else {
9250 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009251 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009252 }
9253 return NO_ERROR;
9254}
9255
Andy Hung4b17e882023-07-07 13:47:37 -07009256void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009257 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9258 mSharedAudioStartFrames = -1;
9259 mSharedAudioPackageName = "";
9260}
9261
Andy Hung4b17e882023-07-07 13:47:37 -07009262ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009263{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009264 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009265 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009266 }
9267 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009268 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009269 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009270 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009271 }
9272 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009273 MetadataUpdate change;
9274 change.recordMetadataUpdate = metadata.tracks;
9275 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009276}
9277
Andy Hungb17d24b2023-08-29 14:26:09 -07009278// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07009279void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009280{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009281 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009282 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009283
Eric Laurent81784c32012-11-19 14:55:58 -08009284 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009285 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009286 removeTrack_l(track);
9287 }
9288}
9289
Andy Hung4b17e882023-07-07 13:47:37 -07009290void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009291{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009292 String8 result;
9293 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009294 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009295
Eric Laurent81784c32012-11-19 14:55:58 -08009296 mTracks.remove(track);
9297 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009298 if (track->isFastTrack()) {
9299 ALOG_ASSERT(!mFastTrackAvail);
9300 mFastTrackAvail = true;
9301 }
Eric Laurent81784c32012-11-19 14:55:58 -08009302}
9303
Andy Hung4b17e882023-07-07 13:47:37 -07009304void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009305{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009306 AudioStreamIn *input = mInput;
9307 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9308 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009309 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009310 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009311 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009312 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009313 }
Andy Hungbfa64962017-06-12 14:43:19 -07009314
9315 if (input != nullptr) {
9316 dprintf(fd, " Hal stream dump:\n");
9317 (void)input->stream->dump(fd);
9318 }
9319
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009320 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009321 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009322
Glenn Kasten2f90c512015-12-02 11:40:09 -08009323 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9324 // while we are dumping it. It may be inconsistent, but it won't mutate!
9325 // This is a large object so we place it on the heap.
9326 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009327 const std::unique_ptr<FastCaptureDumpState> copy =
9328 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009329 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009330}
9331
Andy Hung4b17e882023-07-07 13:47:37 -07009332void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009333{
Eric Laurent81784c32012-11-19 14:55:58 -08009334 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009335 size_t numtracks = mTracks.size();
9336 size_t numactive = mActiveTracks.size();
9337 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009338 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009339 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009340 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009341 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009342 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009343 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009344 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009345 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009346 if (track != 0) {
9347 bool active = mActiveTracks.indexOf(track) >= 0;
9348 if (active) {
9349 numactiveseen++;
9350 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009351 result.append(prefix);
9352 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009353 }
Eric Laurent81784c32012-11-19 14:55:58 -08009354 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009355 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009356 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009357 }
9358
Marco Nelissenb2208842014-02-07 14:00:50 -08009359 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009360 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009361 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009362 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009363 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009364 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009365 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009366 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009367 result.append(prefix);
9368 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009369 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009370 }
Eric Laurent81784c32012-11-19 14:55:58 -08009371
9372 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009373 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009374}
9375
Andy Hung4b17e882023-07-07 13:47:37 -07009376void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009377{
Andy Hungf8635b62023-08-31 16:13:39 -07009378 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009379 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009380 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009381 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009382 track->setSilenced(silenced);
9383 }
9384 }
9385}
Andy Hung73c02e42015-03-29 01:13:58 -07009386
Andy Hung11e74242023-06-26 19:20:57 -07009387void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009388{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009389 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009390 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009391 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009392 const int32_t rear = recordThread->mRsmpInRear;
9393 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009394 if (mRecordTrack->startFrames() >= 0) {
9395 int32_t startFrames = mRecordTrack->startFrames();
9396 // Accept a recent wraparound of mRsmpInRear
9397 if (startFrames <= rear) {
9398 deltaFrames = rear - startFrames;
9399 } else {
9400 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009401 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009402 // start frame cannot be further in the past than start of resampling buffer
9403 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9404 deltaFrames = recordThread->mRsmpInFrames;
9405 }
9406 }
9407 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009408}
9409
Andy Hung11e74242023-06-26 19:20:57 -07009410void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009411 size_t *framesAvailable, bool *hasOverrun)
9412{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009413 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009414 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009415 const int32_t rear = recordThread->mRsmpInRear;
9416 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009417 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009418
9419 size_t framesIn;
9420 bool overrun = false;
9421 if (filled < 0) {
9422 // should not happen, but treat like a massive overrun and re-sync
9423 framesIn = 0;
9424 mRsmpInFront = rear;
9425 overrun = true;
9426 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9427 framesIn = (size_t) filled;
9428 } else {
9429 // client is not keeping up with server, but give it latest data
9430 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009431 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9432 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009433 overrun = true;
9434 }
9435 if (framesAvailable != NULL) {
9436 *framesAvailable = framesIn;
9437 }
9438 if (hasOverrun != NULL) {
9439 *hasOverrun = overrun;
9440 }
9441}
9442
Eric Laurent81784c32012-11-19 14:55:58 -08009443// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009444status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009445 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009446{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009447 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009448 if (threadBase == 0) {
9449 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009450 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009451 return NOT_ENOUGH_DATA;
9452 }
Andy Hung4b17e882023-07-07 13:47:37 -07009453 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009454 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009455 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009456 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009457 // FIXME should not be P2 (don't want to increase latency)
9458 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009459 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009460 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009461
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009462 front &= recordThread->mRsmpInFramesP2 - 1;
9463 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009464 if (part1 > (size_t) filled) {
9465 part1 = filled;
9466 }
9467 size_t ask = buffer->frameCount;
9468 ALOG_ASSERT(ask > 0);
9469 if (part1 > ask) {
9470 part1 = ask;
9471 }
9472 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009473 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009474 buffer->raw = NULL;
9475 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009476 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009477 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009478 }
9479
Andy Hung57446612015-04-19 23:56:46 -07009480 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009481 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009482 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009483 return NO_ERROR;
9484}
9485
9486// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009487void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009488 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009489{
Hongwei Wang95e37682019-04-12 11:13:36 -07009490 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009491 if (stepCount == 0) {
9492 return;
9493 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009494 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009495 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009496 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009497 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009498 buffer->frameCount = 0;
9499}
9500
Andy Hung4b17e882023-07-07 13:47:37 -07009501void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009502{
Andy Hungf8635b62023-08-31 16:13:39 -07009503 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009504 checkBtNrec_l();
9505}
9506
Andy Hung4b17e882023-07-07 13:47:37 -07009507void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009508{
9509 // disable AEC and NS if the device is a BT SCO headset supporting those
9510 // pre processings
Andy Hung94dfbb42023-09-06 19:41:47 -07009511 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009512 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009513 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9514 for (size_t i = 0; i < mEffectChains.size(); i++) {
9515 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9516 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9517 }
9518 }
9519}
9520
Andy Hung97a893e2015-03-29 01:03:07 -07009521
Andy Hung4b17e882023-07-07 13:47:37 -07009522bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009523 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009524{
9525 bool reconfig = false;
9526
Eric Laurent10351942014-05-08 18:49:52 -07009527 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009528
Eric Laurent10351942014-05-08 18:49:52 -07009529 audio_format_t reqFormat = mFormat;
9530 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009531 // 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 +08009532 [[maybe_unused]] audio_channel_mask_t channelMask =
9533 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009534
9535 AudioParameter param = AudioParameter(keyValuePair);
9536 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009537
9538 // scope for AutoPark extends to end of method
9539 AutoPark<FastCapture> park(mFastCapture);
9540
Eric Laurent10351942014-05-08 18:49:52 -07009541 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9542 // channel count change can be requested. Do we mandate the first client defines the
9543 // HAL sampling rate and channel count or do we allow changes on the fly?
9544 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9545 samplingRate = value;
9546 reconfig = true;
9547 }
9548 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009549 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009550 status = BAD_VALUE;
9551 } else {
9552 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009553 reconfig = true;
9554 }
Eric Laurent10351942014-05-08 18:49:52 -07009555 }
9556 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9557 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009558 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009559 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009560 status = BAD_VALUE;
9561 } else {
9562 channelMask = mask;
9563 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009564 }
Eric Laurent10351942014-05-08 18:49:52 -07009565 }
9566 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9567 // do not accept frame count changes if tracks are open as the track buffer
9568 // size depends on frame count and correct behavior would not be guaranteed
9569 // if frame count is changed after track creation
9570 if (mActiveTracks.size() > 0) {
9571 status = INVALID_OPERATION;
9572 } else {
9573 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009574 }
Eric Laurent10351942014-05-08 18:49:52 -07009575 }
9576 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009577 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009578 }
9579 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9580 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009581 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009582 }
Glenn Kastene198c362013-08-13 09:13:36 -07009583
Eric Laurent10351942014-05-08 18:49:52 -07009584 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009585 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009586 if (status == INVALID_OPERATION) {
9587 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009588 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009589 }
9590 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009591 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009592 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9593 if (mInput->stream->getAudioProperties(&config) == OK &&
9594 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9595 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009596 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009597 status = NO_ERROR;
9598 }
Eric Laurent81784c32012-11-19 14:55:58 -08009599 }
Eric Laurent10351942014-05-08 18:49:52 -07009600 if (status == NO_ERROR) {
9601 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009602 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009603 }
9604 }
Eric Laurent81784c32012-11-19 14:55:58 -08009605 }
Eric Laurent10351942014-05-08 18:49:52 -07009606
Eric Laurent81784c32012-11-19 14:55:58 -08009607 return reconfig;
9608}
9609
Andy Hung4b17e882023-07-07 13:47:37 -07009610String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009611{
Andy Hungf8635b62023-08-31 16:13:39 -07009612 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009613 if (initCheck() == NO_ERROR) {
9614 String8 out_s8;
9615 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9616 return out_s8;
9617 }
Eric Laurent81784c32012-11-19 14:55:58 -08009618 }
Andy Hung920f6572022-10-06 12:09:49 -07009619 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009620}
9621
Andy Hung94dfbb42023-09-06 19:41:47 -07009622void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009623 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009624 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009625 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009626 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009627 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009628 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009629 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9630 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009631 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009632 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009633 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009634 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009635 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009636 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009637 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009638 break;
9639 }
Andy Hung94dfbb42023-09-06 19:41:47 -07009640 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009641}
9642
Andy Hung4b17e882023-07-07 13:47:37 -07009643void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009644{
Dean Wheatley6c009512023-10-23 09:34:14 +11009645 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9646 mSampleRate = audioConfig.sample_rate;
9647 mChannelMask = audioConfig.channel_mask;
9648 if (!audio_is_input_channel(mChannelMask)) {
9649 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9650 }
9651
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009652 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009653
9654 // Get actual HAL format.
9655 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9656 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9657 // Get format from the shim, which will be different than the HAL format
9658 // if recording compressed audio from IEC61937 wrapped sources.
9659 mFormat = audioConfig.format;
9660 if (!audio_is_valid_format(mFormat)) {
9661 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9662 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009663 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009664 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9665 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009666 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009667 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009668 ALOGI("HAL format %#x is not linear pcm", mFormat);
9669 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009670 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009671 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9672 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009673 result = mInput->stream->getBufferSize(&mBufferSize);
9674 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009675 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009676 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9677 "mBufferSize=%zu, mFrameCount=%zu",
9678 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009679
Eric Laurentec376dc2021-04-08 20:41:22 +02009680 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9681 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009682 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009683
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009684 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9685 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009686
9687 audio_input_flags_t flags = mInput->flags;
9688 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9689 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07009690 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009691 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9692 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9693 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9694 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9695 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9696 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009697}
9698
Andy Hung4b17e882023-07-07 13:47:37 -07009699uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009700{
Andy Hungf8635b62023-08-31 16:13:39 -07009701 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009702 uint32_t result;
9703 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9704 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009705 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009706 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009707}
9708
Andy Hung4b17e882023-07-07 13:47:37 -07009709KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009710{
Glenn Kastend848eb42016-03-08 13:42:11 -08009711 KeyedVector<audio_session_t, bool> ids;
Andy Hungf8635b62023-08-31 16:13:39 -07009712 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009713 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009714 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009715 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009716 if (ids.indexOfKey(sessionId) < 0) {
9717 ids.add(sessionId, true);
9718 }
9719 }
9720 return ids;
9721}
9722
Andy Hung4b17e882023-07-07 13:47:37 -07009723AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009724{
Andy Hungf8635b62023-08-31 16:13:39 -07009725 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009726 AudioStreamIn *input = mInput;
9727 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009728 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009729 return input;
9730}
9731
Andy Hungb17d24b2023-08-29 14:26:09 -07009732// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009733sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009734{
9735 if (mInput == NULL) {
9736 return NULL;
9737 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009738 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009739}
9740
Andy Hung4b17e882023-07-07 13:47:37 -07009741status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009742{
Eric Laurent81784c32012-11-19 14:55:58 -08009743 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009744 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009745 chain->setInBuffer(NULL);
9746 chain->setOutBuffer(NULL);
9747
9748 checkSuspendOnAddEffectChain_l(chain);
9749
Eric Laurent1b928682014-10-02 19:41:47 -07009750 // make sure enabled pre processing effects state is communicated to the HAL as we
9751 // just moved them to a new input stream.
9752 chain->syncHalEffectsState();
9753
Eric Laurent81784c32012-11-19 14:55:58 -08009754 mEffectChains.add(chain);
9755
9756 return NO_ERROR;
9757}
9758
Andy Hung4b17e882023-07-07 13:47:37 -07009759size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009760{
9761 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009762
9763 for (size_t i = 0; i < mEffectChains.size(); i++) {
9764 if (chain == mEffectChains[i]) {
9765 mEffectChains.removeAt(i);
9766 break;
9767 }
Eric Laurent81784c32012-11-19 14:55:58 -08009768 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009769 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009770}
9771
Andy Hung4b17e882023-07-07 13:47:37 -07009772status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009773 audio_patch_handle_t *handle)
9774{
9775 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009776
9777 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009778 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009779 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009780 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009781 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009782 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009783 }
9784
Eric Laurentd8365c52017-07-16 15:27:05 -07009785 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009786
9787 // store new source and send to effects
9788 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9789 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009790 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009791 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009792 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009793 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009794
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009795 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009796 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9797 status = hwDevice->createAudioPatch(patch->num_sources,
9798 patch->sources,
9799 patch->num_sinks,
9800 patch->sinks,
9801 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009802 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009803 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9804 patch->sinks[0].ext.mix.usecase.source,
9805 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009806 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009807 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009808
jiabinc52b1ff2019-10-31 17:20:42 -07009809 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009810 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009811 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009812 }
Eric Laurent296fb132015-05-01 11:38:42 -07009813
Andy Hungc2b11cb2020-04-22 09:04:01 -07009814 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009815 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009816 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009817 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009818 // also dispatch to active AudioRecords
9819 for (const auto &track : mActiveTracks) {
9820 track->logEndInterval();
9821 track->logBeginInterval(pathSourcesAsString);
9822 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009823 // Force meteadata update after a route change
9824 mActiveTracks.setHasChanged();
9825
Eric Laurent1c333e22014-05-20 10:48:17 -07009826 return status;
9827}
9828
Andy Hung4b17e882023-07-07 13:47:37 -07009829status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009830{
9831 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009832
jiabinc52b1ff2019-10-31 17:20:42 -07009833 mPatch = audio_patch{};
9834 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009835
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009836 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009837 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9838 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009839 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009840 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009841 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009842 // Force meteadata update after a route change
9843 mActiveTracks.setHasChanged();
9844
Eric Laurent1c333e22014-05-20 10:48:17 -07009845 return status;
9846}
9847
Andy Hung4b17e882023-07-07 13:47:37 -07009848void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009849{
Andy Hungf8635b62023-08-31 16:13:39 -07009850 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009851 mOutDevices = outDevices;
9852 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9853 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009854 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009855 }
9856}
9857
Andy Hung4b17e882023-07-07 13:47:37 -07009858int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009859{
9860 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009861 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009862 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009863 int32_t oldestFront = mRsmpInRear;
9864 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009865 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009866 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009867 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009868 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009869 if (filled > maxFilled) {
9870 oldestFront = front;
9871 maxFilled = filled;
9872 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009873 }
Andy Hung920f6572022-10-06 12:09:49 -07009874 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009875 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9876 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009877 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009878}
9879
Andy Hung4b17e882023-07-07 13:47:37 -07009880void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009881{
9882 if (offset == 0) {
9883 return;
9884 }
9885 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009886 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009887 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009888 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009889 }
9890}
9891
Andy Hung4b17e882023-07-07 13:47:37 -07009892void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009893{
9894 // This is the formula for calculating the temporary buffer size.
9895 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9896 // 1 full output buffer, regardless of the alignment of the available input.
9897 // The value is somewhat arbitrary, and could probably be even larger.
9898 // A larger value should allow more old data to be read after a track calls start(),
9899 // without increasing latency.
9900 //
9901 // Note this is independent of the maximum downsampling ratio permitted for capture.
9902 size_t minRsmpInFrames = mFrameCount * 7;
9903
9904 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9905 // capture history available to another client using the same session ID:
9906 // dimension the resampler input buffer accordingly.
9907
9908 // Get oldest client read position: getOldestFront_l() must be called before altering
9909 // mRsmpInRear, or mRsmpInFrames
9910 int32_t previousFront = getOldestFront_l();
9911 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9912 int32_t previousRear = mRsmpInRear;
9913 mRsmpInRear = 0;
9914
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009915 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009916 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009917 "resizeInputBuffer_l() called with invalid max shared history %d",
9918 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009919 if (maxSharedAudioHistoryMs != 0) {
9920 // resizeInputBuffer_l should never be called with a non zero shared history if the
9921 // buffer was not already allocated
9922 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9923 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9924 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9925 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009926 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009927 return;
9928 }
9929 mRsmpInFrames = rsmpInFrames;
9930 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009931 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009932 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9933 // initialized
9934 if (mRsmpInFrames < minRsmpInFrames) {
9935 mRsmpInFrames = minRsmpInFrames;
9936 }
9937 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9938
9939 // TODO optimize audio capture buffer sizes ...
9940 // Here we calculate the size of the sliding buffer used as a source
9941 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9942 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9943 // be better to have it derived from the pipe depth in the long term.
9944 // The current value is higher than necessary. However it should not add to latency.
9945
9946 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9947 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9948
9949 void *rsmpInBuffer;
9950 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9951 // if posix_memalign fails, will segv here.
9952 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9953
9954 // Copy audio history if any from old buffer before freeing it
9955 if (previousRear != 0) {
9956 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9957 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9958
9959 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9960 previousFront &= previousRsmpInFramesP2 - 1;
9961 size_t part1 = previousRsmpInFramesP2 - previousFront;
9962 if (part1 > (size_t) unread) {
9963 part1 = unread;
9964 }
9965 if (part1 != 0) {
9966 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9967 part1 * mFrameSize);
9968 mRsmpInRear = part1;
9969 part1 = unread - part1;
9970 if (part1 != 0) {
9971 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9972 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9973 mRsmpInRear += part1;
9974 }
9975 }
9976 // Update front for all clients according to new rear
9977 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9978 } else {
9979 mRsmpInRear = 0;
9980 }
9981 free(mRsmpInBuffer);
9982 mRsmpInBuffer = rsmpInBuffer;
9983}
9984
Andy Hung4b17e882023-07-07 13:47:37 -07009985void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009986{
Andy Hungf8635b62023-08-31 16:13:39 -07009987 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009988 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009989 if (record->getSource()) {
9990 mSource = record->getSource();
9991 }
Eric Laurent83b88082014-06-20 18:31:16 -07009992}
9993
Andy Hung4b17e882023-07-07 13:47:37 -07009994void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009995{
Andy Hungf8635b62023-08-31 16:13:39 -07009996 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009997 if (mSource == record->getSource()) {
9998 mSource = mInput;
9999 }
Eric Laurent83b88082014-06-20 18:31:16 -070010000 destroyTrack_l(record);
10001}
10002
Andy Hung4b17e882023-07-07 13:47:37 -070010003void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010004{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010005 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010006 config->role = AUDIO_PORT_ROLE_SINK;
10007 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10008 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010009 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10010 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10011 config->flags.input = mInput->flags;
10012 }
Eric Laurent83b88082014-06-20 18:31:16 -070010013}
Eric Laurent1c333e22014-05-20 10:48:17 -070010014
Eric Laurent6acd1d42017-01-04 14:23:29 -080010015// ----------------------------------------------------------------------------
10016// Mmap
10017// ----------------------------------------------------------------------------
10018
Andy Hung765de282023-07-07 15:58:48 -070010019// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10020// MmapPlaybackThread or MmapCaptureThread instance.
10021class MmapThreadHandle : public MmapStreamInterface {
10022public:
10023 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10024 ~MmapThreadHandle() override;
10025
10026 // MmapStreamInterface virtuals
10027 status_t createMmapBuffer(int32_t minSizeFrames,
10028 struct audio_mmap_buffer_info* info) final;
10029 status_t getMmapPosition(struct audio_mmap_position* position) final;
10030 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10031 status_t start(const AudioClient& client,
10032 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10033 status_t stop(audio_port_handle_t handle) final;
10034 status_t standby() final;
10035 status_t reportData(const void* buffer, size_t frameCount) final;
10036private:
10037 const sp<IAfMmapThread> mThread;
10038};
10039
10040/* static */
10041sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10042 const sp<IAfMmapThread>& mmapThread) {
10043 return sp<MmapThreadHandle>::make(mmapThread);
10044}
10045
10046MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010047 : mThread(thread)
10048{
Phil Burk9fabbf82017-08-03 12:02:00 -070010049 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050}
10051
Andy Hung765de282023-07-07 15:58:48 -070010052// MmapStreamInterface could be directly implemented by MmapThread excepting this
10053// special handling on adapter dtor.
10054MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055{
Phil Burk9fabbf82017-08-03 12:02:00 -070010056 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010057}
10058
Andy Hung765de282023-07-07 15:58:48 -070010059status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060 struct audio_mmap_buffer_info *info)
10061{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010062 return mThread->createMmapBuffer(minSizeFrames, info);
10063}
10064
Andy Hung765de282023-07-07 15:58:48 -070010065status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010066{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010067 return mThread->getMmapPosition(position);
10068}
10069
Andy Hung765de282023-07-07 15:58:48 -070010070status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010071 int64_t *timeNanos) {
10072 return mThread->getExternalPosition(position, timeNanos);
10073}
10074
Andy Hung765de282023-07-07 15:58:48 -070010075status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010076 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010077{
jiabind1f1cb62020-03-24 11:57:57 -070010078 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010079}
10080
Andy Hung765de282023-07-07 15:58:48 -070010081status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010082{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010083 return mThread->stop(handle);
10084}
10085
Andy Hung765de282023-07-07 15:58:48 -070010086status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010087{
Eric Laurent18b57012017-02-13 16:23:52 -080010088 return mThread->standby();
10089}
10090
Andy Hung765de282023-07-07 15:58:48 -070010091status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10092{
jiabinfc791ee2023-02-15 19:43:40 +000010093 return mThread->reportData(buffer, frameCount);
10094}
10095
Eric Laurent6acd1d42017-01-04 14:23:29 -080010096
Andy Hung4b17e882023-07-07 13:47:37 -070010097MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010098 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010099 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -070010100 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010101 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010102 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010103 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010104 mActiveTracks(&this->mLocalLog),
10105 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10106 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107{
Eric Laurent18b57012017-02-13 16:23:52 -080010108 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010109 readHalParameters_l();
10110}
10111
Andy Hung4b17e882023-07-07 13:47:37 -070010112void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010113{
10114 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10115}
10116
Andy Hung4b17e882023-07-07 13:47:37 -070010117void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010118{
Andy Hung11e74242023-06-26 19:20:57 -070010119 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010120 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010121 {
Andy Hungf8635b62023-08-31 16:13:39 -070010122 audio_utils::lock_guard _l(mutex());
Andy Hung11e74242023-06-26 19:20:57 -070010123 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010124 activeTracks.add(t);
10125 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010126 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010127 }
Andy Hung11e74242023-06-26 19:20:57 -070010128 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129 stop(t->portId());
10130 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010131 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010132 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010133 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010134 } else {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010135 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010136 }
10137}
10138
10139
Andy Hung160664b2023-09-15 18:19:28 -070010140void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141 audio_stream_type_t streamType __unused,
10142 audio_session_t sessionId,
10143 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010144 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010145 audio_port_handle_t portId)
10146{
10147 mAttr = *attr;
10148 mSessionId = sessionId;
10149 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010150 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010151 mPortId = portId;
10152}
10153
Andy Hung4b17e882023-07-07 13:47:37 -070010154status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010155 struct audio_mmap_buffer_info *info)
10156{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010157 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010158 if (mHalStream == 0) {
10159 return NO_INIT;
10160 }
Eric Laurent18b57012017-02-13 16:23:52 -080010161 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010162 return mHalStream->createMmapBuffer(minSizeFrames, info);
10163}
10164
Andy Hung4b17e882023-07-07 13:47:37 -070010165status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010166{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010167 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010168 if (mHalStream == 0) {
10169 return NO_INIT;
10170 }
10171 return mHalStream->getMmapPosition(position);
10172}
10173
Andy Hung4b17e882023-07-07 13:47:37 -070010174status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010175{
Eric Laurentdda206a2022-07-08 17:28:35 +020010176 // The HAL must receive track metadata before starting the stream
10177 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010178 status_t ret = mHalStream->start();
10179 if (ret != NO_ERROR) {
10180 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10181 return ret;
10182 }
Andy Hungcf10d742020-04-28 15:38:24 -070010183 if (mStandby) {
10184 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010185 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010186 mStandby = false;
10187 }
Eric Laurent331679c2018-04-16 17:03:16 -070010188 return NO_ERROR;
10189}
10190
Andy Hung4b17e882023-07-07 13:47:37 -070010191status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010192 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010193 audio_port_handle_t *handle)
10194{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010195 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010196 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010197 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010198 if (mHalStream == 0) {
10199 return NO_INIT;
10200 }
10201
10202 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010203
Eric Laurentdda206a2022-07-08 17:28:35 +020010204 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010205 if (*handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010206 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010207 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010208 }
10209
10210 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10211
10212 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010213 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010214 client.attributionSource);
10215
Andy Hungbcfd9e12023-09-19 14:48:41 -070010216 const auto localSessionId = mSessionId;
10217 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010218 if (isOutput()) {
10219 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10220 config.sample_rate = mSampleRate;
10221 config.channel_mask = mChannelMask;
10222 config.format = mFormat;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010223 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010224 audio_output_flags_t flags =
10225 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010226 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010227 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010228 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010229 bool isBitPerfect;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010230 mutex().unlock();
10231 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10232 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010233 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010234 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010235 &config,
10236 flags,
10237 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010238 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010239 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010240 &isSpatialized,
10241 &isBitPerfect);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010242 mutex().lock();
10243 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010244 ALOGD_IF(!secondaryOutputs.empty(),
10245 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010247 audio_config_base_t config;
10248 config.sample_rate = mSampleRate;
10249 config.channel_mask = mChannelMask;
10250 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010251 audio_port_handle_t deviceId = mDeviceId;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010252 mutex().unlock();
10253 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010254 RECORD_RIID_INVALID,
Andy Hungbcfd9e12023-09-19 14:48:41 -070010255 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010256 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010257 &config,
10258 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10259 &deviceId,
10260 &portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010261 mutex().lock();
10262 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010263 }
10264 // APM should not chose a different input or output stream for the same set of attributes
10265 // and audo configuration
10266 if (ret != NO_ERROR || io != mId) {
10267 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10268 __FUNCTION__, ret, io, mId);
10269 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010270 }
10271
10272 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010273 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010274 ret = AudioSystem::startOutput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010275 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276 } else {
jiabin09609032022-06-15 19:26:01 +000010277 {
10278 // Add the track record before starting input so that the silent status for the
10279 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010280 setClientSilencedState_l(portId, false /*silenced*/);
10281 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010282 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010283 ret = AudioSystem::startInput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010284 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285 }
10286
10287 // abort if start is rejected by audio policy manager
10288 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010289 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010290 if (!mActiveTracks.isEmpty()) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010291 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010293 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010295 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010296 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010297 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010298 } else {
10299 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010300 }
jiabin09609032022-06-15 19:26:01 +000010301 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010302 return PERMISSION_DENIED;
10303 }
10304
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010305 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010306 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10307 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010308 mChannelMask, mSessionId, isOutput(),
10309 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010310 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010311 if (!isOutput()) {
10312 track->setSilenced_l(isClientSilenced_l(portId));
10313 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314
Eric Laurent4eb58f12018-12-07 16:41:02 -080010315 if (isOutput()) {
10316 // force volume update when a new track is added
10317 mHalVolFloat = -1.0f;
10318 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010319 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010320 if (t->isSilenced_l()
10321 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010322 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010323 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010324 }
10325 }
10326
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010328 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329 if (chain != 0) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010330 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010331 chain->incTrackCnt();
10332 chain->incActiveTrackCnt();
10333 }
10334
Andy Hungc2b11cb2020-04-22 09:04:01 -070010335 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010336 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010337
10338 if (mActiveTracks.size() == 1) {
10339 ret = exitStandby_l();
10340 }
10341
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342 broadcast_l();
10343
Eric Laurentdda206a2022-07-08 17:28:35 +020010344 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010345
Eric Laurentdda206a2022-07-08 17:28:35 +020010346 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010347}
10348
Andy Hung4b17e882023-07-07 13:47:37 -070010349status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010351 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010352 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353
10354 if (mHalStream == 0) {
10355 return NO_INIT;
10356 }
10357
Eric Laurenta54f1282017-07-01 19:39:32 -070010358 if (handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010359 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010360 return NO_ERROR;
10361 }
10362
Andy Hung11e74242023-06-26 19:20:57 -070010363 sp<IAfMmapTrack> track;
10364 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365 if (handle == t->portId()) {
10366 track = t;
10367 break;
10368 }
10369 }
10370 if (track == 0) {
10371 return BAD_VALUE;
10372 }
10373
10374 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010375 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376
Andy Hungb17d24b2023-08-29 14:26:09 -070010377 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010378 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010379 AudioSystem::stopOutput(track->portId());
10380 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010382 AudioSystem::stopInput(track->portId());
10383 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010384 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010385 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010386
Andy Hung116bc262023-06-20 18:56:17 -070010387 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388 if (chain != 0) {
10389 chain->decActiveTrackCnt();
10390 chain->decTrackCnt();
10391 }
10392
Eric Laurentdda206a2022-07-08 17:28:35 +020010393 if (mActiveTracks.isEmpty()) {
10394 mHalStream->stop();
10395 }
10396
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397 broadcast_l();
10398
Eric Laurent6acd1d42017-01-04 14:23:29 -080010399 return NO_ERROR;
10400}
10401
Andy Hung4b17e882023-07-07 13:47:37 -070010402status_t MmapThread::standby()
Andy Hungbcfd9e12023-09-19 14:48:41 -070010403NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010404{
10405 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010406 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010407
10408 if (mHalStream == 0) {
10409 return NO_INIT;
10410 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010411 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010412 return INVALID_OPERATION;
10413 }
10414 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010415 if (!mStandby) {
10416 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010417 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010418 mStandby = true;
10419 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010420 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010421 return NO_ERROR;
10422}
10423
Andy Hung4b17e882023-07-07 13:47:37 -070010424status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010425 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10426 return INVALID_OPERATION;
10427}
10428
Andy Hung4b17e882023-07-07 13:47:37 -070010429void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010430{
10431 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10432 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10433 mFormat = mHALFormat;
10434 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10435 result = mHalStream->getFrameSize(&mFrameSize);
10436 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010437 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10438 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439 result = mHalStream->getBufferSize(&mBufferSize);
10440 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10441 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010442
Andy Hungcf10d742020-04-28 15:38:24 -070010443 // TODO: make a readHalParameters call?
10444 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010445 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -070010446 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010447 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10448 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10449 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10450 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10451 /*
10452 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10453 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10454 (int32_t)mHapticChannelMask)
10455 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10456 (int32_t)mHapticChannelCount)
10457 */
10458 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -070010459 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010460 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10461 (int32_t)mFrameCount) // sic - added HAL
10462 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010463}
10464
Andy Hung4b17e882023-07-07 13:47:37 -070010465bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010466{
Andy Hung94dfbb42023-09-06 19:41:47 -070010467 {
10468 audio_utils::unique_lock _l(mutex());
10469 checkSilentMode_l();
10470 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010471
10472 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10473
10474 while (!exitPending())
10475 {
Andy Hung116bc262023-06-20 18:56:17 -070010476 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010477
Andy Hung13850be2019-03-14 11:33:09 -070010478 { // under Thread lock
Andy Hungb17d24b2023-08-29 14:26:09 -070010479 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010480
Eric Laurent6acd1d42017-01-04 14:23:29 -080010481 if (mSignalPending) {
10482 // A signal was raised while we were unlocked
10483 mSignalPending = false;
10484 } else {
10485 if (mConfigEvents.isEmpty()) {
10486 // we're about to wait, flush the binder command buffer
10487 IPCThreadState::self()->flushCommands();
10488
10489 if (exitPending()) {
10490 break;
10491 }
10492
Eric Laurent6acd1d42017-01-04 14:23:29 -080010493 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010494 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -070010495 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010496 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497
10498 checkSilentMode_l();
10499
10500 continue;
10501 }
10502 }
10503
10504 processConfigEvents_l();
10505
10506 processVolume_l();
10507
10508 checkInvalidTracks_l();
10509
Andy Hung94dfbb42023-09-06 19:41:47 -070010510 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010511
Kevin Rocard069c2712018-03-29 19:09:14 -070010512 updateMetadata_l();
10513
Eric Laurent6acd1d42017-01-04 14:23:29 -080010514 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010515 } // release Thread lock
10516
Eric Laurent6acd1d42017-01-04 14:23:29 -080010517 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010518 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010519 }
Andy Hung13850be2019-03-14 11:33:09 -070010520
10521 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010522 unlockEffectChains(effectChains);
10523 // Effect chains will be actually deleted here if they were removed from
10524 // mEffectChains list during mixing or effects processing
10525 }
10526
10527 threadLoop_exit();
10528
10529 if (!mStandby) {
10530 threadLoop_standby();
10531 mStandby = true;
10532 }
10533
Eric Laurent6acd1d42017-01-04 14:23:29 -080010534 ALOGV("Thread %p type %d exiting", this, mType);
10535 return false;
10536}
10537
Andy Hungb17d24b2023-08-29 14:26:09 -070010538// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070010539bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010540 status_t& status)
10541{
10542 AudioParameter param = AudioParameter(keyValuePair);
10543 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010544 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010546 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010548 if (sendToHal) {
10549 status = mHalStream->setParameters(keyValuePair);
10550 } else {
10551 status = NO_ERROR;
10552 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553
10554 return false;
10555}
10556
Andy Hung4b17e882023-07-07 13:47:37 -070010557String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558{
Andy Hungf8635b62023-08-31 16:13:39 -070010559 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560 String8 out_s8;
10561 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10562 return out_s8;
10563 }
Andy Hung920f6572022-10-06 12:09:49 -070010564 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565}
10566
Andy Hung94dfbb42023-09-06 19:41:47 -070010567void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010568 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010569 sp<AudioIoDescriptor> desc;
10570 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010571 switch (event) {
10572 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010573 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010574 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010575 isInput = true;
10576 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010578 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010579 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010580 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10581 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010583 case AUDIO_INPUT_CLOSED:
10584 case AUDIO_OUTPUT_CLOSED:
10585 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010586 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010587 break;
10588 }
Andy Hung94dfbb42023-09-06 19:41:47 -070010589 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010590}
10591
Andy Hung4b17e882023-07-07 13:47:37 -070010592status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010593 audio_patch_handle_t *handle)
Andy Hungb17d24b2023-08-29 14:26:09 -070010594NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010595{
10596 status_t status = NO_ERROR;
10597
10598 // store new device and send to effects
10599 audio_devices_t type = AUDIO_DEVICE_NONE;
10600 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010601 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10602 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10603 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010604 if (isOutput()) {
10605 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010606 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10607 && !mAudioHwDev->supportsAudioPatches(),
10608 "Enumerated device type(%#x) must not be used "
10609 "as it does not support audio patches",
10610 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010611 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010612 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10613 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010614 }
10615 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010616 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010617 } else {
10618 type = patch->sources[0].ext.device.type;
10619 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010620 numDevices = mPatch.num_sources;
10621 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010622 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010623 }
10624
10625 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010626 if (isOutput()) {
10627 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10628 } else {
10629 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10630 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010631 }
10632
jiabinc52b1ff2019-10-31 17:20:42 -070010633 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634 // store new source and send to effects
10635 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10636 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10637 for (size_t i = 0; i < mEffectChains.size(); i++) {
10638 mEffectChains[i]->setAudioSource_l(mAudioSource);
10639 }
10640 }
10641 }
10642
10643 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010644 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10645 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010646 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010647 audio_port_config port;
10648 std::optional<audio_source_t> source;
10649 if (isOutput()) {
10650 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010651 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010652 port = patch->sources[0];
10653 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010655 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010656 *handle = AUDIO_PATCH_HANDLE_NONE;
10657 }
10658
jiabinc52b1ff2019-10-31 17:20:42 -070010659 if (numDevices == 0 || mDeviceId != deviceId) {
10660 if (isOutput()) {
10661 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10662 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010663 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010664 } else {
10665 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10666 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10667 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010668 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010669 if (mDeviceId != deviceId && callback != 0) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010670 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010671 callback->onRoutingChanged(deviceId);
Andy Hungb17d24b2023-08-29 14:26:09 -070010672 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010673 }
jiabinc52b1ff2019-10-31 17:20:42 -070010674 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010675 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010676 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010677 // Force meteadata update after a route change
10678 mActiveTracks.setHasChanged();
10679
Eric Laurent6acd1d42017-01-04 14:23:29 -080010680 return status;
10681}
10682
Andy Hung4b17e882023-07-07 13:47:37 -070010683status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010684{
10685 status_t status = NO_ERROR;
10686
jiabinc52b1ff2019-10-31 17:20:42 -070010687 mPatch = audio_patch{};
10688 mOutDeviceTypeAddrs.clear();
10689 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010690
10691 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10692 supportsAudioPatches : false;
10693
10694 if (supportsAudioPatches) {
10695 status = mHalDevice->releaseAudioPatch(handle);
10696 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010697 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010698 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010699 // Force meteadata update after a route change
10700 mActiveTracks.setHasChanged();
10701
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702 return status;
10703}
10704
Andy Hung4b17e882023-07-07 13:47:37 -070010705void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hungbcfd9e12023-09-19 14:48:41 -070010706NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010708 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709 if (isOutput()) {
10710 config->role = AUDIO_PORT_ROLE_SOURCE;
10711 config->ext.mix.hw_module = mAudioHwDev->handle();
10712 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10713 } else {
10714 config->role = AUDIO_PORT_ROLE_SINK;
10715 config->ext.mix.hw_module = mAudioHwDev->handle();
10716 config->ext.mix.usecase.source = mAudioSource;
10717 }
10718}
10719
Andy Hung4b17e882023-07-07 13:47:37 -070010720status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010721{
10722 audio_session_t session = chain->sessionId();
10723
10724 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10725 // Attach all tracks with same session ID to this chain.
10726 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010727 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010728 if (session == track->sessionId()) {
10729 chain->incTrackCnt();
10730 chain->incActiveTrackCnt();
10731 }
10732 }
10733
10734 chain->setThread(this);
10735 chain->setInBuffer(nullptr);
10736 chain->setOutBuffer(nullptr);
10737 chain->syncHalEffectsState();
10738
10739 mEffectChains.add(chain);
10740 checkSuspendOnAddEffectChain_l(chain);
10741 return NO_ERROR;
10742}
10743
Andy Hung4b17e882023-07-07 13:47:37 -070010744size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745{
10746 audio_session_t session = chain->sessionId();
10747
10748 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10749
10750 for (size_t i = 0; i < mEffectChains.size(); i++) {
10751 if (chain == mEffectChains[i]) {
10752 mEffectChains.removeAt(i);
10753 // detach all active tracks from the chain
10754 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010755 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010756 if (session == track->sessionId()) {
10757 chain->decActiveTrackCnt();
10758 chain->decTrackCnt();
10759 }
10760 }
10761 break;
10762 }
10763 }
10764 return mEffectChains.size();
10765}
10766
Andy Hung4b17e882023-07-07 13:47:37 -070010767void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010768{
10769 mHalStream->standby();
10770}
10771
Andy Hung4b17e882023-07-07 13:47:37 -070010772void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010773{
Phil Burk7dce7282017-09-27 13:51:41 -070010774 // Do not call callback->onTearDown() because it is redundant for thread exit
10775 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776}
10777
Andy Hung4b17e882023-07-07 13:47:37 -070010778status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779{
10780 return BAD_VALUE;
10781}
10782
Andy Hung4b17e882023-07-07 13:47:37 -070010783bool MmapThread::isValidSyncEvent(
10784 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010785{
10786 return false;
10787}
10788
Andy Hung4b17e882023-07-07 13:47:37 -070010789status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790 const effect_descriptor_t *desc, audio_session_t sessionId)
10791{
10792 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010793 if (audio_is_global_session(sessionId)) {
10794 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010795 desc->name, mThreadName);
10796 return BAD_VALUE;
10797 }
10798
10799 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10800 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10801 desc->name);
10802 return BAD_VALUE;
10803 }
10804 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010805 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10806 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010807 return BAD_VALUE;
10808 }
10809
10810 // Only allow effects without processing load or latency
10811 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10812 return BAD_VALUE;
10813 }
10814
Andy Hung116bc262023-06-20 18:56:17 -070010815 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010816 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10817 return BAD_VALUE;
10818 }
10819
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010821}
10822
Andy Hung4b17e882023-07-07 13:47:37 -070010823void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010824{
Eric Laurent039c24a2022-10-07 14:01:59 +020010825 sp<MmapStreamCallback> callback;
Andy Hung11e74242023-06-26 19:20:57 -070010826 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010827 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010828 callback = mCallback.promote();
10829 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10830 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10831 mNoCallbackWarningCount++;
10832 }
10833 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010834 }
10835 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010836 if (callback != 0) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010837 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010838 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungb17d24b2023-08-29 14:26:09 -070010839 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010840 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010841}
10842
Andy Hung4b17e882023-07-07 13:47:37 -070010843void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010844{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010845 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10846 mAttr.content_type, mAttr.usage, mAttr.source);
10847 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010848 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010849 dprintf(fd, " No active clients\n");
10850 }
10851}
10852
Andy Hung4b17e882023-07-07 13:47:37 -070010853void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010855 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010856 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010857 dprintf(fd, " %zu Tracks\n", numtracks);
10858 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010859 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010860 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010861 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010862 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010863 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010864 result.append(prefix);
10865 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010866 }
10867 } else {
10868 dprintf(fd, "\n");
10869 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010870 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010871}
10872
Andy Hung4b17e882023-07-07 13:47:37 -070010873/* static */
10874sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010875 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010876 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010877 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010878}
10879
10880MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010881 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010882 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010883 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010884 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010885 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886{
10887 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10888 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070010889 mMasterVolume = afThreadCallback->masterVolume_l();
10890 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent19611512023-07-03 18:14:07 +020010891
10892 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10893 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10894 mStreamTypes[stream].volume = 0.0f;
10895 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
10896 }
10897 // Audio patch and call assistant volume are always max
10898 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10899 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10900 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10901 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10902
Eric Laurent6acd1d42017-01-04 14:23:29 -080010903 if (mAudioHwDev) {
10904 if (mAudioHwDev->canSetMasterVolume()) {
10905 mMasterVolume = 1.0;
10906 }
10907
10908 if (mAudioHwDev->canSetMasterMute()) {
10909 mMasterMute = false;
10910 }
10911 }
10912}
10913
Andy Hung4b17e882023-07-07 13:47:37 -070010914void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010915 audio_stream_type_t streamType,
10916 audio_session_t sessionId,
10917 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010918 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010919 audio_port_handle_t portId)
10920{
Andy Hung160664b2023-09-15 18:19:28 -070010921 audio_utils::lock_guard l(mutex());
10922 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010923 mStreamType = streamType;
10924}
10925
Andy Hung4b17e882023-07-07 13:47:37 -070010926AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010927{
Andy Hungf8635b62023-08-31 16:13:39 -070010928 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010929 AudioStreamOut *output = mOutput;
10930 mOutput = NULL;
10931 return output;
10932}
10933
Andy Hung4b17e882023-07-07 13:47:37 -070010934void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935{
Andy Hungf8635b62023-08-31 16:13:39 -070010936 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937 // Don't apply master volume in SW if our HAL can do it for us.
10938 if (mAudioHwDev &&
10939 mAudioHwDev->canSetMasterVolume()) {
10940 mMasterVolume = 1.0;
10941 } else {
10942 mMasterVolume = value;
10943 }
10944}
10945
Andy Hung4b17e882023-07-07 13:47:37 -070010946void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010947{
Andy Hungf8635b62023-08-31 16:13:39 -070010948 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010949 // Don't apply master mute in SW if our HAL can do it for us.
10950 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10951 mMasterMute = false;
10952 } else {
10953 mMasterMute = muted;
10954 }
10955}
10956
Andy Hung4b17e882023-07-07 13:47:37 -070010957void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010958{
Andy Hungf8635b62023-08-31 16:13:39 -070010959 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010960 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010961 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010962 broadcast_l();
10963 }
10964}
10965
Andy Hung4b17e882023-07-07 13:47:37 -070010966float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010967{
Andy Hungf8635b62023-08-31 16:13:39 -070010968 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010969 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010970}
10971
Andy Hung4b17e882023-07-07 13:47:37 -070010972void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010973{
Andy Hungf8635b62023-08-31 16:13:39 -070010974 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010975 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010976 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010977 broadcast_l();
10978 }
10979}
10980
Andy Hung4b17e882023-07-07 13:47:37 -070010981void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010982{
Andy Hungf8635b62023-08-31 16:13:39 -070010983 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010984 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070010985 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010986 track->invalidate();
10987 }
10988 broadcast_l();
10989 }
10990}
10991
Andy Hung4b17e882023-07-07 13:47:37 -070010992void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010993{
Andy Hungf8635b62023-08-31 16:13:39 -070010994 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010995 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070010996 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010997 if (portIds.find(track->portId()) != portIds.end()) {
10998 track->invalidate();
10999 trackMatch = true;
11000 portIds.erase(track->portId());
11001 }
11002 if (portIds.empty()) {
11003 break;
11004 }
11005 }
11006 if (trackMatch) {
11007 broadcast_l();
11008 }
11009}
11010
Andy Hung4b17e882023-07-07 13:47:37 -070011011void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011012NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011013{
11014 float volume;
11015
Eric Laurent19611512023-07-03 18:14:07 +020011016 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011017 volume = 0;
11018 } else {
Eric Laurent19611512023-07-03 18:14:07 +020011019 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011020 }
11021
11022 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011023 // Convert volumes from float to 8.24
11024 uint32_t vol = (uint32_t)(volume * (1 << 24));
11025
11026 // Delegate volume control to effect in track effect chain if needed
11027 // only one effect chain can be present on DirectOutputThread, so if
11028 // there is one, the track is connected to it
11029 if (!mEffectChains.isEmpty()) {
11030 mEffectChains[0]->setVolume_l(&vol, &vol);
11031 volume = (float)vol / (1 << 24);
11032 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011033 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011034 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11035 mHalVolFloat = volume; // HW volume control worked, so update value.
11036 mNoCallbackWarningCount = 0;
11037 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011038 sp<MmapStreamCallback> callback = mCallback.promote();
11039 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011040 mHalVolFloat = volume; // SW volume control worked, so update value.
11041 mNoCallbackWarningCount = 0;
Andy Hungb17d24b2023-08-29 14:26:09 -070011042 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011043 callback->onVolumeChanged(volume);
Andy Hungb17d24b2023-08-29 14:26:09 -070011044 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011046 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11047 ALOGW("Could not set MMAP stream volume: no volume callback!");
11048 mNoCallbackWarningCount++;
11049 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011050 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011051 }
Andy Hung11e74242023-06-26 19:20:57 -070011052 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011053 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070011054 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011055 /*muteState=*/{mMasterMute,
Eric Laurent19611512023-07-03 18:14:07 +020011056 streamVolume_l() == 0.f,
11057 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011058 // TODO(b/241533526): adjust logic to include mute from AppOps
11059 false /*muteFromPlaybackRestricted*/,
11060 false /*muteFromClientVolume*/,
11061 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011062 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011063 }
11064}
11065
Andy Hung4b17e882023-07-07 13:47:37 -070011066ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011067{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011068 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011069 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011070 }
11071 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011072 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011073 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011074 playback_track_metadata_v7_t trackMetadata;
11075 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011076 .usage = track->attributes().usage,
11077 .content_type = track->attributes().content_type,
11078 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011079 };
11080 trackMetadata.channel_mask = track->channelMask(),
11081 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11082 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011083 }
11084 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011085
11086 MetadataUpdate change;
11087 change.playbackMetadataUpdate = metadata.tracks;
11088 return change;
11089};
Kevin Rocard069c2712018-03-29 19:09:14 -070011090
Andy Hung4b17e882023-07-07 13:47:37 -070011091void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011092{
11093 if (!mMasterMute) {
11094 char value[PROPERTY_VALUE_MAX];
11095 if (property_get("ro.audio.silent", value, "0") > 0) {
11096 char *endptr;
11097 unsigned long ul = strtoul(value, &endptr, 0);
11098 if (*endptr == '\0' && ul != 0) {
Andy Hung6fb26892024-02-20 16:32:57 -080011099 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011100 // The setprop command will not allow a property to be changed after
11101 // the first time it is set, so we don't have to worry about un-muting.
11102 setMasterMute_l(true);
11103 }
11104 }
11105 }
11106}
11107
Andy Hung4b17e882023-07-07 13:47:37 -070011108void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011109{
11110 MmapThread::toAudioPortConfig(config);
11111 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11112 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11113 config->flags.output = mOutput->flags;
11114 }
11115}
11116
Andy Hung4b17e882023-07-07 13:47:37 -070011117status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070011118 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011119{
11120 if (mOutput == nullptr) {
11121 return NO_INIT;
11122 }
11123 struct timespec timestamp;
11124 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11125 if (status == NO_ERROR) {
11126 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11127 }
11128 return status;
11129}
11130
Andy Hung4b17e882023-07-07 13:47:37 -070011131status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011132 // Send to MelProcessor for sound dose measurement.
11133 auto processor = mMelProcessor.load();
11134 if (processor) {
11135 processor->process(buffer, frameCount * mFrameSize);
11136 }
11137
jiabinfc791ee2023-02-15 19:43:40 +000011138 return NO_ERROR;
11139}
11140
Andy Hungb17d24b2023-08-29 14:26:09 -070011141// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011142void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011143 const sp<audio_utils::MelProcessor>& processor)
11144{
11145 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011146 mMelProcessor.store(processor);
11147 if (processor) {
11148 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011149 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011150
11151 // no need to update output format for MMapPlaybackThread since it is
11152 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011153}
11154
Andy Hungb17d24b2023-08-29 14:26:09 -070011155// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011156void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011157{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011158 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11159 auto melProcessor = mMelProcessor.load();
11160 if (melProcessor != nullptr) {
11161 melProcessor->pause();
11162 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011163}
11164
Andy Hung4b17e882023-07-07 13:47:37 -070011165void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011166{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011167 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011168
Glenn Kastend3bb6452016-12-05 18:14:37 -080011169 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent19611512023-07-03 18:14:07 +020011170 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011171 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11172}
11173
Andy Hung4b17e882023-07-07 13:47:37 -070011174/* static */
11175sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070011176 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070011177 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011178 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011179}
11180
11181MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011182 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011183 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011184 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011185 mInput(input)
11186{
11187 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11188 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11189}
11190
Andy Hung4b17e882023-07-07 13:47:37 -070011191status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011192{
Phil Burkf054fc32018-12-06 09:45:59 -080011193 {
11194 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011195 if (mInput != nullptr && mInput->stream != nullptr) {
11196 mInput->stream->setGain(1.0f);
11197 }
11198 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011199 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011200}
11201
Andy Hung4b17e882023-07-07 13:47:37 -070011202AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011203{
Andy Hungf8635b62023-08-31 16:13:39 -070011204 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011205 AudioStreamIn *input = mInput;
11206 mInput = NULL;
11207 return input;
11208}
Kevin Rocard069c2712018-03-29 19:09:14 -070011209
Andy Hung4b17e882023-07-07 13:47:37 -070011210void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011211{
11212 bool changed = false;
11213 bool silenced = false;
11214
11215 sp<MmapStreamCallback> callback = mCallback.promote();
11216 if (callback == 0) {
11217 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11218 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11219 mNoCallbackWarningCount++;
11220 }
11221 }
11222
11223 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11224 // track is silenced and unmute otherwise
11225 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11226 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11227 changed = true;
11228 silenced = mActiveTracks[i]->isSilenced_l();
11229 }
11230 }
11231
11232 if (changed) {
11233 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11234 }
11235}
11236
Andy Hung4b17e882023-07-07 13:47:37 -070011237ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011238{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011239 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011240 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011241 }
11242 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011243 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011244 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011245 record_track_metadata_v7_t trackMetadata;
11246 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011247 .source = track->attributes().source,
11248 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011249 };
11250 trackMetadata.channel_mask = track->channelMask(),
11251 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11252 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011253 }
11254 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011255 MetadataUpdate change;
11256 change.recordMetadataUpdate = metadata.tracks;
11257 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011258}
11259
Andy Hung4b17e882023-07-07 13:47:37 -070011260void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011261{
Andy Hungf8635b62023-08-31 16:13:39 -070011262 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011263 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011264 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011265 mActiveTracks[i]->setSilenced_l(silenced);
11266 broadcast_l();
11267 }
11268 }
jiabin09609032022-06-15 19:26:01 +000011269 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011270}
11271
Andy Hung4b17e882023-07-07 13:47:37 -070011272void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011273{
11274 MmapThread::toAudioPortConfig(config);
11275 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11276 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11277 config->flags.input = mInput->flags;
11278 }
11279}
11280
Andy Hung4b17e882023-07-07 13:47:37 -070011281status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011282 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011283{
11284 if (mInput == nullptr) {
11285 return NO_INIT;
11286 }
11287 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11288}
11289
jiabinc658e452022-10-21 20:52:21 +000011290// ----------------------------------------------------------------------------
11291
Andy Hung4b17e882023-07-07 13:47:37 -070011292/* static */
11293sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011294 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011295 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011296 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011297}
11298
Andy Hung7535ed92023-07-17 17:05:00 -070011299BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011300 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011301 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011302
Andy Hung4b17e882023-07-07 13:47:37 -070011303PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011304 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011305 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11306 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011307 float volumeLeft = 1.0f;
11308 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011309 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11310 const int trackId = mActiveTracks[0]->id();
11311 mAudioMixer->setParameter(
11312 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11313 mAudioMixer->setParameter(
11314 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11315 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011316 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011317 mIsBitPerfect = true;
11318 } else {
11319 mIsBitPerfect = false;
11320 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11321 // active.
11322 for (const auto& track : mActiveTracks) {
11323 const int trackId = track->id();
11324 mAudioMixer->setParameter(
11325 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11326 }
11327 }
jiabin76d94692022-12-15 21:51:21 +000011328 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11329 mVolumeLeft = volumeLeft;
11330 mVolumeRight = volumeRight;
11331 setVolumeForOutput_l(volumeLeft, volumeRight);
11332 }
jiabinc658e452022-10-21 20:52:21 +000011333 return result;
11334}
11335
Andy Hung4b17e882023-07-07 13:47:37 -070011336void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011337 MixerThread::threadLoop_mix();
11338 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11339}
11340
Glenn Kasten63238ef2015-03-02 15:50:29 -080011341} // namespace android