blob: cec20334e0fd261a7683d8c155306f63b2cbd654 [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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hungee58e4a2023-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 Hung25a80ac2023-07-19 12:47:35 -0700127// Keep in sync with java definition in media/java/android/media/AudioRecord.java
128static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// retry counts for buffer fill timeout
131// 50 * ~20msecs = 1 second
132static const int8_t kMaxTrackRetries = 50;
133static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// allow less retry attempts on direct output thread.
136// direct outputs can be a scarce resource in audio hardware and should
137// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700138// Notes:
139// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
140// in case the data write is bursty for the AudioTrack. The application
141// should endeavor to write at least once every kMaxTrackRetriesDirectMs
142// to prevent an underrun situation. If the data is bursty, then
143// the application can also throttle the data sent to be even.
144// 2) For compressed audio data, any data present in the AudioTrack buffer
145// will be sent and reset the retry count. This delivers data as
146// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
147// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
148// of data to be available, then any remaining data is delivered.
149// This is required to ensure the last bit of data is delivered before underrun.
150//
151// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
152// or the size of the HAL period for proportional / linear PCM tracks.
153static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800154
155// don't warn about blocked writes or record buffer overflows more often than this
156static const nsecs_t kWarningThrottleNs = seconds(5);
157
158// RecordThread loop sleep time upon application overrun or audio HAL read error
159static const int kRecordThreadSleepUs = 5000;
160
Eric Laurent10351942014-05-08 18:49:52 -0700161// maximum time to wait in sendConfigEvent_l() for a status to be received
162static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// minimum sleep time for the mixer thread loop when tracks are active but in underrun
165static const uint32_t kMinThreadSleepTimeUs = 5000;
166// maximum divider applied to the active sleep time in the mixer thread loop
167static const uint32_t kMaxThreadSleepTimeShift = 2;
168
Andy Hung09a50072014-02-27 14:30:47 -0800169// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700170// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800171static const uint32_t kMinNormalSinkBufferSizeMs = 20;
172// maximum normal sink buffer size
173static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700175// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
176// FIXME This should be based on experimentally observed scheduling jitter
177static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
178
Eric Laurent972a1732013-09-04 09:42:59 -0700179// Offloaded output thread standby delay: allows track transition without going to standby
180static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
181
Eric Laurent51716182016-02-29 18:00:56 -0800182// Direct output thread minimum sleep time in idle or active(underrun) state
183static const nsecs_t kDirectMinSleepTimeUs = 10000;
184
Brian Lindahl65e90012022-07-27 18:01:07 +0200185// Minimum amount of time between checking to see if the timestamp is advancing
186// for underrun detection. If we check too frequently, we may not detect a
187// timestamp update and will falsely detect underrun.
188static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
189
Glenn Kasten1b291842016-07-18 14:55:21 -0700190// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
191// balance between power consumption and latency, and allows threads to be scheduled reliably
192// by the CFS scheduler.
193// FIXME Express other hardcoded references to 20ms with references to this constant and move
194// it appropriately.
195#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800196
Eric Laurent81784c32012-11-19 14:55:58 -0800197// Whether to use fast mixer
198static const enum {
199 FastMixer_Never, // never initialize or use: for debugging only
200 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
201 // normal mixer multiplier is 1
202 FastMixer_Static, // initialize if needed, then use all the time if initialized,
203 // multiplier is calculated based on min & max normal mixer buffer size
204 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 // FIXME for FastMixer_Dynamic:
207 // Supporting this option will require fixing HALs that can't handle large writes.
208 // For example, one HAL implementation returns an error from a large write,
209 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
210 // We could either fix the HAL implementations, or provide a wrapper that breaks
211 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
212} kUseFastMixer = FastMixer_Static;
213
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700214// Whether to use fast capture
215static const enum {
216 FastCapture_Never, // never initialize or use: for debugging only
217 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
218 FastCapture_Static, // initialize if needed, then use all the time if initialized
219} kUseFastCapture = FastCapture_Static;
220
Eric Laurent81784c32012-11-19 14:55:58 -0800221// Priorities for requestPriority
222static const int kPriorityAudioApp = 2;
223static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700224static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800225
Glenn Kastenea38ee72016-04-18 11:08:01 -0700226// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
227// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
228// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700229
230// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800231static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800232
Glenn Kasten03490092014-05-27 12:30:54 -0700233// The minimum and maximum allowed values
234static const int kFastTrackMultiplierMin = 1;
235static const int kFastTrackMultiplierMax = 2;
236
237// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
238static int sFastTrackMultiplier = kFastTrackMultiplier;
239
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700240// See Thread::readOnlyHeap().
241// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
242// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
243// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700244static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700245
Andy Hung25a80ac2023-07-19 12:47:35 -0700246static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-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 Hung81994d62023-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 Hung25a80ac2023-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 Wasilczyk833345b2023-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 Hungee58e4a2023-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 Hung583043b2023-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 Hung583043b2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungc5007f82023-08-29 14:26:09 -0700688 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800689 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700690 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800691 }
692 // When Thread::requestExitAndWait is made virtual and this method is renamed to
693 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
694 requestExitAndWait();
695}
696
Andy Hungee58e4a2023-07-07 13:47:37 -0700697status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800698{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000699 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700700 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800701
Eric Laurent10351942014-05-08 18:49:52 -0700702 return sendSetParameterConfigEvent_l(keyValuePairs);
703}
704
705// sendConfigEvent_l() must be called with ThreadBase::mLock held
706// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700707status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700708NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700709{
710 status_t status = NO_ERROR;
711
Eric Laurent72e3f392015-05-20 14:43:50 -0700712 if (event->mRequiresSystemReady && !mSystemReady) {
713 event->mWaitStatus = false;
714 mPendingConfigEvents.add(event);
715 return status;
716 }
Eric Laurent10351942014-05-08 18:49:52 -0700717 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700718 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700719 mWaitWorkCV.notify_one();
720 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700721 {
Andy Hungc5007f82023-08-29 14:26:09 -0700722 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700723 while (event->mWaitStatus) {
Andy Hungc5007f82023-08-29 14:26:09 -0700724 if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
725 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700726 event->mStatus = TIMED_OUT;
727 event->mWaitStatus = false;
728 }
729 }
730 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800731 }
Andy Hungc5007f82023-08-29 14:26:09 -0700732 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800733 return status;
734}
735
Andy Hungee58e4a2023-07-07 13:47:37 -0700736void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700737 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800738{
Andy Hung972bec12023-08-31 16:13:39 -0700739 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700740 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Andy Hungc5007f82023-08-29 14:26:09 -0700743// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700744void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700745 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800746{
Andy Hungd0979812019-02-21 15:51:44 -0800747 // The audio statistics history is exponentially weighted to forget events
748 // about five or more seconds in the past. In order to have
749 // crisper statistics for mediametrics, we reset the statistics on
750 // an IoConfigEvent, to reflect different properties for a new device.
751 mIoJitterMs.reset();
752 mLatencyMs.reset();
753 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000754 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100755 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800756
Eric Laurent09f1ed22019-04-24 17:45:17 -0700757 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700758 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800759}
760
Andy Hungee58e4a2023-07-07 13:47:37 -0700761void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700762{
Andy Hung972bec12023-08-31 16:13:39 -0700763 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800764 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700765}
766
Andy Hungc5007f82023-08-29 14:26:09 -0700767// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700768void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800769 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800770{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800771 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700772 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800773}
774
Andy Hungc5007f82023-08-29 14:26:09 -0700775// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700776status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800777{
Andy Hung2ddee192015-12-18 17:34:44 -0800778 sp<ConfigEvent> configEvent;
779 AudioParameter param(keyValuePair);
780 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700781 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800782 setMasterMono_l(value != 0);
783 if (param.size() == 1) {
784 return NO_ERROR; // should be a solo parameter - we don't pass down
785 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700786 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800787 configEvent = new SetParameterConfigEvent(param.toString());
788 } else {
789 configEvent = new SetParameterConfigEvent(keyValuePair);
790 }
Eric Laurent10351942014-05-08 18:49:52 -0700791 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700792}
793
Andy Hungee58e4a2023-07-07 13:47:37 -0700794status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700795 const struct audio_patch *patch,
796 audio_patch_handle_t *handle)
797{
Andy Hung972bec12023-08-31 16:13:39 -0700798 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700799 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
800 status_t status = sendConfigEvent_l(configEvent);
801 if (status == NO_ERROR) {
802 CreateAudioPatchConfigEventData *data =
803 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
804 *handle = data->mHandle;
805 }
806 return status;
807}
808
Andy Hungee58e4a2023-07-07 13:47:37 -0700809status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700810 const audio_patch_handle_t handle)
811{
Andy Hung972bec12023-08-31 16:13:39 -0700812 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
814 return sendConfigEvent_l(configEvent);
815}
816
Andy Hungee58e4a2023-07-07 13:47:37 -0700817status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700818 const DeviceDescriptorBaseVector& outDevices)
819{
820 if (type() != RECORD) {
821 // The update out device operation is only for record thread.
822 return INVALID_OPERATION;
823 }
Andy Hung972bec12023-08-31 16:13:39 -0700824 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700825 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
826 return sendConfigEvent_l(configEvent);
827}
828
Andy Hungee58e4a2023-07-07 13:47:37 -0700829void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200830{
831 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
832 sp<ConfigEvent> configEvent =
833 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
834 sendConfigEvent_l(configEvent);
835}
Eric Laurent1c333e22014-05-20 10:48:17 -0700836
Andy Hungee58e4a2023-07-07 13:47:37 -0700837void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200838{
Andy Hung972bec12023-08-31 16:13:39 -0700839 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200840 sendCheckOutputStageEffectsEvent_l();
841}
842
Andy Hungee58e4a2023-07-07 13:47:37 -0700843void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200844{
845 sp<ConfigEvent> configEvent =
846 (ConfigEvent *)new CheckOutputStageEffectsEvent();
847 sendConfigEvent_l(configEvent);
848}
849
Andy Hungee58e4a2023-07-07 13:47:37 -0700850void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200851{
852 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
853 sendConfigEvent_l(configEvent);
854}
855
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700856// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700857void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700858{
Eric Laurent10351942014-05-08 18:49:52 -0700859 bool configChanged = false;
860
Eric Laurent81784c32012-11-19 14:55:58 -0800861 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700862 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700863 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800864 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700865 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700866 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700867 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
868 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800869 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700870 true /*asynchronous*/);
871 if (err != 0) {
872 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700873 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700874 }
875 } break;
876 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700877 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700878 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700879 } break;
880 case CFG_EVENT_SET_PARAMETER: {
881 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
882 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
883 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700884 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000885 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700886 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700887 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700888 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700889 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700890 CreateAudioPatchConfigEventData *data =
891 (CreateAudioPatchConfigEventData *)event->mData.get();
892 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700893 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200894 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700895 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
896 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
897 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700898 } break;
899 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700900 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700901 ReleaseAudioPatchConfigEventData *data =
902 (ReleaseAudioPatchConfigEventData *)event->mData.get();
903 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700904 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200905 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700906 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
907 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
908 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
909 } break;
910 case CFG_EVENT_UPDATE_OUT_DEVICE: {
911 UpdateOutDevicesConfigEventData *data =
912 (UpdateOutDevicesConfigEventData *)event->mData.get();
913 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700914 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200915 case CFG_EVENT_RESIZE_BUFFER: {
916 ResizeBufferConfigEventData *data =
917 (ResizeBufferConfigEventData *)event->mData.get();
918 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
919 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200920
921 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
922 setCheckOutputStageEffects();
923 } break;
924
Eric Laurent68a40a82022-05-03 18:15:04 +0200925 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
926 onHalLatencyModesChanged_l();
927 } break;
928
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700929 default:
Eric Laurent10351942014-05-08 18:49:52 -0700930 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700931 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
Eric Laurent10351942014-05-08 18:49:52 -0700933 {
Andy Hung972bec12023-08-31 16:13:39 -0700934 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700935 if (event->mWaitStatus) {
936 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700937 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700938 }
939 }
940 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
941 }
942
943 if (configChanged) {
944 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
Eric Laurent81784c32012-11-19 14:55:58 -0800946}
947
Marco Nelissenb2208842014-02-07 14:00:50 -0800948String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
949 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700950 const audio_channel_representation_t representation =
951 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700952
953 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800954 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700955 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
956 if (output) {
957 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
958 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
959 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700960 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700961 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
962 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
963 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
964 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
965 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
966 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
967 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
968 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
969 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700973 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
977 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
978 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
979 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700980 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700981 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
982 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700983 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
984 } else {
985 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
986 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
987 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
988 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
989 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
990 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
991 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
992 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
993 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
994 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
995 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
996 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700997 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
998 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
999 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001000 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001001 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1002 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001003 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1004 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1005 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1006 }
1007 const int len = s.length();
1008 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001009 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001010 s.unlockBuffer(len - 2); // remove trailing ", "
1011 }
1012 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001013 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001014 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1015 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1016 return s;
1017 default:
1018 s.appendFormat("unknown mask, representation:%d bits:%#x",
1019 representation, audio_channel_mask_get_bits(mask));
1020 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001021 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001022}
1023
Andy Hungee58e4a2023-07-07 13:47:37 -07001024void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001025NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001026{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001027 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1028 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1029
Andy Hungc5007f82023-08-29 14:26:09 -07001030 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001031 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001032 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001033 }
1034
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001035 dumpBase_l(fd, args);
1036 dumpInternals_l(fd, args);
1037 dumpTracks_l(fd, args);
1038 dumpEffectChains_l(fd, args);
1039
1040 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001041 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001042 }
1043
1044 dprintf(fd, " Local log:\n");
1045 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001046
1047 // --all does the statistics
1048 bool dumpAll = false;
1049 for (const auto &arg : args) {
1050 if (arg == String16("--all")) {
1051 dumpAll = true;
1052 }
1053 }
1054 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001055 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001056 if (!sched.empty()) {
1057 (void)write(fd, sched.c_str(), sched.size());
1058 }
1059 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001060}
1061
Andy Hungee58e4a2023-07-07 13:47:37 -07001062void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001063{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001064 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001065 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001066 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001067 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001068 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1069 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001070 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001071 dprintf(fd, " Channel count: %u\n", mChannelCount);
1072 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001073 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001074 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1075 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001076 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001077 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001078 size_t numConfig = mConfigEvents.size();
1079 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001080 const size_t SIZE = 256;
1081 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001082 for (size_t i = 0; i < numConfig; i++) {
1083 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001084 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001085 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001086 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001087 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001088 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001089 }
Andy Hung293558a2017-03-21 12:19:20 -07001090 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001091 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001092 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001093 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001094 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001095 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001096
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001097 // Dump timestamp statistics for the Thread types that support it.
1098 if (mType == RECORD
1099 || mType == MIXER
1100 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001101 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001102 || mType == OFFLOAD
1103 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001104 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001105 dprintf(fd, " Timestamp corrected: %s\n",
1106 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001107 }
1108
Andy Hung446f4df2019-02-21 12:26:41 -08001109 if (mLastIoBeginNs > 0) { // MMAP may not set this
1110 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1111 isOutput() ? "write" : "read",
1112 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1113 }
1114
1115 if (mProcessTimeMs.getN() > 0) {
1116 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1117 }
1118
1119 if (mIoJitterMs.getN() > 0) {
1120 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1121 isOutput() ? "write" : "read",
1122 mIoJitterMs.toString().c_str());
1123 }
1124
Andy Hunge6c37112019-02-26 17:38:10 -08001125 if (mLatencyMs.getN() > 0) {
1126 dprintf(fd, " Threadloop %s latency stats: %s\n",
1127 isOutput() ? "write" : "read",
1128 mLatencyMs.toString().c_str());
1129 }
Robert Wu06db0a32021-08-10 19:05:34 +00001130
1131 if (mMonopipePipeDepthStats.getN() > 0) {
1132 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1133 isOutput() ? "write" : "read",
1134 mMonopipePipeDepthStats.toString().c_str());
1135 }
Eric Laurent81784c32012-11-19 14:55:58 -08001136}
1137
Andy Hungee58e4a2023-07-07 13:47:37 -07001138void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001139{
1140 const size_t SIZE = 256;
1141 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001142
Marco Nelissenb2208842014-02-07 14:00:50 -08001143 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001144 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001145 write(fd, buffer, strlen(buffer));
1146
Marco Nelissenb2208842014-02-07 14:00:50 -08001147 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001148 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001149 if (chain != 0) {
1150 chain->dump(fd, args);
1151 }
1152 }
1153}
1154
Andy Hungee58e4a2023-07-07 13:47:37 -07001155void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001156{
Andy Hung972bec12023-08-31 16:13:39 -07001157 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001158 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001159}
1160
Andy Hungee58e4a2023-07-07 13:47:37 -07001161String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001162{
1163 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001164 case MIXER:
1165 return String16("AudioMix");
1166 case DIRECT:
1167 return String16("AudioDirectOut");
1168 case DUPLICATING:
1169 return String16("AudioDup");
1170 case RECORD:
1171 return String16("AudioIn");
1172 case OFFLOAD:
1173 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001174 case MMAP_PLAYBACK:
1175 return String16("MmapPlayback");
1176 case MMAP_CAPTURE:
1177 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001178 case SPATIALIZER:
1179 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001180 default:
1181 ALOG_ASSERT(false);
1182 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001183 }
1184}
1185
Andy Hungee58e4a2023-07-07 13:47:37 -07001186void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001187{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001188 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001189 if (mPowerManager != 0) {
1190 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001191 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001192 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1193 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001194 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001195 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001196 {} /* workSource */,
1197 {} /* historyTag */);
1198 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001199 mWakeLockToken = binder;
1200 }
Chris Ye6597d732020-02-28 22:38:25 -08001201 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001202 }
Wei Jia3f273d12015-11-24 09:06:49 -08001203
Andy Hung3f0c9022016-01-15 17:49:46 -08001204 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001205 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1206 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001207}
1208
Andy Hungee58e4a2023-07-07 13:47:37 -07001209void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001210{
Andy Hung972bec12023-08-31 16:13:39 -07001211 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001212 releaseWakeLock_l();
1213}
1214
Andy Hungee58e4a2023-07-07 13:47:37 -07001215void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001216{
Andy Hung3f0c9022016-01-15 17:49:46 -08001217 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001218 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001219 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001220 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001221 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001222 }
1223 mWakeLockToken.clear();
1224 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001225}
1226
Andy Hungee58e4a2023-07-07 13:47:37 -07001227void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001228 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001229 // use checkService() to avoid blocking if power service is not up yet
1230 sp<IBinder> binder =
1231 defaultServiceManager()->checkService(String16("power"));
1232 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001233 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001234 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001235 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001236 binder->linkToDeath(mDeathRecipient);
1237 }
1238 }
1239}
1240
Andy Hungee58e4a2023-07-07 13:47:37 -07001241void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001242 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001243
1244#if !LOG_NDEBUG
1245 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001246 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001247 s << uid << " ";
1248 }
1249 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1250#endif
1251
Andy Hung438e7572015-12-14 15:51:17 -08001252 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1253 if (mSystemReady) {
1254 ALOGE("no wake lock to update, but system ready!");
1255 } else {
1256 ALOGW("no wake lock to update, system not ready yet");
1257 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001258 return;
1259 }
1260 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001261 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001262 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1263 mWakeLockToken, uidsAsInt);
1264 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001265 }
1266}
1267
Andy Hungee58e4a2023-07-07 13:47:37 -07001268void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001269{
Andy Hung972bec12023-08-31 16:13:39 -07001270 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001271 releaseWakeLock_l();
1272 mPowerManager.clear();
1273}
1274
Andy Hungee58e4a2023-07-07 13:47:37 -07001275void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001276 const DeviceDescriptorBaseVector& outDevices __unused)
1277{
1278 ALOGE("%s should only be called in RecordThread", __func__);
1279}
1280
Andy Hungee58e4a2023-07-07 13:47:37 -07001281void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001282{
1283 ALOGE("%s should only be called in RecordThread", __func__);
1284}
1285
Andy Hungee58e4a2023-07-07 13:47:37 -07001286void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001287{
1288 sp<ThreadBase> thread = mThread.promote();
1289 if (thread != 0) {
1290 thread->clearPowerManager();
1291 }
1292 ALOGW("power manager service died !!!");
1293}
1294
Andy Hungee58e4a2023-07-07 13:47:37 -07001295void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001296 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001297{
Andy Hung116bc262023-06-20 18:56:17 -07001298 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001299 if (chain != 0) {
1300 if (type != NULL) {
1301 chain->setEffectSuspended_l(type, suspend);
1302 } else {
1303 chain->setEffectSuspendedAll_l(suspend);
1304 }
1305 }
1306
1307 updateSuspendedSessions_l(type, suspend, sessionId);
1308}
1309
Andy Hungee58e4a2023-07-07 13:47:37 -07001310void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001311{
1312 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1313 if (index < 0) {
1314 return;
1315 }
1316
1317 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1318 mSuspendedSessions.valueAt(index);
1319
1320 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001321 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001322 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001323 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001324 chain->setEffectSuspendedAll_l(true);
1325 } else {
1326 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1327 desc->mType.timeLow);
1328 chain->setEffectSuspended_l(&desc->mType, true);
1329 }
1330 }
1331 }
1332}
1333
Andy Hungee58e4a2023-07-07 13:47:37 -07001334void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001335 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001336 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001337{
1338 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1339
1340 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1341
1342 if (suspend) {
1343 if (index >= 0) {
1344 sessionEffects = mSuspendedSessions.valueAt(index);
1345 } else {
1346 mSuspendedSessions.add(sessionId, sessionEffects);
1347 }
1348 } else {
1349 if (index < 0) {
1350 return;
1351 }
1352 sessionEffects = mSuspendedSessions.valueAt(index);
1353 }
1354
1355
Andy Hung116bc262023-06-20 18:56:17 -07001356 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001357 if (type != NULL) {
1358 key = type->timeLow;
1359 }
1360 index = sessionEffects.indexOfKey(key);
1361
1362 sp<SuspendedSessionDesc> desc;
1363 if (suspend) {
1364 if (index >= 0) {
1365 desc = sessionEffects.valueAt(index);
1366 } else {
1367 desc = new SuspendedSessionDesc();
1368 if (type != NULL) {
1369 desc->mType = *type;
1370 }
1371 sessionEffects.add(key, desc);
1372 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1373 }
1374 desc->mRefCount++;
1375 } else {
1376 if (index < 0) {
1377 return;
1378 }
1379 desc = sessionEffects.valueAt(index);
1380 if (--desc->mRefCount == 0) {
1381 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1382 sessionEffects.removeItemsAt(index);
1383 if (sessionEffects.isEmpty()) {
1384 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1385 sessionId);
1386 mSuspendedSessions.removeItem(sessionId);
1387 }
1388 }
1389 }
1390 if (!sessionEffects.isEmpty()) {
1391 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1392 }
1393}
1394
Andy Hungee58e4a2023-07-07 13:47:37 -07001395void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001396 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001397 bool threadLocked)
1398NO_THREAD_SAFETY_ANALYSIS // manual locking
1399{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001400 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001401 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001402 }
Eric Laurent81784c32012-11-19 14:55:58 -08001403
Eric Laurent81784c32012-11-19 14:55:58 -08001404 if (mType != RECORD) {
1405 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1406 // another session. This gives the priority to well behaved effect control panels
1407 // and applications not using global effects.
1408 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1409 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001410 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001411 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1412 }
1413 }
1414
Eric Laurent6b446ce2019-12-13 10:56:31 -08001415 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001416 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001417 }
1418}
1419
Andy Hungc5007f82023-08-29 14:26:09 -07001420// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001421status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001422 const effect_descriptor_t *desc, audio_session_t sessionId)
1423{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001424 // No global output effect sessions on record threads
1425 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1426 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001427 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1428 desc->name, mThreadName);
1429 return BAD_VALUE;
1430 }
1431 // only pre processing effects on record thread
1432 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1433 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1434 desc->name, mThreadName);
1435 return BAD_VALUE;
1436 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001437
1438 // always allow effects without processing load or latency
1439 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1440 return NO_ERROR;
1441 }
1442
Eric Laurent4c415062016-06-17 16:14:16 -07001443 audio_input_flags_t flags = mInput->flags;
1444 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1445 if (flags & AUDIO_INPUT_FLAG_RAW) {
1446 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1447 desc->name, mThreadName);
1448 return BAD_VALUE;
1449 }
1450 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1451 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1452 desc->name, mThreadName);
1453 return BAD_VALUE;
1454 }
1455 }
jiabineb3bda02020-06-30 14:07:03 -07001456
Andy Hung116bc262023-06-20 18:56:17 -07001457 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001458 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1459 return BAD_VALUE;
1460 }
Eric Laurent4c415062016-06-17 16:14:16 -07001461 return NO_ERROR;
1462}
1463
Andy Hungc5007f82023-08-29 14:26:09 -07001464// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001465status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001466 const effect_descriptor_t *desc, audio_session_t sessionId)
1467{
1468 // no preprocessing on playback threads
1469 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001470 ALOGW("%s: pre processing effect %s created on playback"
1471 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001472 return BAD_VALUE;
1473 }
1474
Eric Laurent3e4de772017-07-16 16:55:08 -07001475 // always allow effects without processing load or latency
1476 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1477 return NO_ERROR;
1478 }
1479
Andy Hung116bc262023-06-20 18:56:17 -07001480 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001481 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1482 __func__);
1483 return BAD_VALUE;
1484 }
1485
Eric Laurentf690c462021-09-17 14:47:03 +02001486 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1487 && mType != SPATIALIZER) {
1488 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1489 __func__, mType);
1490 return BAD_VALUE;
1491 }
1492
Eric Laurent4c415062016-06-17 16:14:16 -07001493 switch (mType) {
1494 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001495 audio_output_flags_t flags = mOutput->flags;
1496 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1497 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1498 // global effects are applied only to non fast tracks if they are SW
1499 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1500 break;
1501 }
1502 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1503 // only post processing on output stage session
1504 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001505 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1506 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001507 return BAD_VALUE;
1508 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001509 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1510 // only post processing on output stage session
1511 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001512 ALOGW("%s: non post processing effect %s not allowed on device session",
1513 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001514 return BAD_VALUE;
1515 }
Eric Laurent4c415062016-06-17 16:14:16 -07001516 } else {
1517 // no restriction on effects applied on non fast tracks
1518 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1519 break;
1520 }
1521 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001522
Eric Laurent4c415062016-06-17 16:14:16 -07001523 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001524 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001525 return BAD_VALUE;
1526 }
1527 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001528 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1529 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001530 return BAD_VALUE;
1531 }
1532 }
1533 } break;
1534 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001535 // nothing actionable on offload threads, if the effect:
1536 // - is offloadable: the effect can be created
1537 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1538 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001539 break;
1540 case DIRECT:
1541 // Reject any effect on Direct output threads for now, since the format of
1542 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001543 ALOGW("%s: effect %s on DIRECT output thread %s",
1544 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001545 return BAD_VALUE;
1546 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001547 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001548 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1549 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001550 return BAD_VALUE;
1551 }
1552 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001553 ALOGW("%s: post processing 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_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001558 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1559 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001560 return BAD_VALUE;
1561 }
1562 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001563 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001564 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1565 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1566 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1567 // are supported and added after the spatializer.
1568 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1569 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1570 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001571 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001572 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1573 // only post processing , downmixer or spatializer effects on output stage session
1574 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1575 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1576 break;
1577 }
1578 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1579 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1580 __func__, desc->name);
1581 return BAD_VALUE;
1582 }
1583 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1584 // only post processing on output stage session
1585 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1586 ALOGW("%s: non post processing effect %s not allowed on device session",
1587 __func__, desc->name);
1588 return BAD_VALUE;
1589 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001590 }
1591 break;
jiabinc658e452022-10-21 20:52:21 +00001592 case BIT_PERFECT:
1593 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1594 // Allow HW accelerated effects of tunnel type
1595 break;
1596 }
1597 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1598 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1599 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1600 // 3) there is any bit-perfect track with the given session id.
1601 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1602 sessionId == AUDIO_SESSION_DEVICE) {
1603 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1604 __func__, desc->name, mThreadName);
1605 return BAD_VALUE;
1606 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1607 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1608 __func__, desc->name, sessionId);
1609 return BAD_VALUE;
1610 }
1611 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001612 default:
1613 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1614 }
1615
1616 return NO_ERROR;
1617}
1618
Andy Hungc5007f82023-08-29 14:26:09 -07001619// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001620sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001621 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001622 const sp<IEffectClient>& effectClient,
1623 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001624 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001625 effect_descriptor_t *desc,
1626 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001627 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001628 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001629 bool probe,
1630 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001631{
Andy Hung116bc262023-06-20 18:56:17 -07001632 sp<IAfEffectModule> effect;
1633 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001634 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001635 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001636 bool chainCreated = false;
1637 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001638 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001639
1640 lStatus = initCheck();
1641 if (lStatus != NO_ERROR) {
1642 ALOGW("createEffect_l() Audio driver not initialized.");
1643 goto Exit;
1644 }
1645
Eric Laurent81784c32012-11-19 14:55:58 -08001646 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1647
Andy Hungc5007f82023-08-29 14:26:09 -07001648 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001649 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001650
Eric Laurent4c415062016-06-17 16:14:16 -07001651 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001652 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001653 goto Exit;
1654 }
1655
Eric Laurent81784c32012-11-19 14:55:58 -08001656 // check for existing effect chain with the requested audio session
1657 chain = getEffectChain_l(sessionId);
1658 if (chain == 0) {
1659 // create a new chain for this session
1660 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001661 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001662 addEffectChain_l(chain);
1663 chain->setStrategy(getStrategyForSession_l(sessionId));
1664 chainCreated = true;
1665 } else {
1666 effect = chain->getEffectFromDesc_l(desc);
1667 }
1668
1669 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1670
1671 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001672 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001673 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001674 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001675 if (lStatus != NO_ERROR) {
1676 goto Exit;
1677 }
1678 effectCreated = true;
1679
jiabinc52b1ff2019-10-31 17:20:42 -07001680 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001681 effect->setDevices(outDeviceTypeAddrs());
1682 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001683 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001684 effect->setAudioSource(mAudioSource);
1685 }
jiabin1319f5a2021-03-30 22:21:24 +00001686 if (effect->isHapticGenerator()) {
1687 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1688 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001689 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001690 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001691 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001692 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001693 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001694 }
1695 }
Eric Laurent81784c32012-11-19 14:55:58 -08001696 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001697 handle = IAfEffectHandle::create(
1698 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001699 lStatus = handle->initCheck();
1700 if (lStatus == OK) {
1701 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001702 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001703 }
Eric Laurent81784c32012-11-19 14:55:58 -08001704 if (enabled != NULL) {
1705 *enabled = (int)effect->isEnabled();
1706 }
1707 }
1708
1709Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001710 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001711 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001712 if (effectCreated) {
1713 chain->removeEffect_l(effect);
1714 }
Eric Laurent81784c32012-11-19 14:55:58 -08001715 if (chainCreated) {
1716 removeEffectChain_l(chain);
1717 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001718 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001719 }
1720
Glenn Kasten9156ef32013-08-06 15:39:08 -07001721 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001722 return handle;
1723}
1724
Andy Hungee58e4a2023-07-07 13:47:37 -07001725void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001726 bool unpinIfLast)
1727{
1728 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001729 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001730 {
Andy Hung972bec12023-08-31 16:13:39 -07001731 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001732 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001733 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001734 return;
1735 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001736 effect = effectBase->asEffectModule();
1737 if (effect == nullptr) {
1738 return;
1739 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001740 // restore suspended effects if the disconnected handle was enabled and the last one.
1741 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1742 if (remove) {
1743 removeEffect_l(effect, true);
1744 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001745 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001746 }
1747 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001748 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001749 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001750 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001751 }
1752 }
1753}
1754
Andy Hungee58e4a2023-07-07 13:47:37 -07001755void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001756 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001757 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001758 broadcast_l();
1759 }
1760 if (!effect->isOffloadable()) {
1761 if (mType == ThreadBase::OFFLOAD) {
1762 PlaybackThread *t = (PlaybackThread *)this;
1763 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1764 }
1765 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001766 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001767 }
1768 }
1769}
1770
Andy Hungee58e4a2023-07-07 13:47:37 -07001771void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001772 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001773 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001774 broadcast_l();
1775 }
1776}
1777
Andy Hungee58e4a2023-07-07 13:47:37 -07001778sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001779 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001780{
Andy Hung972bec12023-08-31 16:13:39 -07001781 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001782 return getEffect_l(sessionId, effectId);
1783}
1784
Andy Hungee58e4a2023-07-07 13:47:37 -07001785sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001786 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001787{
Andy Hung116bc262023-06-20 18:56:17 -07001788 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001789 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1790}
1791
Andy Hungee58e4a2023-07-07 13:47:37 -07001792std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001793{
Andy Hung116bc262023-06-20 18:56:17 -07001794 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001795 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1796}
1797
Andy Hung972bec12023-08-31 16:13:39 -07001798// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1799// ThreadBase::mutex() held
1800status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001801{
1802 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001803 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001804 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001805 bool chainCreated = false;
1806
Eric Laurent5baf2af2013-09-12 17:37:00 -07001807 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001808 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1809 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001810
Eric Laurent81784c32012-11-19 14:55:58 -08001811 if (chain == 0) {
1812 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001813 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001814 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001815 addEffectChain_l(chain);
1816 chain->setStrategy(getStrategyForSession_l(sessionId));
1817 chainCreated = true;
1818 }
Andy Hung972bec12023-08-31 16:13:39 -07001819 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001820
1821 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001822 ALOGW("%s: %p effect %s already present in chain %p",
1823 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001824 return BAD_VALUE;
1825 }
1826
Eric Laurent5baf2af2013-09-12 17:37:00 -07001827 effect->setOffloaded(mType == OFFLOAD, mId);
1828
Eric Laurent81784c32012-11-19 14:55:58 -08001829 status_t status = chain->addEffect_l(effect);
1830 if (status != NO_ERROR) {
1831 if (chainCreated) {
1832 removeEffectChain_l(chain);
1833 }
1834 return status;
1835 }
1836
jiabin8f278ee2019-11-11 12:16:27 -08001837 effect->setDevices(outDeviceTypeAddrs());
1838 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001839 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001840 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001841
Eric Laurent81784c32012-11-19 14:55:58 -08001842 return NO_ERROR;
1843}
1844
Andy Hungee58e4a2023-07-07 13:47:37 -07001845void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001846
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001847 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001848 effect_descriptor_t desc = effect->desc();
1849 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1850 detachAuxEffect_l(effect->id());
1851 }
1852
Andy Hung116bc262023-06-20 18:56:17 -07001853 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001854 if (chain != 0) {
1855 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001856 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001857 removeEffectChain_l(chain);
1858 }
1859 } else {
1860 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1861 }
1862}
1863
Andy Hungee58e4a2023-07-07 13:47:37 -07001864void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001865 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001866NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001867{
1868 effectChains = mEffectChains;
1869 for (size_t i = 0; i < mEffectChains.size(); i++) {
Andy Hungf65f5a72023-08-29 12:19:17 -07001870 mEffectChains[i]->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001871 }
1872}
1873
Andy Hungee58e4a2023-07-07 13:47:37 -07001874void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001875 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001876NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001877{
1878 for (size_t i = 0; i < effectChains.size(); i++) {
Andy Hungf65f5a72023-08-29 12:19:17 -07001879 effectChains[i]->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001880 }
1881}
1882
Andy Hungee58e4a2023-07-07 13:47:37 -07001883sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001884{
Andy Hung972bec12023-08-31 16:13:39 -07001885 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001886 return getEffectChain_l(sessionId);
1887}
1888
Andy Hungee58e4a2023-07-07 13:47:37 -07001889sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001890 const
Eric Laurent81784c32012-11-19 14:55:58 -08001891{
1892 size_t size = mEffectChains.size();
1893 for (size_t i = 0; i < size; i++) {
1894 if (mEffectChains[i]->sessionId() == sessionId) {
1895 return mEffectChains[i];
1896 }
1897 }
1898 return 0;
1899}
1900
Andy Hungee58e4a2023-07-07 13:47:37 -07001901void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001902{
Andy Hung972bec12023-08-31 16:13:39 -07001903 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001904 size_t size = mEffectChains.size();
1905 for (size_t i = 0; i < size; i++) {
1906 mEffectChains[i]->setMode_l(mode);
1907 }
1908}
1909
Andy Hungee58e4a2023-07-07 13:47:37 -07001910void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001911{
1912 config->type = AUDIO_PORT_TYPE_MIX;
1913 config->ext.mix.handle = mId;
1914 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001915 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001916 config->channel_mask = mChannelMask;
1917 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1918 AUDIO_PORT_CONFIG_FORMAT;
1919}
1920
Andy Hungee58e4a2023-07-07 13:47:37 -07001921void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001922{
Andy Hung972bec12023-08-31 16:13:39 -07001923 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001924 if (mSystemReady) {
1925 return;
1926 }
1927 mSystemReady = true;
1928
1929 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1930 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1931 }
1932 mPendingConfigEvents.clear();
1933}
1934
Andy Hungdae27702016-10-31 14:01:16 -07001935template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001936ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001937 ssize_t index = mActiveTracks.indexOf(track);
1938 if (index >= 0) {
1939 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1940 return index;
1941 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001942 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001943 mActiveTracksGeneration++;
1944 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001945 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001946 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001947 return mActiveTracks.add(track);
1948}
1949
1950template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001951ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001952 ssize_t index = mActiveTracks.remove(track);
1953 if (index < 0) {
1954 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1955 return index;
1956 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001957 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001958 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001959 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001960 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001961 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001962#ifdef TEE_SINK
1963 track->dumpTee(-1 /* fd */, "_REMOVE");
1964#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001965 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001966 return index;
1967}
1968
1969template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001970void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001971 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001972 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001973 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001974 }
1975 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001976 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001977 mActiveTracks.clear();
1978 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001979}
1980
1981template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001982void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001983 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001984 // Updates ActiveTracks client uids to the thread wakelock.
1985 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1986 thread->updateWakeLockUids_l(getWakeLockUids());
1987 mLastActiveTracksGeneration = mActiveTracksGeneration;
1988 }
Andy Hungdae27702016-10-31 14:01:16 -07001989}
Eric Laurent83b88082014-06-20 18:31:16 -07001990
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001991template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001992bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001993 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001994 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001995
1996 for (const sp<T> &track : mActiveTracks) {
1997 // Do not short-circuit as all hasChanged states must be reset
1998 // as all the metadata are going to be sent
1999 hasChanged |= track->readAndClearHasChanged();
2000 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002001 return hasChanged;
2002}
2003
2004template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002005void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002006 const char *funcName, const sp<T> &track) const {
2007 if (mLocalLog != nullptr) {
2008 String8 result;
2009 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002010 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002011 }
2012}
2013
Andy Hungee58e4a2023-07-07 13:47:37 -07002014void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002015{
2016 // Thread could be blocked waiting for async
2017 // so signal it to handle state changes immediately
2018 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2019 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2020 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002021 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002022}
2023
Andy Hungd0979812019-02-21 15:51:44 -08002024// Call only from threadLoop() or when it is idle.
2025// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002026void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002027NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002028{
2029 // Do not log if we have no stats.
2030 // We choose the timestamp verifier because it is the most likely item to be present.
2031 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2032 if (nstats == 0) {
2033 return;
2034 }
2035
2036 // Don't log more frequently than once per 12 hours.
2037 // We use BOOTTIME to include suspend time.
2038 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2039 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2040 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2041 return;
2042 }
2043
2044 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2045 mLastRecordedTimeNs = timeNs;
2046
Ray Essickf27e9872019-12-07 06:28:46 -08002047 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002048
2049#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2050
2051 // thread configuration
2052 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2053 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2054 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2055 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2056 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2057 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2058 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002059 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2060 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002061
2062 // thread statistics
2063 if (mIoJitterMs.getN() > 0) {
2064 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2065 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2066 }
2067 if (mProcessTimeMs.getN() > 0) {
2068 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2069 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2070 }
2071 const auto tsjitter = mTimestampVerifier.getJitterMs();
2072 if (tsjitter.getN() > 0) {
2073 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2074 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2075 }
2076 if (mLatencyMs.getN() > 0) {
2077 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2078 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2079 }
Robert Wu06db0a32021-08-10 19:05:34 +00002080 if (mMonopipePipeDepthStats.getN() > 0) {
2081 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2082 mMonopipePipeDepthStats.getMean());
2083 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2084 mMonopipePipeDepthStats.getStdDev());
2085 }
Andy Hungd0979812019-02-21 15:51:44 -08002086
2087 item->selfrecord();
2088}
2089
Andy Hungee58e4a2023-07-07 13:47:37 -07002090product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002091{
Andy Hung583043b2023-07-17 17:05:00 -07002092 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002093 return PRODUCT_STRATEGY_NONE;
2094 }
2095 return AudioSystem::getStrategyForStream(stream);
2096}
2097
Andy Hungc5007f82023-08-29 14:26:09 -07002098// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002099void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002100 const sp<audio_utils::MelProcessor>& /*processor*/)
2101{
2102 // Do nothing
2103 ALOGW("%s: ThreadBase does not support CSD", __func__);
2104}
2105
Andy Hungc5007f82023-08-29 14:26:09 -07002106// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002107void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002108{
2109 // Do nothing
2110 ALOGW("%s: ThreadBase does not support CSD", __func__);
2111}
2112
Eric Laurent81784c32012-11-19 14:55:58 -08002113// ----------------------------------------------------------------------------
2114// Playback
2115// ----------------------------------------------------------------------------
2116
Andy Hung583043b2023-07-17 17:05:00 -07002117PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002118 AudioStreamOut* output,
2119 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002120 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002121 bool systemReady,
2122 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002123 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002124 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002125 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002126 mMixerBuffer(NULL),
2127 mMixerBufferSize(0),
2128 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2129 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002130 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002131 mEffectBuffer(NULL),
2132 mEffectBufferSize(0),
2133 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2134 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002135 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002136 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002137 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002138 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002139 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002140 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002141 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002142 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002143 mMixerStatus(MIXER_IDLE),
2144 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002145 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002146 mBytesRemaining(0),
2147 mCurrentWriteLength(0),
2148 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002149 mWriteAckSequence(0),
2150 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002151 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002152 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002153 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002154 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002155 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002156 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002157 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002158{
Glenn Kastend7dca052015-03-05 16:05:54 -08002159 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002160 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002161
Andy Hungc5007f82023-08-29 14:26:09 -07002162 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002163 // it would be safer to explicitly pass initial masterVolume/masterMute as
2164 // parameter.
2165 //
2166 // If the HAL we are using has support for master volume or master mute,
2167 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2168 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002169 mMasterVolume = afThreadCallback->masterVolume_l();
2170 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002171 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002172 if (mOutput->audioHwDev->canSetMasterVolume()) {
2173 mMasterVolume = 1.0;
2174 }
2175
2176 if (mOutput->audioHwDev->canSetMasterMute()) {
2177 mMasterMute = false;
2178 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002179 mIsMsdDevice = strcmp(
2180 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002181 }
2182
Eric Laurentf1f22e72021-07-13 14:04:14 +02002183 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2184 mMixerChannelMask = mixerConfig->channel_mask;
2185 }
2186
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002187 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002188
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002189 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002190 && mMixerChannelMask != mChannelMask) {
2191 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2192 mChannelMask, mMixerChannelMask);
2193 }
2194
Andy Hungc8fddf32018-08-08 18:32:37 -07002195 // TODO: We may also match on address as well as device type for
2196 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002197 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002198 // TODO: This property should be ensure that only contains one single device type.
2199 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2200 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002201 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2202 : AUDIO_DEVICE_NONE));
2203 }
2204
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002205 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2206 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002207 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002208 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002209 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002210 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002211 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2212 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002213 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2214 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002215}
2216
Andy Hungee58e4a2023-07-07 13:47:37 -07002217PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002218{
Andy Hung583043b2023-07-17 17:05:00 -07002219 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002220 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002221 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002222 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002223 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002224}
2225
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002226// Thread virtuals
2227
Andy Hungee58e4a2023-07-07 13:47:37 -07002228void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002229{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002230 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002231 ALOGE("The stream is not open yet"); // This should not happen.
2232 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002233 // Callbacks take strong or weak pointers as a parameter.
2234 // Since PlaybackThread passes itself as a callback handler, it can only
2235 // be done outside of the constructor. Creating weak and especially strong
2236 // pointers to a refcounted object in its own constructor is strongly
2237 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2238 // Even if a function takes a weak pointer, it is possible that it will
2239 // need to convert it to a strong pointer down the line.
2240 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2241 mOutput->stream->setCallback(this) == OK) {
2242 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002243 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002244 }
2245
jiabinf6eb4c32020-02-25 14:06:25 -08002246 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002247 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002248 }
2249 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002250 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002251 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002252}
2253
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002254// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002255void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002256{
2257 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002258 status_t result = mOutput->stream->exit();
2259 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002260}
2261
Andy Hungee58e4a2023-07-07 13:47:37 -07002262void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002263{
Eric Laurent81784c32012-11-19 14:55:58 -08002264 String8 result;
2265
Marco Nelissenb2208842014-02-07 14:00:50 -08002266 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002267 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2268 const stream_type_t *st = &mStreamTypes[i];
2269 if (i > 0) {
2270 result.appendFormat(", ");
2271 }
2272 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2273 if (st->mute) {
2274 result.append("M");
2275 }
2276 }
2277 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002278 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002279 result.clear();
2280
Eric Laurent81784c32012-11-19 14:55:58 -08002281 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2282 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002283 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002284 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002285
2286 size_t numtracks = mTracks.size();
2287 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002288 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002289 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002290 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002291 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002292 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002293 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002294 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002295 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002296 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002297 if (track != 0) {
2298 bool active = mActiveTracks.indexOf(track) >= 0;
2299 if (active) {
2300 numactiveseen++;
2301 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002302 result.append(prefix);
2303 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002304 }
2305 }
2306 } else {
2307 result.append("\n");
2308 }
2309 if (numactiveseen != numactive) {
2310 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002311 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002312 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002313 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002314 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002315 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002316 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002317 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002318 result.append(prefix);
2319 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002320 }
2321 }
2322 }
2323
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002324 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002325}
2326
Andy Hungee58e4a2023-07-07 13:47:37 -07002327void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002328{
Andy Hung04cb8f72020-03-20 13:44:33 -07002329 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002330 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002331 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2332 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002333 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2334 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2335 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2336 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002337 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002338 dprintf(fd, " Total writes: %d\n", mNumWrites);
2339 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2340 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002341 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002342 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002343 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002344 AudioStreamOut *output = mOutput;
2345 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002346 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002347 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002348 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2349 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2350 if (mPipeSink.get() != nullptr) {
2351 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2352 }
2353 if (output != nullptr) {
2354 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002355 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002356 }
Eric Laurent81784c32012-11-19 14:55:58 -08002357}
2358
Andy Hungc5007f82023-08-29 14:26:09 -07002359// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002360sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002361 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002362 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002363 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002364 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002365 audio_format_t format,
2366 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002367 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002368 size_t *pNotificationFrameCount,
2369 uint32_t notificationsPerBuffer,
2370 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002371 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002372 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002373 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002374 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002375 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002376 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002377 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002378 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002379 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002380 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002381 bool isBitPerfect,
2382 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002383{
Glenn Kasten74935e42013-12-19 08:56:45 -08002384 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002385 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002386 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002387 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002388 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002389 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002390 uint32_t sampleRate;
2391
2392 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2393 lStatus = BAD_VALUE;
2394 goto Exit;
2395 }
Eric Laurent21da6472017-11-09 16:29:26 -08002396
2397 if (*pSampleRate == 0) {
2398 *pSampleRate = mSampleRate;
2399 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002400 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002401
2402 // special case for FAST flag considered OK if fast mixer is present
2403 if (hasFastMixer()) {
2404 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2405 }
2406
2407 // Check if requested flags are compatible with output stream flags
2408 if ((*flags & outputFlags) != *flags) {
2409 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2410 *flags, outputFlags);
2411 *flags = (audio_output_flags_t)(*flags & outputFlags);
2412 }
Eric Laurent81784c32012-11-19 14:55:58 -08002413
jiabinc658e452022-10-21 20:52:21 +00002414 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002415 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002416 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002417 if (chain.get() != nullptr) {
2418 // Bit-perfect is required according to the configuration and preferred mixer
2419 // attributes, but it is not in the output flag from the client's request. Explicitly
2420 // adding bit-perfect flag to check the compatibility
2421 audio_output_flags_t flagsToCheck =
2422 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2423 chain->checkOutputFlagCompatibility(&flagsToCheck);
2424 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2425 ALOGE("%s cannot create track as there is data-processing effect attached to "
2426 "given session id(%d)", __func__, sessionId);
2427 lStatus = BAD_VALUE;
2428 goto Exit;
2429 }
2430 *flags = flagsToCheck;
2431 }
2432 }
2433
Eric Laurent81784c32012-11-19 14:55:58 -08002434 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002435 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002436 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // PCM data
2438 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002439 // TODO: extract as a data library function that checks that a computationally
2440 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002441 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002442 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2443 (channelMask == AUDIO_CHANNEL_OUT_MONO
2444 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // hardware sample rate
2446 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002447 // normal mixer has an associated fast mixer
2448 hasFastMixer() &&
2449 // there are sufficient fast track slots available
2450 (mFastTrackAvailMask != 0)
2451 // FIXME test that MixerThread for this fast track has a capable output HAL
2452 // FIXME add a permission test also?
2453 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002454 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2455 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002456 // read the fast track multiplier property the first time it is needed
2457 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2458 if (ok != 0) {
2459 ALOGE("%s pthread_once failed: %d", __func__, ok);
2460 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002461 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002462 }
Eric Laurent4c415062016-06-17 16:14:16 -07002463
2464 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002465 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002466 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002467 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002468 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002469 AUDIO_SESSION_OUTPUT_STAGE,
2470 AUDIO_SESSION_OUTPUT_MIX,
2471 sessionId,
2472 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002473 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002474 if (chain.get() != nullptr) {
2475 audio_output_flags_t old = *flags;
2476 chain->checkOutputFlagCompatibility(flags);
2477 if (old != *flags) {
2478 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2479 (int)session, (int)old, (int)*flags);
2480 }
Eric Laurent4c415062016-06-17 16:14:16 -07002481 }
2482 }
2483 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002484 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002485 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2486 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002487 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002488 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002489 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002490 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002491 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002492 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002493 audio_is_linear_pcm(format), channelMask, sampleRate,
2494 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002495 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002496 }
2497 }
Eric Laurent21da6472017-11-09 16:29:26 -08002498
2499 if (!audio_has_proportional_frames(format)) {
2500 if (sharedBuffer != 0) {
2501 // Same comment as below about ignoring frameCount parameter for set()
2502 frameCount = sharedBuffer->size();
2503 } else if (frameCount == 0) {
2504 frameCount = mNormalFrameCount;
2505 }
2506 if (notificationFrameCount != frameCount) {
2507 notificationFrameCount = frameCount;
2508 }
2509 } else if (sharedBuffer != 0) {
2510 // FIXME: Ensure client side memory buffers need
2511 // not have additional alignment beyond sample
2512 // (e.g. 16 bit stereo accessed as 32 bit frame).
2513 size_t alignment = audio_bytes_per_sample(format);
2514 if (alignment & 1) {
2515 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2516 alignment = 1;
2517 }
2518 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2519 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2520 if (channelCount > 1) {
2521 // More than 2 channels does not require stronger alignment than stereo
2522 alignment <<= 1;
2523 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002524 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002525 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002526 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002527 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002528 goto Exit;
2529 }
Eric Laurent21da6472017-11-09 16:29:26 -08002530
2531 // When initializing a shared buffer AudioTrack via constructors,
2532 // there's no frameCount parameter.
2533 // But when initializing a shared buffer AudioTrack via set(),
2534 // there _is_ a frameCount parameter. We silently ignore it.
2535 frameCount = sharedBuffer->size() / frameSize;
2536 } else {
2537 size_t minFrameCount = 0;
2538 // For fast tracks we try to respect the application's request for notifications per buffer.
2539 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2540 if (notificationsPerBuffer > 0) {
2541 // Avoid possible arithmetic overflow during multiplication.
2542 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2543 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2544 notificationsPerBuffer, mFrameCount);
2545 } else {
2546 minFrameCount = mFrameCount * notificationsPerBuffer;
2547 }
2548 }
2549 } else {
2550 // For normal PCM streaming tracks, update minimum frame count.
2551 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2552 // cover audio hardware latency.
2553 // This is probably too conservative, but legacy application code may depend on it.
2554 // If you change this calculation, also review the start threshold which is related.
2555 uint32_t latencyMs = latency_l();
2556 if (latencyMs == 0) {
2557 ALOGE("Error when retrieving output stream latency");
2558 lStatus = UNKNOWN_ERROR;
2559 goto Exit;
2560 }
2561
2562 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2563 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2564
Eric Laurent81784c32012-11-19 14:55:58 -08002565 }
Eric Laurent21da6472017-11-09 16:29:26 -08002566 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002567 frameCount = minFrameCount;
2568 }
Eric Laurent81784c32012-11-19 14:55:58 -08002569 }
Eric Laurent21da6472017-11-09 16:29:26 -08002570
2571 // Make sure that application is notified with sufficient margin before underrun.
2572 // The client can divide the AudioTrack buffer into sub-buffers,
2573 // and expresses its desire to server as the notification frame count.
2574 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2575 size_t maxNotificationFrames;
2576 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2577 // notify every HAL buffer, regardless of the size of the track buffer
2578 maxNotificationFrames = mFrameCount;
2579 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002580 // Triple buffer the notification period for a triple buffered mixer period;
2581 // otherwise, double buffering for the notification period is fine.
2582 //
2583 // TODO: This should be moved to AudioTrack to modify the notification period
2584 // on AudioTrack::setBufferSizeInFrames() changes.
2585 const int nBuffering =
2586 (uint64_t{frameCount} * mSampleRate)
2587 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2588
Eric Laurent21da6472017-11-09 16:29:26 -08002589 maxNotificationFrames = frameCount / nBuffering;
2590 // If client requested a fast track but this was denied, then use the smaller maximum.
2591 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2592 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2593 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2594 maxNotificationFrames = maxNotificationFramesFastDenied;
2595 }
2596 }
2597 }
2598 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2599 if (notificationFrameCount == 0) {
2600 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2601 maxNotificationFrames, frameCount);
2602 } else {
2603 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2604 notificationFrameCount, maxNotificationFrames, frameCount);
2605 }
2606 notificationFrameCount = maxNotificationFrames;
2607 }
2608 }
2609
Glenn Kasten74935e42013-12-19 08:56:45 -08002610 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002611 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002612
Glenn Kastenc3df8382014-03-13 15:05:25 -07002613 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002614 case BIT_PERFECT:
2615 if (isBitPerfect) {
2616 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2617 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2618 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2619 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2620 mChannelMask);
2621 lStatus = BAD_VALUE;
2622 goto Exit;
2623 }
2624 }
2625 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002626
2627 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002628 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002629 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002630 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2631 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002632 sampleRate, format, channelMask, mOutput, mFormat);
2633 lStatus = BAD_VALUE;
2634 goto Exit;
2635 }
2636 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002637 break;
2638
2639 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002640 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002641 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2642 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 sampleRate, format, channelMask, mOutput, mFormat);
2644 lStatus = BAD_VALUE;
2645 goto Exit;
2646 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002647 break;
2648
2649 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002650 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002651 ALOGE("createTrack_l() Bad parameter: format %#x \""
2652 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 format, mOutput, mFormat);
2654 lStatus = BAD_VALUE;
2655 goto Exit;
2656 }
Andy Hungcd044842014-08-07 11:04:34 -07002657 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002658 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2659 lStatus = BAD_VALUE;
2660 goto Exit;
2661 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002662 break;
2663
Eric Laurent81784c32012-11-19 14:55:58 -08002664 }
2665
2666 lStatus = initCheck();
2667 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002668 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002669 goto Exit;
2670 }
2671
Andy Hungc5007f82023-08-29 14:26:09 -07002672 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002673 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002674
2675 // all tracks in same audio session must share the same routing strategy otherwise
2676 // conflicts will happen when tracks are moved from one output to another by audio policy
2677 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002678 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002679 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002680 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002681 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002682 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002683 if (sessionId == t->sessionId() && strategy != actual) {
2684 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2685 strategy, actual);
2686 lStatus = BAD_VALUE;
2687 goto Exit;
2688 }
2689 }
2690 }
2691
yucliuc9c49cd2020-07-13 16:25:21 -07002692 // Set DIRECT flag if current thread is DirectOutputThread. This can
2693 // happen when the playback is rerouted to direct output thread by
2694 // dynamic audio policy.
2695 // Do NOT report the flag changes back to client, since the client
2696 // doesn't explicitly request a direct flag.
2697 audio_output_flags_t trackFlags = *flags;
2698 if (mType == DIRECT) {
2699 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2700 }
jiabin94ed47c2023-07-27 23:34:20 +00002701 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002702
Andy Hung8d31fd22023-06-26 19:20:57 -07002703 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002704 channelMask, frameCount,
2705 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002706 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002707 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002708 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002709
Glenn Kasten03003332013-08-06 15:40:54 -07002710 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2711 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002712 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002713 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002714 goto Exit;
2715 }
2716 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002717 {
Andy Hung972bec12023-08-31 16:13:39 -07002718 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002719 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002720 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002721 }
2722 }
Eric Laurent81784c32012-11-19 14:55:58 -08002723
Andy Hung116bc262023-06-20 18:56:17 -07002724 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002725 if (chain != 0) {
2726 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2727 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002728 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002729 chain->incTrackCnt();
2730 }
2731
Eric Laurent05067782016-06-01 18:27:28 -07002732 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002733 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2734 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2735 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002736 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002737 }
2738 }
2739
2740 lStatus = NO_ERROR;
2741
2742Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002743 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002744 return track;
2745}
2746
Andy Hung1bc088a2018-02-09 15:57:31 -08002747template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002748ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002749{
Andy Hungc0691382018-09-12 18:01:57 -07002750 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002751 const ssize_t index = mTracks.remove(track);
2752 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002753 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002754 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002755 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002756 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002757 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002758 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002759 }
2760 return index;
2761}
2762
Andy Hungee58e4a2023-07-07 13:47:37 -07002763uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002764{
2765 return latency;
2766}
2767
Andy Hungee58e4a2023-07-07 13:47:37 -07002768uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002769{
Andy Hung972bec12023-08-31 16:13:39 -07002770 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002771 return latency_l();
2772}
Andy Hungee58e4a2023-07-07 13:47:37 -07002773uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002774NO_THREAD_SAFETY_ANALYSIS
2775// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002776{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002777 uint32_t latency;
2778 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2779 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002780 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002781 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002782}
2783
Andy Hungee58e4a2023-07-07 13:47:37 -07002784void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002785{
Andy Hung972bec12023-08-31 16:13:39 -07002786 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002787 // Don't apply master volume in SW if our HAL can do it for us.
2788 if (mOutput && mOutput->audioHwDev &&
2789 mOutput->audioHwDev->canSetMasterVolume()) {
2790 mMasterVolume = 1.0;
2791 } else {
2792 mMasterVolume = value;
2793 }
2794}
2795
Andy Hungee58e4a2023-07-07 13:47:37 -07002796void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002797{
2798 mMasterBalance.store(balance);
2799}
2800
Andy Hungee58e4a2023-07-07 13:47:37 -07002801void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002802{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002803 if (isDuplicating()) {
2804 return;
2805 }
Andy Hung972bec12023-08-31 16:13:39 -07002806 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002807 // Don't apply master mute in SW if our HAL can do it for us.
2808 if (mOutput && mOutput->audioHwDev &&
2809 mOutput->audioHwDev->canSetMasterMute()) {
2810 mMasterMute = false;
2811 } else {
2812 mMasterMute = muted;
2813 }
2814}
2815
Andy Hungee58e4a2023-07-07 13:47:37 -07002816void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002817{
Andy Hung972bec12023-08-31 16:13:39 -07002818 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002819 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002820 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002821}
2822
Andy Hungee58e4a2023-07-07 13:47:37 -07002823void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002824{
Andy Hung972bec12023-08-31 16:13:39 -07002825 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002826 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002827 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002828}
2829
Andy Hungee58e4a2023-07-07 13:47:37 -07002830float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002831{
Andy Hung972bec12023-08-31 16:13:39 -07002832 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002833 return mStreamTypes[stream].volume;
2834}
2835
Andy Hungee58e4a2023-07-07 13:47:37 -07002836void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002837{
2838 mOutput->stream->setVolume(left, right);
2839}
2840
Andy Hungc5007f82023-08-29 14:26:09 -07002841// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002842status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002843{
2844 status_t status = ALREADY_EXISTS;
2845
Eric Laurent81784c32012-11-19 14:55:58 -08002846 if (mActiveTracks.indexOf(track) < 0) {
2847 // the track is newly added, make sure it fills up all its
2848 // buffers before playing. This is to ensure the client will
2849 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002850 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002851 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002852 // Because the track is not on the ActiveTracks,
2853 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002854 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002855 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002856 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002857 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002858 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002859 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002860 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002861 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002862 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 }
2864 return INVALID_OPERATION;
2865 }
2866 // abort if start is rejected by audio policy manager
2867 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002868 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2869 // current playback thread is reopened, which may happen when clients set preferred
2870 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2871 // immediately.
2872 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873 }
2874#ifdef ADD_BATTERY_DATA
2875 // to track the speaker usage
2876 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2877#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002878 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879 }
2880
Eric Laurent51716182016-02-29 18:00:56 -08002881 // set retry count for buffer fill
2882 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002883 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002884 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002885 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002886 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002887 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002888 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002889 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002890 track->retryCount() = kMaxTrackStartupRetries;
2891 track->fillingStatus() =
2892 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002893 }
2894
Andy Hung116bc262023-06-20 18:56:17 -07002895 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002896 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2897 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2898 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002899 // Unlock due to VibratorService will lock for this call and will
2900 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002901 mutex().unlock();
Andy Hung7fb97e12023-07-20 21:23:42 -07002902 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002903 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002904 std::optional<media::AudioVibratorInfo> vibratorInfo;
2905 {
2906 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2907 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002908 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002909 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002910 }
Andy Hungc5007f82023-08-29 14:26:09 -07002911 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002912 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002913 if (vibratorInfo) {
2914 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2915 }
2916
jiabin57303cc2018-12-18 15:45:57 -08002917 // Haptic playback should be enabled by vibrator service.
2918 if (track->getHapticPlaybackEnabled()) {
2919 // Disable haptic playback of all active track to ensure only
2920 // one track playing haptic if current track should play haptic.
2921 for (const auto &t : mActiveTracks) {
2922 t->setHapticPlaybackEnabled(false);
2923 }
jiabin245cdd92018-12-07 17:55:15 -08002924 }
jiabine70bc7f2020-06-30 22:07:55 -07002925
2926 // Set haptic intensity for effect
2927 if (chain != nullptr) {
2928 chain->setHapticIntensity_l(track->id(), intensity);
2929 }
jiabin245cdd92018-12-07 17:55:15 -08002930 }
2931
Andy Hung8d31fd22023-06-26 19:20:57 -07002932 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002933 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002934
2935 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2936 // all key changes are complete. It is possible that the threadLoop will begin
2937 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002938 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002939
Eric Laurentd0107bc2013-06-11 14:38:48 -07002940 if (chain != 0) {
2941 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2942 track->sessionId());
2943 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002944 }
2945
Andy Hungc2b11cb2020-04-22 09:04:01 -07002946 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002947 status = NO_ERROR;
2948 }
2949
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002950 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002951 return status;
2952}
2953
Andy Hungee58e4a2023-07-07 13:47:37 -07002954bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002955{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002957 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002959 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002961 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002962 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002963 if (track->isPausePending()) {
2964 track->pauseAck();
2965 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002966 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002967 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002968
2969 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002970}
2971
Andy Hungee58e4a2023-07-07 13:47:37 -07002972void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002973{
2974 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002975
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002976 String8 result;
2977 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002978 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002979
Eric Laurent81784c32012-11-19 14:55:58 -08002980 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002981 {
Andy Hung972bec12023-08-31 16:13:39 -07002982 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002983 mAudioTrackCallbacks.erase(track);
2984 }
Eric Laurent81784c32012-11-19 14:55:58 -08002985 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002986 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002987 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002988 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2989 mFastTrackAvailMask |= 1 << index;
2990 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002991 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002992 }
Andy Hung116bc262023-06-20 18:56:17 -07002993 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002994 if (chain != 0) {
2995 chain->decTrackCnt();
2996 }
2997}
2998
Andy Hungee58e4a2023-07-07 13:47:37 -07002999String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003000{
Andy Hung972bec12023-08-31 16:13:39 -07003001 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003002 String8 out_s8;
3003 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3004 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003005 }
Andy Hung920f6572022-10-06 12:09:49 -07003006 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003007}
3008
Andy Hungee58e4a2023-07-07 13:47:37 -07003009status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003010 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003011 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003012 return NO_INIT;
3013 }
3014 return mOutput->stream->selectPresentation(presentationId, programId);
3015}
3016
Andy Hungab65b182023-09-06 19:41:47 -07003017void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003018 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003019 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003020 sp<AudioIoDescriptor> desc;
3021 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003022 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003023 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003024 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003025 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003026 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3027 mSampleRate, mFormat, mChannelMask,
3028 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3029 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003030 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003031 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003032 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003033 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003034 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003035 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003036 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003037 break;
3038 }
Andy Hungab65b182023-09-06 19:41:47 -07003039 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003040}
3041
Andy Hungee58e4a2023-07-07 13:47:37 -07003042void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003043{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003044 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045}
3046
Andy Hungee58e4a2023-07-07 13:47:37 -07003047void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003048{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003049 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003050}
3051
Andy Hungee58e4a2023-07-07 13:47:37 -07003052void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003053{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003054 mCallbackThread->setAsyncError();
3055}
3056
Andy Hungee58e4a2023-07-07 13:47:37 -07003057void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003058 const std::basic_string<uint8_t>& metadataBs)
3059{
Andy Hungee58e4a2023-07-07 13:47:37 -07003060 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003061 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003062 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003063 if (playbackThread == nullptr) {
3064 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3065 return;
3066 }
3067
jiabinf6eb4c32020-02-25 14:06:25 -08003068 audio_utils::metadata::Data metadata =
3069 audio_utils::metadata::dataFromByteString(metadataBs);
3070 if (metadata.empty()) {
3071 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3072 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3073 (int)metadataBs.size());
3074 return;
3075 }
3076
3077 audio_utils::metadata::ByteString metaDataStr =
3078 audio_utils::metadata::byteStringFromData(metadata);
3079 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003080 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003081 for (const auto& callbackPair : mAudioTrackCallbacks) {
3082 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003083 }
3084 }).detach();
3085}
3086
Andy Hungee58e4a2023-07-07 13:47:37 -07003087void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088{
Andy Hung972bec12023-08-31 16:13:39 -07003089 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003090 // reject out of sequence requests
3091 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3092 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003093 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094 }
3095}
3096
Andy Hungee58e4a2023-07-07 13:47:37 -07003097void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098{
Andy Hung972bec12023-08-31 16:13:39 -07003099 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003100 // reject out of sequence requests
3101 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003102 // Register discontinuity when HW drain is completed because that can cause
3103 // the timestamp frame position to reset to 0 for direct and offload threads.
3104 // (Out of sequence requests are ignored, since the discontinuity would be handled
3105 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003106 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003107 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003108 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109 }
3110}
3111
Andy Hungee58e4a2023-07-07 13:47:37 -07003112void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003113NO_THREAD_SAFETY_ANALYSIS
3114// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003115{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003116 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003117 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3118 mSampleRate = audioConfig.sample_rate;
3119 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003120 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003121 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003122 }
Andy Hung81994d62023-07-20 21:44:14 -07003123 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003124 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3125 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003126 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003127
3128 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3129 mMixerChannelMask = mChannelMask;
3130 }
3131
Andy Hunge5412692014-05-16 11:25:07 -07003132 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003133 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003134
Eric Laurentf1f22e72021-07-13 14:04:14 +02003135 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3136
Phil Burkca5e6142015-07-14 09:42:29 -07003137 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003138 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003139 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003140 // Get format from the shim, which will be different than the HAL format
3141 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003142 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003143 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003144 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003145 }
Andy Hung81994d62023-07-20 21:44:14 -07003146 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003147 LOG_FATAL("HAL format %#x not supported for mixed output",
3148 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003149 }
Phil Burk062e67a2015-02-11 13:40:50 -08003150 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003151 result = mOutput->stream->getBufferSize(&mBufferSize);
3152 LOG_ALWAYS_FATAL_IF(result != OK,
3153 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003154 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003155 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003156 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003157 mFrameCount);
3158 }
3159
Eric Laurentd1f69b02014-12-15 14:33:13 -08003160 mHwSupportsPause = false;
3161 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003162 bool supportsPause = false, supportsResume = false;
3163 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3164 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003165 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003166 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003167 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003168 } else if (supportsResume) {
3169 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003170 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003171 }
3172 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003173 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3174 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3175 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003176
Andy Hungfbfc3952015-01-15 13:33:51 -08003177 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3178 // For best precision, we use float instead of the associated output
3179 // device format (typically PCM 16 bit).
3180
3181 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3182 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3183 mBufferSize = mFrameSize * mFrameCount;
3184
3185 // TODO: We currently use the associated output device channel mask and sample rate.
3186 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3187 // (if a valid mask) to avoid premature downmix.
3188 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3189 // instead of the output device sample rate to avoid loss of high frequency information.
3190 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3191 }
3192
Andy Hung09a50072014-02-27 14:30:47 -08003193 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003194 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003195 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003196 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3197 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003198 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3199 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003200
Eric Laurent81784c32012-11-19 14:55:58 -08003201 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3202 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3203 maxNormalFrameCount = maxNormalFrameCount & ~15;
3204 if (maxNormalFrameCount < minNormalFrameCount) {
3205 maxNormalFrameCount = minNormalFrameCount;
3206 }
3207 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3208 if (multiplier <= 1.0) {
3209 multiplier = 1.0;
3210 } else if (multiplier <= 2.0) {
3211 if (2 * mFrameCount <= maxNormalFrameCount) {
3212 multiplier = 2.0;
3213 } else {
3214 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3215 }
3216 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003217 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003218 }
3219 }
3220 mNormalFrameCount = multiplier * mFrameCount;
3221 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003222 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003223 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3224 }
Andy Hungab65b182023-09-06 19:41:47 -07003225 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3226 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003227
Andy Hung08fb1742015-05-31 23:22:10 -07003228 // Check if we want to throttle the processing to no more than 2x normal rate
3229 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003230 mThreadThrottleTimeMs = 0;
3231 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003232 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3233
Andy Hung010a1a12014-03-13 13:57:33 -07003234 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3235 // Originally this was int16_t[] array, need to remove legacy implications.
3236 free(mSinkBuffer);
3237 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003238
Andy Hung5b10a202014-03-13 13:59:29 -07003239 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3240 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3241 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003242 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003243
Andy Hung69aed5f2014-02-25 17:24:40 -08003244 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3245 // drives the output.
3246 free(mMixerBuffer);
3247 mMixerBuffer = NULL;
3248 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003249 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003250 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003251 * audio_bytes_per_sample(mMixerBufferFormat);
3252 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3253 }
Andy Hung98ef9782014-03-04 14:46:50 -08003254 free(mEffectBuffer);
3255 mEffectBuffer = NULL;
3256 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003257 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003258 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003259 * audio_bytes_per_sample(mEffectBufferFormat);
3260 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3261 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003262
Eric Laurentb62d0362021-10-26 17:40:18 +02003263 if (mType == SPATIALIZER) {
3264 free(mPostSpatializerBuffer);
3265 mPostSpatializerBuffer = nullptr;
3266 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3267 * audio_bytes_per_sample(mEffectBufferFormat);
3268 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3269 }
3270
Mikhail Naganov55773032020-10-01 15:08:13 -07003271 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3272 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003273 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3274 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003275 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003276
Eric Laurent81784c32012-11-19 14:55:58 -08003277 // force reconfiguration of effect chains and engines to take new buffer size and audio
3278 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003279 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003280 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3281 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003282 // create a copy of mEffectChains as calling moveEffectChain_ll()
3283 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003284 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003285 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003286 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003287 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003288 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003289
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003290 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003291 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003292 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003293 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003294 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3295 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3296 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3297 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3298 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3299 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3300 (int32_t)mHapticChannelMask)
3301 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3302 (int32_t)mHapticChannelCount)
3303 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003304 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003305 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3306 (int32_t)mFrameCount) // sic - added HAL
3307 ;
3308 uint32_t latencyMs;
3309 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3310 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3311 }
3312 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003313}
3314
Andy Hungee58e4a2023-07-07 13:47:37 -07003315ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003316{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003317 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003318 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003319 }
3320 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003321 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07003322 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003323 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003324 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003325 }
Kevin Rocard12381092018-04-11 09:19:59 -07003326 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003327 MetadataUpdate change;
3328 change.playbackMetadataUpdate = metadata.tracks;
3329 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003330}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003331
Andy Hungee58e4a2023-07-07 13:47:37 -07003332void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003333 const StreamOutHalInterface::SourceMetadata& metadata)
3334{
3335 mOutput->stream->updateSourceMetadata(metadata);
3336};
3337
Andy Hungee58e4a2023-07-07 13:47:37 -07003338status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003339 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003340{
3341 if (halFrames == NULL || dspFrames == NULL) {
3342 return BAD_VALUE;
3343 }
Andy Hung972bec12023-08-31 16:13:39 -07003344 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003345 if (initCheck() != NO_ERROR) {
3346 return INVALID_OPERATION;
3347 }
Andy Hung818e7a32016-02-16 18:08:07 -08003348 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003349 *halFrames = framesWritten;
3350
3351 if (isSuspended()) {
3352 // return an estimation of rendered frames when the output is suspended
3353 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003354 *dspFrames = (uint32_t)
3355 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003356 return NO_ERROR;
3357 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003358 status_t status;
3359 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003360 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003361 *dspFrames = (size_t)frames;
3362 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003363 }
3364}
3365
Andy Hungee58e4a2023-07-07 13:47:37 -07003366product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003367{
3368 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3369 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3370 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003371 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003372 }
3373 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003374 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003375 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003376 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003377 }
3378 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003379 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003380}
3381
3382
Andy Hungee58e4a2023-07-07 13:47:37 -07003383AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003384{
Andy Hung972bec12023-08-31 16:13:39 -07003385 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003386 return mOutput;
3387}
3388
Andy Hungee58e4a2023-07-07 13:47:37 -07003389AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003390{
Andy Hung972bec12023-08-31 16:13:39 -07003391 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003392 AudioStreamOut *output = mOutput;
3393 mOutput = NULL;
3394 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3395 // must push a NULL and wait for ack
3396 mOutputSink.clear();
3397 mPipeSink.clear();
3398 mNormalSink.clear();
3399 return output;
3400}
3401
Andy Hungc5007f82023-08-29 14:26:09 -07003402// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003403sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003404{
3405 if (mOutput == NULL) {
3406 return NULL;
3407 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003408 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003409}
3410
Andy Hungee58e4a2023-07-07 13:47:37 -07003411uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003412{
3413 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3414}
3415
Andy Hungee58e4a2023-07-07 13:47:37 -07003416status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003417{
3418 if (!isValidSyncEvent(event)) {
3419 return BAD_VALUE;
3420 }
3421
Andy Hung972bec12023-08-31 16:13:39 -07003422 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003423
3424 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003425 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003426 if (event->triggerSession() == track->sessionId()) {
3427 (void) track->setSyncEvent(event);
3428 return NO_ERROR;
3429 }
3430 }
3431
3432 return NAME_NOT_FOUND;
3433}
3434
Andy Hungee58e4a2023-07-07 13:47:37 -07003435bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003436{
3437 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3438}
3439
Andy Hungee58e4a2023-07-07 13:47:37 -07003440void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003441 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003442{
Andy Hungfe726a62018-09-27 15:17:25 -07003443 // Miscellaneous track cleanup when removed from the active list,
3444 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003445#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003446 for (const auto& track : tracksToRemove) {
3447 if (track->isExternalTrack()) {
3448 // to track the speaker usage
3449 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003450 }
3451 }
Andy Hungfe726a62018-09-27 15:17:25 -07003452#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003453}
3454
Andy Hungee58e4a2023-07-07 13:47:37 -07003455void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003456{
3457 if (!mMasterMute) {
3458 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003459 if (mOutDeviceTypeAddrs.empty()) {
3460 ALOGD("ro.audio.silent is ignored since no output device is set");
3461 return;
3462 }
Andy Hungab65b182023-09-06 19:41:47 -07003463 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003464 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3465 return;
3466 }
Eric Laurent81784c32012-11-19 14:55:58 -08003467 if (property_get("ro.audio.silent", value, "0") > 0) {
3468 char *endptr;
3469 unsigned long ul = strtoul(value, &endptr, 0);
3470 if (*endptr == '\0' && ul != 0) {
3471 ALOGD("Silence is golden");
3472 // The setprop command will not allow a property to be changed after
3473 // the first time it is set, so we don't have to worry about un-muting.
3474 setMasterMute_l(true);
3475 }
3476 }
3477 }
3478}
3479
3480// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003481ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003482{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003483 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003484 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003485 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003486 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003487
3488 // If an NBAIO sink is present, use it to write the normal mixer's submix
3489 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003490
Andy Hung010a1a12014-03-13 13:57:33 -07003491 const size_t count = mBytesRemaining / mFrameSize;
3492
Simon Wilson2d590962012-11-29 15:18:50 -08003493 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003494 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003495 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003496 if (screenState != mScreenState) {
3497 mScreenState = screenState;
3498 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3499 if (pipe != NULL) {
3500 pipe->setAvgFrames((mScreenState & 1) ?
3501 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3502 }
3503 }
Andy Hung010a1a12014-03-13 13:57:33 -07003504 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003505 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003506
Eric Laurent81784c32012-11-19 14:55:58 -08003507 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003508 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003509
Andy Hung8946a282018-04-19 20:04:56 -07003510#ifdef TEE_SINK
3511 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3512#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003513 } else {
3514 bytesWritten = framesWritten;
3515 }
3516 // otherwise use the HAL / AudioStreamOut directly
3517 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003519
Eric Laurentbfb1b832013-01-07 09:53:42 -08003520 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003521 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3522 mWriteAckSequence += 2;
3523 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003524 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003525 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003527 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003528 // FIXME We should have an implementation of timestamps for direct output threads.
3529 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003530 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003531 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003532
Eric Laurentbfb1b832013-01-07 09:53:42 -08003533 if (mUseAsyncWrite &&
3534 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3535 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003536 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003537 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003538 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003539 }
Eric Laurent81784c32012-11-19 14:55:58 -08003540 }
3541
Eric Laurent81784c32012-11-19 14:55:58 -08003542 mNumWrites++;
3543 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003544 if (mStandby) {
3545 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003546 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003547 mStandby = false;
3548 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549 return bytesWritten;
3550}
3551
Andy Hungc5007f82023-08-29 14:26:09 -07003552// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003553void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003554 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003555{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003556 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003557 if (outputSink != nullptr) {
3558 outputSink->startMelComputation(processor);
3559 }
Vlad Popab042ee62022-10-20 18:05:00 +02003560}
3561
Andy Hungc5007f82023-08-29 14:26:09 -07003562// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003563void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003564{
3565 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003566 if (outputSink != nullptr) {
3567 outputSink->stopMelComputation();
3568 }
Vlad Popab042ee62022-10-20 18:05:00 +02003569}
3570
Andy Hungee58e4a2023-07-07 13:47:37 -07003571void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003572{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003573 bool supportsDrain = false;
3574 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003575 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3576 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003577 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3578 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003579 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003580 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003581 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003582 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003583 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003584 }
3585}
3586
Andy Hungee58e4a2023-07-07 13:47:37 -07003587void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003588{
Eric Laurent275e8e92014-11-30 15:14:47 -08003589 {
Andy Hung972bec12023-08-31 16:13:39 -07003590 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003591 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003592 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003593 track->invalidate();
3594 }
Andy Hungdae27702016-10-31 14:01:16 -07003595 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3596 // After we exit there are no more track changes sent to BatteryNotifier
3597 // because that requires an active threadLoop.
3598 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3599 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003600 }
Eric Laurent81784c32012-11-19 14:55:58 -08003601}
3602
3603/*
3604The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003605 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003606 - mActiveSleepTimeUs from activeSleepTimeUs()
3607 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003608 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3609 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003610 - maxPeriod from frame count and sample rate (MIXER only)
3611
3612The parameters that affect these derived values are:
3613 - frame count
3614 - frame size
3615 - sample rate
3616 - device type: A2DP or not
3617 - device latency
3618 - format: PCM or not
3619 - active sleep time
3620 - idle sleep time
3621*/
3622
Andy Hungee58e4a2023-07-07 13:47:37 -07003623void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003624{
Andy Hung25c2dac2014-02-27 14:56:00 -08003625 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003626 mActiveSleepTimeUs = activeSleepTimeUs();
3627 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003628
Andy Hung8fe87eb2023-07-20 21:31:38 -07003629 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003630
Eric Laurent42537be2016-01-08 17:16:42 -08003631 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3632 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003633 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003634 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3635 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3636 }
3637 }
Eric Laurent81784c32012-11-19 14:55:58 -08003638}
3639
Andy Hungee58e4a2023-07-07 13:47:37 -07003640bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003641{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003642 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003643 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003644 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003645 size_t size = mTracks.size();
3646 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003647 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003648 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003649 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003650 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003651 }
3652 }
Eric Laurent13084622016-05-17 10:51:49 -07003653 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003654}
3655
Andy Hungee58e4a2023-07-07 13:47:37 -07003656void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003657{
Andy Hung972bec12023-08-31 16:13:39 -07003658 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003659 invalidateTracks_l(streamType);
3660}
3661
Andy Hungee58e4a2023-07-07 13:47:37 -07003662void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003663 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003664 invalidateTracks_l(portIds);
3665}
3666
Andy Hungee58e4a2023-07-07 13:47:37 -07003667bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003668 bool trackMatch = false;
3669 const size_t size = mTracks.size();
3670 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003671 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003672 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3673 t->invalidate();
3674 portIds.erase(t->portId());
3675 trackMatch = true;
3676 }
3677 if (portIds.empty()) {
3678 break;
3679 }
3680 }
3681 return trackMatch;
3682}
3683
jiabinf042b9b2021-05-07 23:46:28 +00003684// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003685IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003686 audio_port_handle_t trackPortId) {
3687 for (size_t i = 0; i < mTracks.size(); i++) {
3688 if (mTracks[i]->portId() == trackPortId) {
3689 return mTracks[i].get();
3690 }
3691 }
3692 return nullptr;
3693}
3694
Andy Hungee58e4a2023-07-07 13:47:37 -07003695status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003696{
Glenn Kastend848eb42016-03-08 13:42:11 -08003697 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003698 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003699 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003700
Andy Hungd3639922022-04-28 18:00:49 -07003701 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003702 if (!audio_is_global_session(session)) {
3703 // player sessions on a spatializer output will use a dedicated input buffer and
3704 // will either output multi channel to mEffectBuffer if the track is spatilaized
3705 // or stereo to mPostSpatializerBuffer if not spatialized.
3706 uint32_t channelMask;
3707 bool isSessionSpatialized =
3708 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3709 if (isSessionSpatialized) {
3710 channelMask = mMixerChannelMask;
3711 } else {
3712 channelMask = mChannelMask;
3713 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003714 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003715 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003716 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003717 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003718 &halInBuffer);
3719 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003720
Andy Hung583043b2023-07-17 17:05:00 -07003721 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003722 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3723 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3724 &halOutBuffer);
3725 if (result != OK) return result;
3726
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003727 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003728
Mikhail Naganov022b9952017-01-04 16:36:51 -08003729 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3730 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003731 } else {
3732 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3733 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3734 // mPostSpatializerBuffer as output buffer
3735 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003736 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003737 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3738 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003739 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003740 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3741 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003742
Eric Laurentb62d0362021-10-26 17:40:18 +02003743 if (session == AUDIO_SESSION_DEVICE) {
3744 halInBuffer = halOutBuffer;
3745 }
3746 }
3747 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003748 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003749 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3750 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3751 &halInBuffer);
3752 if (result != OK) return result;
3753 halOutBuffer = halInBuffer;
3754 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3755 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003756 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003757 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003758 // Only one effect chain can be present in direct output thread and it uses
3759 // the sink buffer as input
3760 if (mType != DIRECT) {
3761 size_t numSamples = mNormalFrameCount
3762 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3763 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003764 const status_t allocateStatus =
3765 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003766 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003767 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003768 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003769
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003770 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003771 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3772 buffer, session);
3773 }
3774 }
3775 }
3776
3777 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003778 // Attach all tracks with same session ID to this chain.
3779 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003780 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003781 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003782 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3783 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003784 track->setMainBuffer(buffer);
3785 chain->incTrackCnt();
3786 }
3787 }
3788
3789 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003790 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003791 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003792 ALOGV("addEffectChain_l() activating track %p on session %d",
3793 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003794 chain->incActiveTrackCnt();
3795 }
3796 }
3797 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003798
Eric Laurentaaa44472014-09-12 17:41:50 -07003799 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003800 chain->setInBuffer(halInBuffer);
3801 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003802 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3803 // chains list in order to be processed last as it contains output device effects.
3804 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3805 // processing effects specific to an output stream before effects applied to all streams
3806 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003807 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3808 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003809 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003810 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003811 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003812 // Effect chain for other sessions are inserted at beginning of effect
3813 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003814 // sessions is not important.
3815 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003816 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3817 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003818 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003819 size_t size = mEffectChains.size();
3820 size_t i = 0;
3821 for (i = 0; i < size; i++) {
3822 if (mEffectChains[i]->sessionId() < session) {
3823 break;
3824 }
3825 }
3826 mEffectChains.insertAt(chain, i);
3827 checkSuspendOnAddEffectChain_l(chain);
3828
3829 return NO_ERROR;
3830}
3831
Andy Hungee58e4a2023-07-07 13:47:37 -07003832size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003833{
Glenn Kastend848eb42016-03-08 13:42:11 -08003834 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003835
3836 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3837
3838 for (size_t i = 0; i < mEffectChains.size(); i++) {
3839 if (chain == mEffectChains[i]) {
3840 mEffectChains.removeAt(i);
3841 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003842 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003843 if (session == track->sessionId()) {
3844 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3845 chain.get(), session);
3846 chain->decActiveTrackCnt();
3847 }
3848 }
3849
3850 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003851 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003852 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003853 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003854 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003855 chain->decTrackCnt();
3856 }
3857 }
3858 break;
3859 }
3860 }
3861 return mEffectChains.size();
3862}
3863
Andy Hungee58e4a2023-07-07 13:47:37 -07003864status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003865 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003866{
Andy Hung972bec12023-08-31 16:13:39 -07003867 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003868 return attachAuxEffect_l(track, EffectId);
3869}
3870
Andy Hungee58e4a2023-07-07 13:47:37 -07003871status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003872 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003873{
3874 status_t status = NO_ERROR;
3875
3876 if (EffectId == 0) {
3877 track->setAuxBuffer(0, NULL);
3878 } else {
3879 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003880 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003881 if (effect != 0) {
3882 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3883 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3884 } else {
3885 status = INVALID_OPERATION;
3886 }
3887 } else {
3888 status = BAD_VALUE;
3889 }
3890 }
3891 return status;
3892}
3893
Andy Hungee58e4a2023-07-07 13:47:37 -07003894void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003895{
3896 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003897 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003898 if (track->auxEffectId() == effectId) {
3899 attachAuxEffect_l(track, 0);
3900 }
3901 }
3902}
3903
Andy Hungee58e4a2023-07-07 13:47:37 -07003904bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003905NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003906{
Andy Hung78d8d952023-05-30 18:10:23 -07003907 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003908
Andy Hung077d62e2023-10-03 10:49:34 -07003909 if (mType == SPATIALIZER) {
3910 const pid_t tid = getTid();
3911 if (tid == -1) { // odd: we are here, we must be a running thread.
3912 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3913 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003914 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3915 if (priorityBoost > 0) {
3916 stream()->setHalThreadPriority(priorityBoost);
3917 }
Andy Hung077d62e2023-10-03 10:49:34 -07003918 }
3919 }
3920
Andy Hung8d31fd22023-06-26 19:20:57 -07003921 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003922
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003923 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003924 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003925
3926 // MIXER
3927 nsecs_t lastWarning = 0;
3928
3929 // DUPLICATING
3930 // FIXME could this be made local to while loop?
3931 writeFrames = 0;
3932
3933 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003934 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003935
Andy Hungd3639922022-04-28 18:00:49 -07003936 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003937 sleepTimeShift = 0;
3938 }
3939
3940 CpuStats cpuStats;
3941 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3942
3943 acquireWakeLock();
3944
Glenn Kasteneef598c2017-04-03 14:41:13 -07003945 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3946 // thread associated with this PlaybackThread.
3947 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3948 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003949 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3950 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003951 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003952 const char *logString = NULL;
3953
rago1bb90822017-05-02 18:31:48 -07003954 // Estimated time for next buffer to be written to hal. This is used only on
3955 // suspended mode (for now) to help schedule the wait time until next iteration.
3956 nsecs_t timeLoopNextNs = 0;
3957
Eric Laurent664539d2013-09-23 18:24:31 -07003958 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003959
Andy Hung2dbffc22018-08-08 18:50:41 -07003960 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003961
Eric Laurentb3f315a2021-07-13 15:09:05 +02003962 sendCheckOutputStageEffectsEvent();
3963
Andy Hung446f4df2019-02-21 12:26:41 -08003964 // loopCount is used for statistics and diagnostics.
3965 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003966 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003967 // Log merge requests are performed during AudioFlinger binder transactions, but
3968 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07003969 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003970
Eric Laurent81784c32012-11-19 14:55:58 -08003971 cpuStats.sample(myName);
3972
Andy Hung116bc262023-06-20 18:56:17 -07003973 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003974 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003975 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07003976 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003977
Andy Hung2dbffc22018-08-08 18:50:41 -07003978 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3979 //
Andy Hungc5007f82023-08-29 14:26:09 -07003980 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07003981 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003982 // Here, we try for the AF lock, but do not block on it as the latency
3983 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07003984 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07003985 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003986 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003987 status_t status = INVALID_OPERATION;
3988 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07003989 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07003990 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003991 && swPatches.size() > 0) {
3992 status = swPatches[0].getLatencyMs_l(&latencyMs);
3993 downstreamPatchHandle = swPatches[0].getPatchHandle();
3994 }
3995 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003996 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003997 lastDownstreamPatchHandle = downstreamPatchHandle;
3998 }
3999 if (status == OK) {
4000 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004001 // latency of 5 seconds).
4002 const double minLatency = 0., maxLatency = 5000.;
4003 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004004 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004005 } else {
4006 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004007 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004008 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004009 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004010 }
Andy Hung583043b2023-07-17 17:05:00 -07004011 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004012 }
4013 } else {
4014 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4015 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004016 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004017 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4018 }
4019 }
4020
Eric Laurentb3f315a2021-07-13 15:09:05 +02004021 if (mCheckOutputStageEffects.exchange(false)) {
4022 checkOutputStageEffects();
4023 }
4024
Vlad Popa7e81cea2023-01-19 16:34:16 +01004025 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004026 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004027
Andy Hungc5007f82023-08-29 14:26:09 -07004028 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004029
Eric Laurent021cf962014-05-13 10:18:14 -07004030 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004031 if (mCheckOutputStageEffects.load()) {
4032 continue;
4033 }
Eric Laurent10351942014-05-08 18:49:52 -07004034
Andy Hungc5007f82023-08-29 14:26:09 -07004035 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004036 if (logString != NULL) {
4037 mNBLogWriter->logTimestamp();
4038 mNBLogWriter->log(logString);
4039 logString = NULL;
4040 }
4041
Dean Wheatley12473e92021-03-18 23:00:55 +11004042 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004043
Eric Laurent81784c32012-11-19 14:55:58 -08004044 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004045 if (mSignalPending) {
4046 // A signal was raised while we were unlocked
4047 mSignalPending = false;
4048 } else if (waitingAsyncCallback_l()) {
4049 if (exitPending()) {
4050 break;
4051 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004052 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004053 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004054 releaseWakeLock_l();
4055 released = true;
4056 }
Andy Hung10cbff12017-02-21 17:30:14 -08004057
4058 const int64_t waitNs = computeWaitTimeNs_l();
4059 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004060 std::cv_status cvstatus =
4061 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4062 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004063 mSignalPending = true; // if timeout recheck everything
4064 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004066 if (released) {
4067 acquireWakeLock_l();
4068 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004069 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4070 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004071
4072 continue;
4073 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004074 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004075 isSuspended()) {
4076 // put audio hardware into standby after short delay
4077 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004078
4079 threadLoop_standby();
4080
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004081 // This is where we go into standby
4082 if (!mStandby) {
4083 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004084 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004085 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004086 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004087 }
Andy Hungd0979812019-02-21 15:51:44 -08004088 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004089 }
4090
Eric Tan39ec8d62018-07-24 09:49:29 -07004091 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004092 // we're about to wait, flush the binder command buffer
4093 IPCThreadState::self()->flushCommands();
4094
4095 clearOutputTracks();
4096
4097 if (exitPending()) {
4098 break;
4099 }
4100
4101 releaseWakeLock_l();
4102 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004103 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004104 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004105 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004106 acquireWakeLock_l();
4107
4108 mMixerStatus = MIXER_IDLE;
4109 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4110 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004111 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004112 checkSilentMode_l();
4113
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004114 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4115 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004116 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004117 sleepTimeShift = 0;
4118 }
4119
4120 continue;
4121 }
4122 }
Eric Laurent81784c32012-11-19 14:55:58 -08004123 // mMixerStatusIgnoringFastTracks is also updated internally
4124 mMixerStatus = prepareTracks_l(&tracksToRemove);
4125
Andy Hungab65b182023-09-06 19:41:47 -07004126 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004127
Vlad Popa7e81cea2023-01-19 16:34:16 +01004128 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004129
Eric Laurent81784c32012-11-19 14:55:58 -08004130 // prevent any changes in effect chain list and in each effect chain
4131 // during mixing and effect process as the audio buffers could be deleted
4132 // or modified if an effect is created or deleted
4133 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004134
4135 // Determine which session to pick up haptic data.
4136 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004137 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004138 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004139 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004140 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004141 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004142 if (effectChain != nullptr
4143 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004144 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004145 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004146 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004147 break;
4148 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004149 if (activeHapticSessionId == AUDIO_SESSION_NONE
4150 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004151 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004152 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004153 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004154 }
4155 }
4156 }
4157
Andy Hungc1646382019-04-30 16:12:10 -07004158 // Acquire a local copy of active tracks with lock (release w/o lock).
4159 //
4160 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4161 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4162 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4163 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004164
4165 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004166
Jiabin Huangfb476842022-12-06 03:18:10 +00004167 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004168 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004169 }
4170
Eric Laurent19952e12023-04-20 10:08:29 +02004171 // signal actual start of output stream when the render position reported by the kernel
4172 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004173 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4174 && (mKernelPositionOnStandby
4175 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004176 mHalStarted = true;
Andy Hungc5007f82023-08-29 14:26:09 -07004177 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004178 }
Andy Hungc5007f82023-08-29 14:26:09 -07004179 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004180
Eric Laurentbfb1b832013-01-07 09:53:42 -08004181 if (mBytesRemaining == 0) {
4182 mCurrentWriteLength = 0;
4183 if (mMixerStatus == MIXER_TRACKS_READY) {
4184 // threadLoop_mix() sets mCurrentWriteLength
4185 threadLoop_mix();
4186 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4187 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004188 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004189 // must be written to HAL
4190 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004191 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004192 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004193
4194 // Tally underrun frames as we are inserting 0s here.
4195 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004196 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004197 && !track->isStopped()
4198 && !track->isPaused()
4199 && !track->isTerminated()) {
4200 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4201 __func__, track->id(), track->getTrackStateAsString(),
4202 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004203 track->audioTrackServerProxy()->tallyUnderrunFrames(
4204 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004205 }
4206 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004207 }
4208 }
Andy Hung98ef9782014-03-04 14:46:50 -08004209 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004210 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004211 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004212 // or mSinkBuffer (if there are no effects and there is no data already copied to
4213 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004214 //
4215 // This is done pre-effects computation; if effects change to
4216 // support higher precision, this needs to move.
4217 //
4218 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004219 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004220 uint32_t mixerChannelCount = mEffectBufferValid ?
4221 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004222 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004223 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4224 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4225
David Li88ee0902022-06-22 10:01:21 +08004226 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4227 // do these processes after effects are applied.
4228 if (!mEffectBufferValid) {
4229 // mono blend occurs for mixer threads only (not direct or offloaded)
4230 // and is handled here if we're going directly to the sink.
4231 if (requireMonoBlend()) {
4232 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4233 mNormalFrameCount, true /*limit*/);
4234 }
Andy Hung2ddee192015-12-18 17:34:44 -08004235
David Li88ee0902022-06-22 10:01:21 +08004236 if (!hasFastMixer()) {
4237 // Balance must take effect after mono conversion.
4238 // We do it here if there is no FastMixer.
4239 // mBalance detects zero balance within the class for speed
4240 // (not needed here).
4241 mBalance.setBalance(mMasterBalance.load());
4242 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4243 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004244 }
4245
Andy Hung98ef9782014-03-04 14:46:50 -08004246 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004247 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004248
4249 // If we're going directly to the sink and there are haptic channels,
4250 // we should adjust channels as the sample data is partially interleaved
4251 // in this case.
4252 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4253 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4254 mChannelCount + mHapticChannelCount,
4255 audio_bytes_per_sample(format),
4256 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4257 }
Andy Hung98ef9782014-03-04 14:46:50 -08004258 }
4259
Eric Laurentbfb1b832013-01-07 09:53:42 -08004260 mBytesRemaining = mCurrentWriteLength;
4261 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004262 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4263 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4264 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4265 mBytesWritten += mBytesRemaining;
4266 mFramesWritten += framesRemaining;
4267 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004268 mBytesRemaining = 0;
4269 }
Eric Laurent81784c32012-11-19 14:55:58 -08004270
Eric Laurentbfb1b832013-01-07 09:53:42 -08004271 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004272 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273 for (size_t i = 0; i < effectChains.size(); i ++) {
4274 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004275 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004276 if (activeHapticSessionId != AUDIO_SESSION_NONE
4277 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004278 // Haptic data is active in this case, copy it directly from
4279 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004280 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4281 audio_channel_count_from_out_mask(mMixerChannelMask) :
4282 mChannelCount;
4283 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4284 hapticSessionChannelCount = mChannelCount;
4285 }
4286
jiabin47affe52019-04-04 18:02:07 -07004287 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004288 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004289 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004290 memcpy_by_audio_format(
4291 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004292 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004293 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004294 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004295 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004296 }
Eric Laurent81784c32012-11-19 14:55:58 -08004297 }
4298 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004299 // Process effect chains for offloaded thread even if no audio
4300 // was read from audio track: process only updates effect state
4301 // and thus does have to be synchronized with audio writes but may have
4302 // to be called while waiting for async write callback
4303 if (mType == OFFLOAD) {
4304 for (size_t i = 0; i < effectChains.size(); i ++) {
4305 effectChains[i]->process_l();
4306 }
4307 }
Eric Laurent81784c32012-11-19 14:55:58 -08004308
Andy Hung98ef9782014-03-04 14:46:50 -08004309 // Only if the Effects buffer is enabled and there is data in the
4310 // Effects buffer (buffer valid), we need to
4311 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004312 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004313 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004314 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004315 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004316 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004317 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004318 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004319 }
4320
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004321 if (!hasFastMixer()) {
4322 // Balance must take effect after mono conversion.
4323 // We do it here if there is no FastMixer.
4324 // mBalance detects zero balance within the class for speed (not needed here).
4325 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004326 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004327 }
4328
Eric Laurentb62d0362021-10-26 17:40:18 +02004329 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4330 // mPostSpatializerBuffer if the haptics track is spatialized.
4331 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4332 // For other thread types, the haptics channels are already in mEffectBuffer.
4333 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4334 const size_t srcBufferSize = mNormalFrameCount *
4335 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4336 mEffectBufferFormat);
4337 const size_t dstBufferSize = mNormalFrameCount
4338 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4339
4340 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4341 mEffectBufferFormat,
4342 (uint8_t*)mEffectBuffer + srcBufferSize,
4343 mEffectBufferFormat,
4344 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004345 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004346 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4347 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4348 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4349 // Clamp PCM float values more than this distance from 0 to insulate
4350 // a HAL which doesn't handle NaN correctly.
4351 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4352 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4353 static_cast<const float*>(effectBuffer),
4354 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4355 } else {
4356 memcpy_by_audio_format(mSinkBuffer, mFormat,
4357 effectBuffer, mEffectBufferFormat, framesToCopy);
4358 }
jiabin245cdd92018-12-07 17:55:15 -08004359 // The sample data is partially interleaved when haptic channels exist,
4360 // we need to adjust channels here.
4361 if (mHapticChannelCount > 0) {
4362 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4363 mChannelCount + mHapticChannelCount,
4364 audio_bytes_per_sample(mFormat),
4365 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4366 }
Andy Hung98ef9782014-03-04 14:46:50 -08004367 }
4368
Eric Laurent81784c32012-11-19 14:55:58 -08004369 // enable changes in effect chain
4370 unlockEffectChains(effectChains);
4371
Vlad Popafce10862023-02-03 10:37:07 +01004372 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004373 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004374 metadataUpdate.playbackMetadataUpdate);
4375 }
4376
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004378 // mSleepTimeUs == 0 means we must write to audio hardware
4379 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004380 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004381 // writePeriodNs is updated >= 0 when ret > 0.
4382 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004383 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004384 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004385 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004386 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004387 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004388 if (ret < 0) {
4389 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004390 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004391 mBytesWritten += ret;
4392 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004393 const int64_t frames = ret / mFrameSize;
4394 mFramesWritten += frames;
4395
4396 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4397 // process information relating to write time.
4398 if (audio_has_proportional_frames(mFormat)) {
4399 // we are in a continuous mixing cycle
4400 if (mMixerStatus == MIXER_TRACKS_READY &&
4401 loopCount == lastLoopCountWritten + 1) {
4402
4403 const double jitterMs =
4404 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4405 {frames, writePeriodNs},
4406 {0, 0} /* lastTimestamp */, mSampleRate);
4407 const double processMs =
4408 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4409
Andy Hung972bec12023-08-31 16:13:39 -07004410 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004411 mIoJitterMs.add(jitterMs);
4412 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004413
4414 if (mPipeSink.get() != nullptr) {
4415 // Using the Monopipe availableToWrite, we estimate the current
4416 // buffer size.
4417 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4418 const ssize_t
4419 availableToWrite = mPipeSink->availableToWrite();
4420 const size_t pipeFrames = monoPipe->maxFrames();
4421 const size_t
4422 remainingFrames = pipeFrames - max(availableToWrite, 0);
4423 mMonopipePipeDepthStats.add(remainingFrames);
4424 }
Andy Hung446f4df2019-02-21 12:26:41 -08004425 }
4426
4427 // write blocked detection
4428 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004429 if ((mType == MIXER || mType == SPATIALIZER)
4430 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004431 mNumDelayedWrites++;
4432 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4433 ATRACE_NAME("underrun");
4434 ALOGW("write blocked for %lld msecs, "
4435 "%d delayed writes, thread %d",
4436 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4437 mNumDelayedWrites, mId);
4438 lastWarning = lastIoEndNs;
4439 }
4440 }
4441 }
4442 // update timing info.
4443 mLastIoBeginNs = lastIoBeginNs;
4444 mLastIoEndNs = lastIoEndNs;
4445 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004446 }
4447 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4448 (mMixerStatus == MIXER_DRAIN_ALL)) {
4449 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004450 }
Andy Hungd3639922022-04-28 18:00:49 -07004451 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004452
4453 if (mThreadThrottle
4454 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004455 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004456 // Limit MixerThread data processing to no more than twice the
4457 // expected processing rate.
4458 //
4459 // This helps prevent underruns with NuPlayer and other applications
4460 // which may set up buffers that are close to the minimum size, or use
4461 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4462 //
4463 // The throttle smooths out sudden large data drains from the device,
4464 // e.g. when it comes out of standby, which often causes problems with
4465 // (1) mixer threads without a fast mixer (which has its own warm-up)
4466 // (2) minimum buffer sized tracks (even if the track is full,
4467 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004468 //
4469 // Total time spent in last processing cycle equals time spent in
4470 // 1. threadLoop_write, as well as time spent in
4471 // 2. threadLoop_mix (significant for heavy mixing, especially
4472 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004473
Andy Hung446f4df2019-02-21 12:26:41 -08004474 // it's OK if deltaMs is an overestimate.
4475
4476 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004477
Ivan Lozanoea04d392017-11-07 14:37:07 -08004478 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004479 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004480 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004481
Andy Hung08fb1742015-05-31 23:22:10 -07004482 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004483 // notify of throttle start on verbose log
4484 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4485 "mixer(%p) throttle begin:"
4486 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004487 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004488 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004489 // Throttle must be attributed to the previous mixer loop's write time
4490 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004491 // This also ensures proper timing statistics.
4492 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004493 } else {
4494 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4495 if (diff > 0) {
4496 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004497 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004498 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004499 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004500 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004501 outDeviceTypes_l(),
4502 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004503 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004504 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4505 }
Andy Hung08fb1742015-05-31 23:22:10 -07004506 }
4507 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004508 }
Eric Laurent81784c32012-11-19 14:55:58 -08004509
Eric Laurentbfb1b832013-01-07 09:53:42 -08004510 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004511 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004512 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004513 // suspended requires accurate metering of sleep time.
4514 if (isSuspended()) {
4515 // advance by expected sleepTime
4516 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4517 const nsecs_t nowNs = systemTime();
4518
4519 // compute expected next time vs current time.
4520 // (negative deltas are treated as delays).
4521 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4522 if (deltaNs < -kMaxNextBufferDelayNs) {
4523 // Delays longer than the max allowed trigger a reset.
4524 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4525 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4526 timeLoopNextNs = nowNs + deltaNs;
4527 } else if (deltaNs < 0) {
4528 // Delays within the max delay allowed: zero the delta/sleepTime
4529 // to help the system catch up in the next iteration(s)
4530 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4531 deltaNs = 0;
4532 }
4533 // update sleep time (which is >= 0)
4534 mSleepTimeUs = deltaNs / 1000;
4535 }
Eric Laurente93cc032016-05-05 10:15:10 -07004536 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004537 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004538 }
Glenn Kastene7754022014-10-31 12:11:26 -07004539 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004540 }
Eric Laurent81784c32012-11-19 14:55:58 -08004541 }
4542
4543 // Finally let go of removed track(s), without the lock held
4544 // since we can't guarantee the destructors won't acquire that
4545 // same lock. This will also mutate and push a new fast mixer state.
4546 threadLoop_removeTracks(tracksToRemove);
4547 tracksToRemove.clear();
4548
4549 // FIXME I don't understand the need for this here;
4550 // it was in the original code but maybe the
4551 // assignment in saveOutputTracks() makes this unnecessary?
4552 clearOutputTracks();
4553
4554 // Effect chains will be actually deleted here if they were removed from
4555 // mEffectChains list during mixing or effects processing
4556 effectChains.clear();
4557
4558 // FIXME Note that the above .clear() is no longer necessary since effectChains
4559 // is now local to this block, but will keep it for now (at least until merge done).
4560 }
4561
Eric Laurentbfb1b832013-01-07 09:53:42 -08004562 threadLoop_exit();
4563
Eric Laurentcf817a22014-08-04 20:36:31 -07004564 if (!mStandby) {
4565 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004566 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004567 }
4568
4569 releaseWakeLock();
4570
4571 ALOGV("Thread %p type %d exiting", this, mType);
4572 return false;
4573}
4574
Andy Hungee58e4a2023-07-07 13:47:37 -07004575void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004576{
Dean Wheatley12473e92021-03-18 23:00:55 +11004577 if (mStandby) {
4578 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4579 return;
4580 } else if (mHwPaused) {
4581 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4582 return;
4583 }
4584
4585 // Gather the framesReleased counters for all active tracks,
4586 // and associate with the sink frames written out. We need
4587 // this to convert the sink timestamp to the track timestamp.
4588 bool kernelLocationUpdate = false;
4589 ExtendedTimestamp timestamp; // use private copy to fetch
4590
4591 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4592 // HAL may be draining some small duration buffered data for fade out.
4593 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4594 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4595 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4596 mSampleRate);
4597
Andy Hungab65b182023-09-06 19:41:47 -07004598 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004599 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4600 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4601 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4602 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4603 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4604 = correctedTimestamp.mFrames;
4605 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4606 = correctedTimestamp.mTimeNs;
4607 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4608 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4609 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4610
4611 // Note: Downstream latency only added if timestamp correction enabled.
4612 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4613 const int64_t newPosition =
4614 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4615 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4616 // prevent retrograde
4617 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4618 newPosition,
4619 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4620 - mSuspendedFrames));
4621 }
4622 }
4623
4624 // We always fetch the timestamp here because often the downstream
4625 // sink will block while writing.
4626
4627 // We keep track of the last valid kernel position in case we are in underrun
4628 // and the normal mixer period is the same as the fast mixer period, or there
4629 // is some error from the HAL.
4630 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4631 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4632 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4633 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4634 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4635
4636 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4637 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4638 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4639 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4640 }
4641
4642 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4643 kernelLocationUpdate = true;
4644 } else {
4645 ALOGVV("getTimestamp error - no valid kernel position");
4646 }
4647
4648 // copy over kernel info
4649 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4650 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4651 + mSuspendedFrames; // add frames discarded when suspended
4652 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4653 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4654 } else {
4655 mTimestampVerifier.error();
4656 }
4657
4658 // mFramesWritten for non-offloaded tracks are contiguous
4659 // even after standby() is called. This is useful for the track frame
4660 // to sink frame mapping.
4661 bool serverLocationUpdate = false;
4662 if (mFramesWritten != mLastFramesWritten) {
4663 serverLocationUpdate = true;
4664 mLastFramesWritten = mFramesWritten;
4665 }
4666 // Only update timestamps if there is a meaningful change.
4667 // Either the kernel timestamp must be valid or we have written something.
4668 if (kernelLocationUpdate || serverLocationUpdate) {
4669 if (serverLocationUpdate) {
4670 // use the time before we called the HAL write - it is a bit more accurate
4671 // to when the server last read data than the current time here.
4672 //
4673 // If we haven't written anything, mLastIoBeginNs will be -1
4674 // and we use systemTime().
4675 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4676 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004677 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004678 }
4679
Andy Hung8d31fd22023-06-26 19:20:57 -07004680 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004681 if (!t->isFastTrack()) {
4682 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004683 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004684 mFramesWritten,
4685 mSampleRate,
4686 mTimestamp);
4687 }
4688 }
4689 }
4690
4691 if (audio_has_proportional_frames(mFormat)) {
4692 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4693 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4694 mLatencyMs.add(latencyMs);
4695 }
4696 }
4697#if 0
4698 // logFormat example
4699 if (z % 100 == 0) {
4700 timespec ts;
4701 clock_gettime(CLOCK_MONOTONIC, &ts);
4702 LOGT("This is an integer %d, this is a float %f, this is my "
4703 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4704 LOGT("A deceptive null-terminated string %\0");
4705 }
4706 ++z;
4707#endif
4708}
4709
Andy Hungc5007f82023-08-29 14:26:09 -07004710// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004711void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004712NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004713{
Andy Hung6c498e92023-12-05 17:28:17 -08004714 if (tracksToRemove.empty()) return;
4715
4716 // Block all incoming TrackHandle requests until we are finished with the release.
4717 setThreadBusy_l(true);
4718
Andy Hungfe726a62018-09-27 15:17:25 -07004719 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004720 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004721 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004722 if (chain != 0) {
4723 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4724 __func__, track->id(), chain.get(), track->sessionId());
4725 chain->decActiveTrackCnt();
4726 }
Andy Hung6c498e92023-12-05 17:28:17 -08004727
Andy Hungfe726a62018-09-27 15:17:25 -07004728 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004729 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004730 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004731 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004732 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004733 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004734 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735 }
Andy Hung6c498e92023-12-05 17:28:17 -08004736 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004737 }
jiabineb3bda02020-06-30 14:07:03 -07004738 if (mHapticChannelCount > 0 &&
4739 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4740 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004741 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004742 // Unlock due to VibratorService will lock for this call and will
4743 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004744 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004745 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004746
4747 // When the track is stop, set the haptic intensity as MUTE
4748 // for the HapticGenerator effect.
4749 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004750 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004751 }
jiabin245cdd92018-12-07 17:55:15 -08004752 }
Andy Hung6c498e92023-12-05 17:28:17 -08004753
4754 // Under lock, the track is removed from the active tracks list.
4755 //
4756 // Once the track is no longer active, the TrackHandle may directly
4757 // modify it as the threadLoop() is no longer responsible for its maintenance.
4758 // Do not modify the track from threadLoop after the mutex is unlocked
4759 // if it is not active.
4760 mActiveTracks.remove(track);
4761
4762 if (track->isTerminated()) {
4763 // remove from our tracks vector
4764 removeTrack_l(track);
4765 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004766 }
Andy Hung6c498e92023-12-05 17:28:17 -08004767
4768 // Allow incoming TrackHandle requests. We still hold the mutex,
4769 // so pending TrackHandle requests will occur after we unlock it.
4770 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004771}
Eric Laurent81784c32012-11-19 14:55:58 -08004772
Andy Hungee58e4a2023-07-07 13:47:37 -07004773status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004774{
4775 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004776 ExtendedTimestamp ets;
4777 status_t status = mNormalSink->getTimestamp(ets);
4778 if (status == NO_ERROR) {
4779 status = ets.getBestTimestamp(&timestamp);
4780 }
4781 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004782 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004783 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004784 collectTimestamps_l();
4785 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4786 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004787 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004788 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4789 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4790 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4791 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4792 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004793 }
4794 return INVALID_OPERATION;
4795}
Eric Laurent1c333e22014-05-20 10:48:17 -07004796
Eric Laurenteab90452019-06-24 15:17:46 -07004797// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4798// still applied by the mixer.
4799// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4800// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4801// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004802status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004803{
4804 status_t result = NO_ERROR;
4805 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4806 if (*volume != mLeftVolFloat) {
4807 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004808 // HAL can return INVALID_OPERATION if operation is not supported.
4809 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004810 "Error when setting output stream volume: %d", result);
4811 if (result == NO_ERROR) {
4812 mLeftVolFloat = *volume;
4813 }
4814 }
4815 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4816 // remove stream volume contribution from software volume.
4817 if (mLeftVolFloat == *volume) {
4818 *volume = 1.0f;
4819 }
4820 }
4821 return result;
4822}
4823
Andy Hungee58e4a2023-07-07 13:47:37 -07004824status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004825 audio_patch_handle_t *handle)
4826{
Andy Hungf60abce2016-08-26 11:37:54 -07004827 status_t status;
4828 if (property_get_bool("af.patch_park", false /* default_value */)) {
4829 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4830 // or if HAL does not properly lock against access.
4831 AutoPark<FastMixer> park(mFastMixer);
4832 status = PlaybackThread::createAudioPatch_l(patch, handle);
4833 } else {
4834 status = PlaybackThread::createAudioPatch_l(patch, handle);
4835 }
Eric Laurentb0463942022-12-20 16:31:10 +01004836
4837 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004838 return status;
4839}
4840
Andy Hungee58e4a2023-07-07 13:47:37 -07004841status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004842 audio_patch_handle_t *handle)
4843{
4844 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004845
4846 // store new device and send to effects
4847 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004848 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004849 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004850 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4851 && !mOutput->audioHwDev->supportsAudioPatches(),
4852 "Enumerated device type(%#x) must not be used "
4853 "as it does not support audio patches",
4854 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004855 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004856 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4857 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004858 }
4859
François Gaffie0c280aa2018-07-25 10:02:15 +02004860 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004861#ifdef ADD_BATTERY_DATA
4862 // when changing the audio output device, call addBatteryData to notify
4863 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004864 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004865 uint32_t params = 0;
4866 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004867 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004868 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004869 }
4870
Eric Laurent054d9d32015-04-24 08:48:48 -07004871 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004872 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004873 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4874 }
4875
4876 if (params != 0) {
4877 addBatteryData(params);
4878 }
4879 }
4880#endif
4881
4882 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004883 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004884 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004885
jiabinc52b1ff2019-10-31 17:20:42 -07004886 // mPatch.num_sinks is not set when the thread is created so that
4887 // the first patch creation triggers an ioConfigChanged callback
4888 bool configChanged = (mPatch.num_sinks == 0) ||
4889 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004890 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004891 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004892 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004893
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004894 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004895 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4896 status = hwDevice->createAudioPatch(patch->num_sources,
4897 patch->sources,
4898 patch->num_sinks,
4899 patch->sinks,
4900 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004901 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004902 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004903 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004904 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004905 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004906
4907 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004908 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004909 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004910 // also dispatch to active AudioTracks for MediaMetrics
4911 for (const auto &track : mActiveTracks) {
4912 track->logEndInterval();
4913 track->logBeginInterval(patchSinksAsString);
4914 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004915
Eric Laurente8726fe2015-06-26 09:39:24 -07004916 if (configChanged) {
4917 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4918 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004919 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004920 mActiveTracks.setHasChanged();
4921
Eric Laurent1c333e22014-05-20 10:48:17 -07004922 return status;
4923}
4924
Andy Hungee58e4a2023-07-07 13:47:37 -07004925status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004926{
Andy Hungf60abce2016-08-26 11:37:54 -07004927 status_t status;
4928 if (property_get_bool("af.patch_park", false /* default_value */)) {
4929 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4930 // or if HAL does not properly lock against access.
4931 AutoPark<FastMixer> park(mFastMixer);
4932 status = PlaybackThread::releaseAudioPatch_l(handle);
4933 } else {
4934 status = PlaybackThread::releaseAudioPatch_l(handle);
4935 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004936 return status;
4937}
4938
Andy Hungee58e4a2023-07-07 13:47:37 -07004939status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004940{
4941 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004942
jiabinc52b1ff2019-10-31 17:20:42 -07004943 mPatch = audio_patch{};
4944 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004945
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004946 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004947 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4948 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004949 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004950 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004951 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004952 // Force meteadata update after a route change
4953 mActiveTracks.setHasChanged();
4954
Eric Laurent1c333e22014-05-20 10:48:17 -07004955 return status;
4956}
4957
Andy Hungee58e4a2023-07-07 13:47:37 -07004958void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004959{
Andy Hung972bec12023-08-31 16:13:39 -07004960 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004961 mTracks.add(track);
4962}
4963
Andy Hungee58e4a2023-07-07 13:47:37 -07004964void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004965{
Andy Hung972bec12023-08-31 16:13:39 -07004966 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004967 destroyTrack_l(track);
4968}
4969
Andy Hungee58e4a2023-07-07 13:47:37 -07004970void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004971{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004972 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004973 config->role = AUDIO_PORT_ROLE_SOURCE;
4974 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4975 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004976 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4977 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4978 config->flags.output = mOutput->flags;
4979 }
Eric Laurent83b88082014-06-20 18:31:16 -07004980}
4981
Eric Laurent81784c32012-11-19 14:55:58 -08004982// ----------------------------------------------------------------------------
4983
Andy Hungee58e4a2023-07-07 13:47:37 -07004984/* static */
4985sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07004986 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07004987 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07004988 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07004989}
4990
Andy Hung583043b2023-07-17 17:05:00 -07004991MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004992 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07004993 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004994 // mAudioMixer below
4995 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004996 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004997 mFastMixerFutex(0),
4998 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004999 // mOutputSink below
5000 // mPipeSink below
5001 // mNormalSink below
5002{
Andy Hung583043b2023-07-17 17:05:00 -07005003 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005004 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005005 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005006 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005007 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5008 mNormalFrameCount);
5009 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5010
Andy Hungfbfc3952015-01-15 13:33:51 -08005011 if (type == DUPLICATING) {
5012 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5013 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5014 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5015 return;
5016 }
Eric Laurent81784c32012-11-19 14:55:58 -08005017 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005018 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005019 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005020 const NBAIO_Format offers[1] = {Format_from_SR_C(
5021 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005022#if !LOG_NDEBUG
5023 ssize_t index =
5024#else
5025 (void)
5026#endif
5027 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005028 ALOG_ASSERT(index == 0);
5029
5030 // initialize fast mixer depending on configuration
5031 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005032 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005033 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005034 } else {
5035 switch (kUseFastMixer) {
5036 case FastMixer_Never:
5037 initFastMixer = false;
5038 break;
5039 case FastMixer_Always:
5040 initFastMixer = true;
5041 break;
5042 case FastMixer_Static:
5043 case FastMixer_Dynamic:
5044 initFastMixer = mFrameCount < mNormalFrameCount;
5045 break;
5046 }
5047 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5048 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5049 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005050 }
5051 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005052 audio_format_t fastMixerFormat;
5053 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5054 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5055 } else {
5056 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5057 }
5058 if (mFormat != fastMixerFormat) {
5059 // change our Sink format to accept our intermediate precision
5060 mFormat = fastMixerFormat;
5061 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005062 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005063 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5064 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5065 }
Eric Laurent81784c32012-11-19 14:55:58 -08005066
5067 // create a MonoPipe to connect our submix to FastMixer
5068 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005069
Andy Hung1258c1a2014-05-23 21:22:17 -07005070 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005071 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005072 format.mFormat = fastMixerFormat;
5073 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5074
Eric Laurent81784c32012-11-19 14:55:58 -08005075 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5076 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5077 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5078 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005079 const NBAIO_Format offersFast[1] = {format};
5080 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005081#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005082 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005083#else
5084 (void)
5085#endif
Andy Hung920f6572022-10-06 12:09:49 -07005086 monoPipe->negotiate(offersFast, std::size(offersFast),
5087 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005088 ALOG_ASSERT(index == 0);
5089 monoPipe->setAvgFrames((mScreenState & 1) ?
5090 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5091 mPipeSink = monoPipe;
5092
Eric Laurent81784c32012-11-19 14:55:58 -08005093 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005094 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005095 FastMixerStateQueue *sq = mFastMixer->sq();
5096#ifdef STATE_QUEUE_DUMP
5097 sq->setObserverDump(&mStateQueueObserverDump);
5098 sq->setMutatorDump(&mStateQueueMutatorDump);
5099#endif
5100 FastMixerState *state = sq->begin();
5101 FastTrack *fastTrack = &state->mFastTracks[0];
5102 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5103 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5104 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005105 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5106 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5107 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005108 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005109 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005110 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005111 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005112 fastTrack->mGeneration++;
5113 state->mFastTracksGen++;
5114 state->mTrackMask = 1;
5115 // fast mixer will use the HAL output sink
5116 state->mOutputSink = mOutputSink.get();
5117 state->mOutputSinkGen++;
5118 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005119 // specify sink channel mask when haptic channel mask present as it can not
5120 // be calculated directly from channel count
5121 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005122 ? AUDIO_CHANNEL_NONE
5123 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005124 state->mCommand = FastMixerState::COLD_IDLE;
5125 // already done in constructor initialization list
5126 //mFastMixerFutex = 0;
5127 state->mColdFutexAddr = &mFastMixerFutex;
5128 state->mColdGen++;
5129 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005130 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005131 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005132 sq->end();
5133 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5134
Eric Tan0513b5d2018-09-17 10:32:48 -07005135 NBLog::thread_info_t info;
5136 info.id = mId;
5137 info.type = NBLog::FASTMIXER;
5138 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5139
Eric Laurent81784c32012-11-19 14:55:58 -08005140 // start the fast mixer
5141 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5142 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005143 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005144 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005145
5146#ifdef AUDIO_WATCHDOG
5147 // create and start the watchdog
5148 mAudioWatchdog = new AudioWatchdog();
5149 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5150 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5151 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005152 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005153#endif
Andy Hung8946a282018-04-19 20:04:56 -07005154 } else {
5155#ifdef TEE_SINK
5156 // Only use the MixerThread tee if there is no FastMixer.
5157 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5158 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5159#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005160 }
5161
5162 switch (kUseFastMixer) {
5163 case FastMixer_Never:
5164 case FastMixer_Dynamic:
5165 mNormalSink = mOutputSink;
5166 break;
5167 case FastMixer_Always:
5168 mNormalSink = mPipeSink;
5169 break;
5170 case FastMixer_Static:
5171 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5172 break;
5173 }
5174}
5175
Andy Hungee58e4a2023-07-07 13:47:37 -07005176MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005177{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005178 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005179 FastMixerStateQueue *sq = mFastMixer->sq();
5180 FastMixerState *state = sq->begin();
5181 if (state->mCommand == FastMixerState::COLD_IDLE) {
5182 int32_t old = android_atomic_inc(&mFastMixerFutex);
5183 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005184 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005185 }
5186 }
5187 state->mCommand = FastMixerState::EXIT;
5188 sq->end();
5189 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5190 mFastMixer->join();
5191 // Though the fast mixer thread has exited, it's state queue is still valid.
5192 // We'll use that extract the final state which contains one remaining fast track
5193 // corresponding to our sub-mix.
5194 state = sq->begin();
5195 ALOG_ASSERT(state->mTrackMask == 1);
5196 FastTrack *fastTrack = &state->mFastTracks[0];
5197 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5198 delete fastTrack->mBufferProvider;
5199 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005200 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005201#ifdef AUDIO_WATCHDOG
5202 if (mAudioWatchdog != 0) {
5203 mAudioWatchdog->requestExit();
5204 mAudioWatchdog->requestExitAndWait();
5205 mAudioWatchdog.clear();
5206 }
5207#endif
5208 }
Andy Hung583043b2023-07-17 17:05:00 -07005209 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005210 delete mAudioMixer;
5211}
5212
Andy Hungee58e4a2023-07-07 13:47:37 -07005213void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005214 PlaybackThread::onFirstRef();
5215
Andy Hung972bec12023-08-31 16:13:39 -07005216 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005217 if (mOutput != nullptr && mOutput->stream != nullptr) {
5218 status_t status = mOutput->stream->setLatencyModeCallback(this);
5219 if (status != INVALID_OPERATION) {
5220 updateHalSupportedLatencyModes_l();
5221 }
5222 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5223 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5224 mBluetoothLatencyModesEnabled.store(
5225 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5226 }
5227}
Eric Laurent81784c32012-11-19 14:55:58 -08005228
Andy Hungee58e4a2023-07-07 13:47:37 -07005229uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005230{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005231 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005232 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5233 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5234 }
5235 return latency;
5236}
5237
Andy Hungee58e4a2023-07-07 13:47:37 -07005238ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005239{
5240 // FIXME we should only do one push per cycle; confirm this is true
5241 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005242 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005243 FastMixerStateQueue *sq = mFastMixer->sq();
5244 FastMixerState *state = sq->begin();
5245 if (state->mCommand != FastMixerState::MIX_WRITE &&
5246 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5247 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005248
5249 // FIXME workaround for first HAL write being CPU bound on some devices
5250 ATRACE_BEGIN("write");
5251 mOutput->write((char *)mSinkBuffer, 0);
5252 ATRACE_END();
5253
Eric Laurent81784c32012-11-19 14:55:58 -08005254 int32_t old = android_atomic_inc(&mFastMixerFutex);
5255 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005256 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005257 }
5258#ifdef AUDIO_WATCHDOG
5259 if (mAudioWatchdog != 0) {
5260 mAudioWatchdog->resume();
5261 }
5262#endif
5263 }
5264 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005265#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005266 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005267 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005268#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005269 sq->end();
5270 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5271 if (kUseFastMixer == FastMixer_Dynamic) {
5272 mNormalSink = mPipeSink;
5273 }
5274 } else {
5275 sq->end(false /*didModify*/);
5276 }
5277 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005278 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005279}
5280
Andy Hungee58e4a2023-07-07 13:47:37 -07005281void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005282{
5283 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005284 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005285 FastMixerStateQueue *sq = mFastMixer->sq();
5286 FastMixerState *state = sq->begin();
5287 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005288 // Report any frames trapped in the Monopipe
5289 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5290 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5291 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5292 "monoPipeWritten:%lld monoPipeLeft:%lld",
5293 (long long)mFramesWritten, (long long)mSuspendedFrames,
5294 (long long)mPipeSink->framesWritten(), pipeFrames);
5295 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5296
Eric Laurent81784c32012-11-19 14:55:58 -08005297 state->mCommand = FastMixerState::COLD_IDLE;
5298 state->mColdFutexAddr = &mFastMixerFutex;
5299 state->mColdGen++;
5300 mFastMixerFutex = 0;
5301 sq->end();
5302 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5303 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5304 if (kUseFastMixer == FastMixer_Dynamic) {
5305 mNormalSink = mOutputSink;
5306 }
5307#ifdef AUDIO_WATCHDOG
5308 if (mAudioWatchdog != 0) {
5309 mAudioWatchdog->pause();
5310 }
5311#endif
5312 } else {
5313 sq->end(false /*didModify*/);
5314 }
5315 }
5316 PlaybackThread::threadLoop_standby();
5317}
5318
Andy Hungee58e4a2023-07-07 13:47:37 -07005319bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005320{
5321 return false;
5322}
5323
Andy Hungee58e4a2023-07-07 13:47:37 -07005324bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005325{
5326 return !mStandby;
5327}
5328
Andy Hungee58e4a2023-07-07 13:47:37 -07005329bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005330{
Andy Hung972bec12023-08-31 16:13:39 -07005331 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005332 return waitingAsyncCallback_l();
5333}
5334
Eric Laurent81784c32012-11-19 14:55:58 -08005335// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005336void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005337{
Andy Hung8d672e02023-09-15 18:19:28 -07005338 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5339 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005340 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005342 // discard any pending drain or write ack by incrementing sequence
5343 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5344 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005346 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5347 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005348 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005349 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005350 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005351}
5352
Andy Hungee58e4a2023-07-07 13:47:37 -07005353void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005354{
5355 ALOGV("signal playback thread");
5356 broadcast_l();
5357}
5358
Andy Hungee58e4a2023-07-07 13:47:37 -07005359void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005360{
5361 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5362 invalidateTracks((audio_stream_type_t)i);
5363 }
5364}
5365
Andy Hungee58e4a2023-07-07 13:47:37 -07005366void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005367{
Eric Laurent81784c32012-11-19 14:55:58 -08005368 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005369 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005370 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005371 // increase sleep time progressively when application underrun condition clears.
5372 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5373 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5374 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005375 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005376 sleepTimeShift--;
5377 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005378 mSleepTimeUs = 0;
5379 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005380 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005381
Eric Laurent81784c32012-11-19 14:55:58 -08005382}
5383
Andy Hungee58e4a2023-07-07 13:47:37 -07005384void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005385{
5386 // If no tracks are ready, sleep once for the duration of an output
5387 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005388 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005389 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005390 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5391 // Using the Monopipe availableToWrite, we estimate the
5392 // sleep time to retry for more data (before we underrun).
5393 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5394 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5395 const size_t pipeFrames = monoPipe->maxFrames();
5396 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5397 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5398 const size_t framesDelay = std::min(
5399 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5400 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5401 pipeFrames, framesLeft, framesDelay);
5402 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5403 } else {
5404 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5405 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5406 mSleepTimeUs = kMinThreadSleepTimeUs;
5407 }
5408 // reduce sleep time in case of consecutive application underruns to avoid
5409 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5410 // duration we would end up writing less data than needed by the audio HAL if
5411 // the condition persists.
5412 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5413 sleepTimeShift++;
5414 }
Eric Laurent81784c32012-11-19 14:55:58 -08005415 }
5416 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005417 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005418 }
5419 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005420 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5421 // before effects processing or output.
5422 if (mMixerBufferValid) {
5423 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005424 if (mType == SPATIALIZER) {
5425 memset(mSinkBuffer, 0, mSinkBufferSize);
5426 }
Andy Hung98ef9782014-03-04 14:46:50 -08005427 } else {
5428 memset(mSinkBuffer, 0, mSinkBufferSize);
5429 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005430 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005431 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5432 "anticipated start");
5433 }
5434 // TODO add standby time extension fct of effect tail
5435}
5436
Andy Hungc5007f82023-08-29 14:26:09 -07005437// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005438PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005439 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005440{
Andy Hungc0691382018-09-12 18:01:57 -07005441 // clean up deleted track ids in AudioMixer before allocating new tracks
5442 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5443 // for each trackId, destroy it in the AudioMixer
5444 if (mAudioMixer->exists(trackId)) {
5445 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005446 }
5447 });
Andy Hungc0691382018-09-12 18:01:57 -07005448 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005449
5450 mixer_state mixerStatus = MIXER_IDLE;
5451 // find out which tracks need to be processed
5452 size_t count = mActiveTracks.size();
5453 size_t mixedTracks = 0;
5454 size_t tracksWithEffect = 0;
5455 // counts only _active_ fast tracks
5456 size_t fastTracks = 0;
5457 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5458
5459 float masterVolume = mMasterVolume;
5460 bool masterMute = mMasterMute;
5461
5462 if (masterMute) {
5463 masterVolume = 0;
5464 }
5465 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005466 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005467 if (chain != 0) {
5468 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5469 chain->setVolume_l(&v, &v);
5470 masterVolume = (float)((v + (1 << 23)) >> 24);
5471 chain.clear();
5472 }
5473
5474 // prepare a new state to push
5475 FastMixerStateQueue *sq = NULL;
5476 FastMixerState *state = NULL;
5477 bool didModify = false;
5478 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005479 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005480 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005481 sq = mFastMixer->sq();
5482 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005483 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005484 }
5485
Andy Hung69aed5f2014-02-25 17:24:40 -08005486 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005487 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005488
Andy Hungbd3b2b02018-05-21 10:53:11 -07005489 // DeferredOperations handles statistics after setting mixerStatus.
5490 class DeferredOperations {
5491 public:
Andy Hungea840382020-05-05 21:50:17 -07005492 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5493 : mMixerStatus(mixerStatus)
5494 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005495
5496 // when leaving scope, tally frames properly.
5497 ~DeferredOperations() {
5498 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5499 // because that is when the underrun occurs.
5500 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005501 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005502 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005503 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005504 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005505 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005506 }
5507 }
Andy Hungea840382020-05-05 21:50:17 -07005508 // send the max underrun frames for this mixer period
5509 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005510 }
5511
5512 // tallyUnderrunFrames() is called to update the track counters
5513 // with the number of underrun frames for a particular mixer period.
5514 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005515 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005516 mUnderrunFrames.emplace_back(track, underrunFrames);
5517 }
5518
5519 private:
5520 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005521 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005522 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005523 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005524 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005525
jiabin245cdd92018-12-07 17:55:15 -08005526 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005527 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005528 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005529
5530 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005531 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005532
5533 // process fast tracks
5534 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005535 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5536 "%s(%d): FastTrack(%d) present without FastMixer",
5537 __func__, id(), track->id());
5538
jiabin245cdd92018-12-07 17:55:15 -08005539 if (track->getHapticPlaybackEnabled()) {
5540 noFastHapticTrack = false;
5541 }
Eric Laurent81784c32012-11-19 14:55:58 -08005542
5543 // It's theoretically possible (though unlikely) for a fast track to be created
5544 // and then removed within the same normal mix cycle. This is not a problem, as
5545 // the track never becomes active so it's fast mixer slot is never touched.
5546 // The converse, of removing an (active) track and then creating a new track
5547 // at the identical fast mixer slot within the same normal mix cycle,
5548 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005549 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005550 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005551 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5552 FastTrack *fastTrack = &state->mFastTracks[j];
5553
5554 // Determine whether the track is currently in underrun condition,
5555 // and whether it had a recent underrun.
5556 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5557 FastTrackUnderruns underruns = ftDump->mUnderruns;
5558 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005559 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005560 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005561 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005562 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005563 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005564 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005565 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005566 // don't count underruns that occur while stopping or pausing
5567 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005568 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005569 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5570 recentUnderruns > 0) {
5571 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005572 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005573 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005574 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005575 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005576
5577 // This is similar to the state machine for normal tracks,
5578 // with a few modifications for fast tracks.
5579 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005580 switch (track->state()) {
5581 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005582 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005583 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005584 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005585 }
5586 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005587 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005588 // ramp down is not yet implemented
5589 track->setPaused();
5590 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005591 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005592 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005593 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005594 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005595 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005596 if (recentFull > 0 || recentPartial > 0) {
5597 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005598 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005599 }
5600 if (recentUnderruns == 0) {
5601 // no recent underruns: stay active
5602 break;
5603 }
5604 // there has recently been an underrun of some kind
5605 if (track->sharedBuffer() == 0) {
5606 // were any of the recent underruns "empty" (no frames available)?
5607 if (recentEmpty == 0) {
5608 // no, then ignore the partial underruns as they are allowed indefinitely
5609 break;
5610 }
5611 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005612 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005613 break;
5614 }
5615 // indicate to client process that the track was disabled because of underrun;
5616 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005617 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005618 // remove from active list, but state remains ACTIVE [confusing but true]
5619 isActive = false;
5620 break;
5621 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005622 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005623 case IAfTrackBase::STOPPING_2:
5624 case IAfTrackBase::PAUSED:
5625 case IAfTrackBase::STOPPED:
5626 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005627 // Check for presentation complete if track is inactive
5628 // We have consumed all the buffers of this track.
5629 // This would be incomplete if we auto-paused on underrun
5630 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005631 uint32_t latency = 0;
5632 status_t result = mOutput->stream->getLatency(&latency);
5633 ALOGE_IF(result != OK,
5634 "Error when retrieving output stream latency: %d", result);
5635 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005636 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005637 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5638 // track stays in active list until presentation is complete
5639 break;
5640 }
5641 }
5642 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005643 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005644 }
5645 if (track->isStopped()) {
5646 // Can't reset directly, as fast mixer is still polling this track
5647 // track->reset();
5648 // So instead mark this track as needing to be reset after push with ack
5649 resetMask |= 1 << i;
5650 }
5651 isActive = false;
5652 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005653 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005654 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005655 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005656 }
5657
5658 if (isActive) {
5659 // was it previously inactive?
5660 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005661 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5662 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005663 fastTrack->mBufferProvider = eabp;
5664 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005665 fastTrack->mChannelMask = track->channelMask();
5666 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005667 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005668 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005669 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005670 fastTrack->mGeneration++;
5671 state->mTrackMask |= 1 << j;
5672 didModify = true;
5673 // no acknowledgement required for newly active tracks
5674 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005675 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005676 float volume;
5677 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5678 volume = 0.f;
5679 } else {
5680 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5681 }
5682
5683 handleVoipVolume_l(&volume);
5684
Eric Laurent81784c32012-11-19 14:55:58 -08005685 // cache the combined master volume and stream type volume for fast mixer; this
5686 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005687 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005688 proxy->framesReleased()).first;
5689 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005690 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005691 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005692 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5693 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5694
Andy Hung583043b2023-07-17 17:05:00 -07005695 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005696 /*muteState=*/{masterVolume == 0.f,
5697 mStreamTypes[track->streamType()].volume == 0.f,
5698 mStreamTypes[track->streamType()].mute,
5699 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005700 vlf == 0.f && vrf == 0.f,
5701 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005702
5703 vlf *= volume;
5704 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005705
jiabin76d94692022-12-15 21:51:21 +00005706 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005707 ++fastTracks;
5708 } else {
5709 // was it previously active?
5710 if (state->mTrackMask & (1 << j)) {
5711 fastTrack->mBufferProvider = NULL;
5712 fastTrack->mGeneration++;
5713 state->mTrackMask &= ~(1 << j);
5714 didModify = true;
5715 // If any fast tracks were removed, we must wait for acknowledgement
5716 // because we're about to decrement the last sp<> on those tracks.
5717 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5718 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005719 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5720 // AudioTrack may start (which may not be with a start() but with a write()
5721 // after underrun) and immediately paused or released. In that case the
5722 // FastTrack state hasn't had time to update.
5723 // TODO Remove the ALOGW when this theory is confirmed.
5724 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005725 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005726 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005727 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005728 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005729 }
5730 tracksToRemove->add(track);
5731 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005732 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005733 }
jiabin245cdd92018-12-07 17:55:15 -08005734 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5735 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5736 didModify = true;
5737 }
Eric Laurent81784c32012-11-19 14:55:58 -08005738 continue;
5739 }
5740
5741 { // local variable scope to avoid goto warning
5742
5743 audio_track_cblk_t* cblk = track->cblk();
5744
5745 // The first time a track is added we wait
5746 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005747 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005748
5749 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005750 // use the trackId as the AudioMixer name.
5751 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005752 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005753 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005754 track->channelMask(),
5755 track->format(),
5756 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005757 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005758 ALOGW("%s(): AudioMixer cannot create track(%d)"
5759 " mask %#x, format %#x, sessionId %d",
5760 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005761 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005762 tracksToRemove->add(track);
5763 track->invalidate(); // consider it dead.
5764 continue;
5765 }
5766 }
5767
Eric Laurent81784c32012-11-19 14:55:58 -08005768 // make sure that we have enough frames to mix one full buffer.
5769 // enforce this condition only once to enable draining the buffer in case the client
5770 // app does not call stop() and relies on underrun to stop:
5771 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5772 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005773 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005774 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5775 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005776
5777 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005778 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005779 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5780 // add frames already consumed but not yet released by the resampler
5781 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005782 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005783
Eric Laurent81784c32012-11-19 14:55:58 -08005784 uint32_t minFrames = 1;
5785 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5786 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005787 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005788 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005789
5790 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005791 if (ATRACE_ENABLED()) {
5792 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005793 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005794 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005795 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005796 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005797 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005798 !track->isPaused() && !track->isTerminated())
5799 {
Andy Hungc0691382018-09-12 18:01:57 -07005800 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005801
5802 mixedTracks++;
5803
Andy Hung69aed5f2014-02-25 17:24:40 -08005804 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5805 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005806 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005807 if (track->mainBuffer() != mSinkBuffer &&
5808 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005809 if (mEffectBufferEnabled) {
5810 mEffectBufferValid = true; // Later can set directly.
5811 }
Eric Laurent81784c32012-11-19 14:55:58 -08005812 chain = getEffectChain_l(track->sessionId());
5813 // Delegate volume control to effect in track effect chain if needed
5814 if (chain != 0) {
5815 tracksWithEffect++;
5816 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005817 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005818 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005819 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005820 }
5821 }
5822
5823
5824 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005825 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005826 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005827 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5828 if (track->state() == IAfTrackBase::RESUMING) {
5829 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005830 // If a new track is paused immediately after start, do not ramp on resume.
5831 if (cblk->mServer != 0) {
5832 param = AudioMixer::RAMP_VOLUME;
5833 }
Eric Laurent81784c32012-11-19 14:55:58 -08005834 }
Andy Hungc0691382018-09-12 18:01:57 -07005835 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005836 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005837 // FIXME should not make a decision based on mServer
5838 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005839 // If the track is stopped before the first frame was mixed,
5840 // do not apply ramp
5841 param = AudioMixer::RAMP_VOLUME;
5842 }
5843
5844 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005845 uint32_t vl, vr; // in U8.24 integer format
5846 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005847 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005848 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005849 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005850 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005851 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005852 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005853
Eric Laurenteab90452019-06-24 15:17:46 -07005854 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5855 v = 0;
5856 }
5857
5858 handleVoipVolume_l(&v);
5859
5860 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005861 vl = vr = 0;
5862 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005863 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005864 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005865 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005866 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5867 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005868 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005869 if (vlf > GAIN_FLOAT_UNITY) {
5870 ALOGV("Track left volume out of range: %.3g", vlf);
5871 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005872 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005873 if (vrf > GAIN_FLOAT_UNITY) {
5874 ALOGV("Track right volume out of range: %.3g", vrf);
5875 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005876 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005877
Andy Hung583043b2023-07-17 17:05:00 -07005878 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005879 /*muteState=*/{masterVolume == 0.f,
5880 mStreamTypes[track->streamType()].volume == 0.f,
5881 mStreamTypes[track->streamType()].mute,
5882 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005883 vlf == 0.f && vrf == 0.f,
5884 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005885
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005886 // now apply the master volume and stream type volume and shaper volume
5887 vlf *= v * vh;
5888 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005889 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005890 // then derive vl and vr as U8.24 versions for the effect chain
5891 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5892 vl = (uint32_t) (scaleto8_24 * vlf);
5893 vr = (uint32_t) (scaleto8_24 * vrf);
5894 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005895 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005896 // send level comes from shared memory and so may be corrupt
5897 if (sendLevel > MAX_GAIN_INT) {
5898 ALOGV("Track send level out of range: %04X", sendLevel);
5899 sendLevel = MAX_GAIN_INT;
5900 }
Andy Hung6be49402014-05-30 10:42:03 -07005901 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5902 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005903 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005904
jiabin76d94692022-12-15 21:51:21 +00005905 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005906
Eric Laurent81784c32012-11-19 14:55:58 -08005907 // Delegate volume control to effect in track effect chain if needed
5908 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5909 // Do not ramp volume if volume is controlled by effect
5910 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005911 // Update remaining floating point volume levels
5912 vlf = (float)vl / (1 << 24);
5913 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005914 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005915 } else {
5916 // force no volume ramp when volume controller was just disabled or removed
5917 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005918 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005919 param = AudioMixer::VOLUME;
5920 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005921 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005922 }
5923
Eric Laurent81784c32012-11-19 14:55:58 -08005924 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005925 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005926 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005927
Andy Hungc0691382018-09-12 18:01:57 -07005928 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5929 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5930 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005931 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005932 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005933 AudioMixer::TRACK,
5934 AudioMixer::FORMAT, (void *)track->format());
5935 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005936 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005937 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005938 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005939
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005940 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005941 mAudioMixer->setParameter(
5942 trackId,
5943 AudioMixer::TRACK,
5944 AudioMixer::MIXER_CHANNEL_MASK,
5945 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5946 } else {
5947 mAudioMixer->setParameter(
5948 trackId,
5949 AudioMixer::TRACK,
5950 AudioMixer::MIXER_CHANNEL_MASK,
5951 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5952 }
5953
Glenn Kastene3aa6592012-12-04 12:22:46 -08005954 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005955 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005956 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005957 if (reqSampleRate == 0) {
5958 reqSampleRate = mSampleRate;
5959 } else if (reqSampleRate > maxSampleRate) {
5960 reqSampleRate = maxSampleRate;
5961 }
Eric Laurent81784c32012-11-19 14:55:58 -08005962 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005963 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005964 AudioMixer::RESAMPLE,
5965 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005966 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005967
Andy Hung8edb8dc2015-03-26 19:13:55 -07005968 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005969 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005970 AudioMixer::TIMESTRETCH,
5971 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005972 // cast away constness for this generic API.
5973 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005974
Andy Hung69aed5f2014-02-25 17:24:40 -08005975 /*
5976 * Select the appropriate output buffer for the track.
5977 *
Andy Hung98ef9782014-03-04 14:46:50 -08005978 * Tracks with effects go into their own effects chain buffer
5979 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005980 *
5981 * Other tracks can use mMixerBuffer for higher precision
5982 * channel accumulation. If this buffer is enabled
5983 * (mMixerBufferEnabled true), then selected tracks will accumulate
5984 * into it.
5985 *
5986 */
5987 if (mMixerBufferEnabled
5988 && (track->mainBuffer() == mSinkBuffer
5989 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005990 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005991 mAudioMixer->setParameter(
5992 trackId,
5993 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005994 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005995 mAudioMixer->setParameter(
5996 trackId,
5997 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005998 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005999 } else {
6000 mAudioMixer->setParameter(
6001 trackId,
6002 AudioMixer::TRACK,
6003 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6004 mAudioMixer->setParameter(
6005 trackId,
6006 AudioMixer::TRACK,
6007 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6008 // TODO: override track->mainBuffer()?
6009 mMixerBufferValid = true;
6010 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006011 } else {
6012 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006013 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006014 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006015 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006016 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006017 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006018 AudioMixer::TRACK,
6019 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6020 }
Eric Laurent81784c32012-11-19 14:55:58 -08006021 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006022 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006023 AudioMixer::TRACK,
6024 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006025 mAudioMixer->setParameter(
6026 trackId,
6027 AudioMixer::TRACK,
6028 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006029 mAudioMixer->setParameter(
6030 trackId,
6031 AudioMixer::TRACK,
6032 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07006033 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006034 mAudioMixer->setParameter(
6035 trackId,
6036 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006037 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006038
6039 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006040 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006041
6042 // If one track is ready, set the mixer ready if:
6043 // - the mixer was not ready during previous round OR
6044 // - no other track is not ready
6045 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6046 mixerStatus != MIXER_TRACKS_ENABLED) {
6047 mixerStatus = MIXER_TRACKS_READY;
6048 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006049
6050 // Enable the next few lines to instrument a test for underrun log handling.
6051 // TODO: Remove when we have a better way of testing the underrun log.
6052#if 0
6053 static int i;
6054 if ((++i & 0xf) == 0) {
6055 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6056 }
6057#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006058 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006059 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006060 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006061 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6062 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006063 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006064 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006065 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006066
Eric Laurent81784c32012-11-19 14:55:58 -08006067 // clear effect chain input buffer if an active track underruns to avoid sending
6068 // previous audio buffer again to effects
6069 chain = getEffectChain_l(track->sessionId());
6070 if (chain != 0) {
6071 chain->clearInputBuffer();
6072 }
6073
Andy Hungc0691382018-09-12 18:01:57 -07006074 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006075 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6076 track->isStopped() || track->isPaused()) {
6077 // We have consumed all the buffers of this track.
6078 // Remove it from the list of active tracks.
6079 // TODO: use actual buffer filling status instead of latency when available from
6080 // audio HAL
6081 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006082 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006083 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6084 if (track->isStopped()) {
6085 track->reset();
6086 }
6087 tracksToRemove->add(track);
6088 }
6089 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006090 // No buffers for this track. Give it a few chances to
6091 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006092 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006093 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6094 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006095 tracksToRemove->add(track);
6096 // indicate to client process that the track was disabled because of underrun;
6097 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006098 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006099 // If one track is not ready, mark the mixer also not ready if:
6100 // - the mixer was ready during previous round OR
6101 // - no other track is ready
6102 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6103 mixerStatus != MIXER_TRACKS_READY) {
6104 mixerStatus = MIXER_TRACKS_ENABLED;
6105 }
6106 }
Andy Hungc0691382018-09-12 18:01:57 -07006107 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006108 }
6109
6110 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006111
6112 }
6113
jiabin245cdd92018-12-07 17:55:15 -08006114 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6115 // When there is no fast track playing haptic and FastMixer exists,
6116 // enabling the first FastTrack, which provides mixed data from normal
6117 // tracks, to play haptic data.
6118 FastTrack *fastTrack = &state->mFastTracks[0];
6119 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6120 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6121 didModify = true;
6122 }
6123 }
6124
Eric Laurent81784c32012-11-19 14:55:58 -08006125 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006126 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006127 if (didModify) {
6128 state->mFastTracksGen++;
6129 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6130 if (kUseFastMixer == FastMixer_Dynamic &&
6131 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6132 state->mCommand = FastMixerState::COLD_IDLE;
6133 state->mColdFutexAddr = &mFastMixerFutex;
6134 state->mColdGen++;
6135 mFastMixerFutex = 0;
6136 if (kUseFastMixer == FastMixer_Dynamic) {
6137 mNormalSink = mOutputSink;
6138 }
6139 // If we go into cold idle, need to wait for acknowledgement
6140 // so that fast mixer stops doing I/O.
6141 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6142 pauseAudioWatchdog = true;
6143 }
Eric Laurent81784c32012-11-19 14:55:58 -08006144 }
6145 if (sq != NULL) {
6146 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006147 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6148 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6149 // when bringing the output sink into standby.)
6150 //
6151 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6152 //
6153 // This occurs with BT suspend when we idle the FastMixer with
6154 // active tracks, which may be added or removed.
6155 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006156 }
6157#ifdef AUDIO_WATCHDOG
6158 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6159 mAudioWatchdog->pause();
6160 }
6161#endif
6162
6163 // Now perform the deferred reset on fast tracks that have stopped
6164 while (resetMask != 0) {
6165 size_t i = __builtin_ctz(resetMask);
6166 ALOG_ASSERT(i < count);
6167 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006168 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006169 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6170 track->reset();
6171 }
6172
Andy Hung80d03d22018-04-10 10:32:11 -07006173 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6174 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6175 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6176 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6177 // See also the implementation of destroyTrack_l().
6178 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006179 const int trackId = track->id();
6180 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6181 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006182 }
6183 }
6184
Eric Laurent81784c32012-11-19 14:55:58 -08006185 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006186 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006187
Eric Laurentb3f315a2021-07-13 15:09:05 +02006188 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6189 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006190 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006191 }
6192
6193 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006194 // as long as there are effects we should clear the effects buffer, to avoid
6195 // passing a non-clean buffer to the effect chain
6196 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006197 if (mType == SPATIALIZER) {
6198 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6199 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006200 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006201 // sink or mix buffer must be cleared if all tracks are connected to an
6202 // effect chain as in this case the mixer will not write to the sink or mix buffer
6203 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006204 // always clear sink buffer for spatializer output as the output of the spatializer
6205 // effect will be accumulated into it
6206 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6207 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006208 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006209 if (mMixerBufferValid) {
6210 memset(mMixerBuffer, 0, mMixerBufferSize);
6211 // TODO: In testing, mSinkBuffer below need not be cleared because
6212 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6213 // after mixing.
6214 //
6215 // To enforce this guarantee:
6216 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6217 // (mixedTracks == 0 && fastTracks > 0))
6218 // must imply MIXER_TRACKS_READY.
6219 // Later, we may clear buffers regardless, and skip much of this logic.
6220 }
Andy Hung98ef9782014-03-04 14:46:50 -08006221 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006222 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006223 }
6224
6225 // if any fast tracks, then status is ready
6226 mMixerStatusIgnoringFastTracks = mixerStatus;
6227 if (fastTracks > 0) {
6228 mixerStatus = MIXER_TRACKS_READY;
6229 }
6230 return mixerStatus;
6231}
6232
Andy Hungc5007f82023-08-29 14:26:09 -07006233// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006234uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006235{
6236 uint32_t trackCount = 0;
6237 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006238 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006239 trackCount++;
6240 }
6241 }
6242 return trackCount;
6243}
6244
Andy Hungee58e4a2023-07-07 13:47:37 -07006245bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006246{
Brian Lindahl65e90012022-07-27 18:01:07 +02006247 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6248 // could falsely detect that the frame position has stalled due to underrun because we haven't
6249 // given the Audio HAL enough time to update.
6250 const nsecs_t nowNs = systemTime();
6251 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6252 return mLatchedValue;
6253 }
6254 mPreviousNs = nowNs;
6255 mLatchedValue = false;
6256 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006257 uint64_t position = 0;
6258 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006259 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006260 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006261 if (position != mPreviousPosition) {
6262 mPreviousPosition = position;
6263 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006264 }
6265 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006266 return mLatchedValue;
6267}
6268
Andy Hungee58e4a2023-07-07 13:47:37 -07006269void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006270{
6271 mLatchedValue = true;
6272 mPreviousPosition = 0;
6273 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006274}
6275
Andy Hungc5007f82023-08-29 14:26:09 -07006276// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006277bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006278 audio_channel_mask_t channelMask, audio_format_t format,
6279 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006280{
Andy Hung1bc088a2018-02-09 15:57:31 -08006281 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6282 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006283 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006284 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006285 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006286 ALOGW("%s: invalid format: %#x", __func__, format);
6287 return false;
6288 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006289 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006290 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6291 return false;
6292 }
6293 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006294}
6295
Andy Hungc5007f82023-08-29 14:26:09 -07006296// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006297bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006298 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006299{
Eric Laurent81784c32012-11-19 14:55:58 -08006300 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006301 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006302
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006303 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006304
Eric Laurent10351942014-05-08 18:49:52 -07006305 AudioParameter param = AudioParameter(keyValuePair);
6306 int value;
6307 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6308 reconfig = true;
6309 }
6310 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006311 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006312 status = BAD_VALUE;
6313 } else {
6314 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006315 reconfig = true;
6316 }
Eric Laurent10351942014-05-08 18:49:52 -07006317 }
6318 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006319 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006320 status = BAD_VALUE;
6321 } else {
6322 // no need to save value, since it's constant
6323 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006324 }
Eric Laurent10351942014-05-08 18:49:52 -07006325 }
6326 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6327 // do not accept frame count changes if tracks are open as the track buffer
6328 // size depends on frame count and correct behavior would not be guaranteed
6329 // if frame count is changed after track creation
6330 if (!mTracks.isEmpty()) {
6331 status = INVALID_OPERATION;
6332 } else {
6333 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006334 }
Eric Laurent10351942014-05-08 18:49:52 -07006335 }
6336 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006337 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006338 }
Eric Laurent81784c32012-11-19 14:55:58 -08006339
Eric Laurent10351942014-05-08 18:49:52 -07006340 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006341 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006342 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006343 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6344 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006345 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006346 mThreadMetrics.logEndInterval();
6347 mThreadSnapshot.onEnd();
6348 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006349 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006350 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006351 }
Eric Laurent10351942014-05-08 18:49:52 -07006352 if (status == NO_ERROR && reconfig) {
6353 readOutputParameters_l();
6354 delete mAudioMixer;
6355 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006356 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006357 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006358 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006359 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006360 track->channelMask(),
6361 track->format(),
6362 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006363 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006364 "%s(): AudioMixer cannot create track(%d)"
6365 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006366 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006367 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006368 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006369 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006370 }
Eric Laurent81784c32012-11-19 14:55:58 -08006371 }
6372
Dean Wheatley68918102021-03-19 22:09:19 +11006373 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006374}
6375
6376
Andy Hungee58e4a2023-07-07 13:47:37 -07006377void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006378{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006379 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006380 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006381 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006382 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006383 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6384 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6385 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006386 if (hasFastMixer()) {
6387 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6388
6389 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6390 // while we are dumping it. It may be inconsistent, but it won't mutate!
6391 // This is a large object so we place it on the heap.
6392 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006393 const std::unique_ptr<FastMixerDumpState> copy =
6394 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006395 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006396
6397#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006398 // Similar for state queue
6399 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6400 observerCopy.dump(fd);
6401 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6402 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006403#endif
6404
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006405#ifdef AUDIO_WATCHDOG
6406 if (mAudioWatchdog != 0) {
6407 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6408 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6409 wdCopy.dump(fd);
6410 }
6411#endif
6412
6413 } else {
6414 dprintf(fd, " No FastMixer\n");
6415 }
Eric Laurent90cea102023-05-15 15:08:27 +02006416
6417 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6418 mBluetoothLatencyModesEnabled ? "" : "not ");
6419 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6420 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6421 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006422}
6423
Andy Hungee58e4a2023-07-07 13:47:37 -07006424uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006425{
6426 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6427}
6428
Andy Hungee58e4a2023-07-07 13:47:37 -07006429uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006430{
6431 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6432}
6433
Andy Hungee58e4a2023-07-07 13:47:37 -07006434void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006435{
6436 PlaybackThread::cacheParameters_l();
6437
6438 // FIXME: Relaxed timing because of a certain device that can't meet latency
6439 // Should be reduced to 2x after the vendor fixes the driver issue
6440 // increase threshold again due to low power audio mode. The way this warning
6441 // threshold is calculated and its usefulness should be reconsidered anyway.
6442 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6443}
6444
Andy Hungee58e4a2023-07-07 13:47:37 -07006445void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006446 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006447}
6448
Andy Hungee58e4a2023-07-07 13:47:37 -07006449void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006450 // Only handle latency mode if:
6451 // - mBluetoothLatencyModesEnabled is true
6452 // - the HAL supports latency modes
6453 // - the selected device is Bluetooth LE or A2DP
6454 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6455 return;
6456 }
6457 if (mOutDeviceTypeAddrs.size() != 1
6458 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6459 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6460 return;
6461 }
6462
6463 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6464 if (mSupportedLatencyModes.size() == 1) {
6465 // If the HAL only support one latency mode currently, confirm the choice
6466 latencyMode = mSupportedLatencyModes[0];
6467 } else if (mSupportedLatencyModes.size() > 1) {
6468 // Request low latency if:
6469 // - At least one active track is either:
6470 // - a fast track with gaming usage or
6471 // - a track with acessibility usage
6472 for (const auto& track : mActiveTracks) {
6473 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6474 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6475 latencyMode = AUDIO_LATENCY_MODE_LOW;
6476 break;
6477 }
6478 }
6479 }
6480
6481 if (latencyMode != mSetLatencyMode) {
6482 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6483 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6484 __func__, mId, toString(latencyMode).c_str(), status);
6485 if (status == NO_ERROR) {
6486 mSetLatencyMode = latencyMode;
6487 }
6488 }
6489}
6490
Andy Hungee58e4a2023-07-07 13:47:37 -07006491void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006492
6493 if (mOutput == nullptr || mOutput->stream == nullptr) {
6494 return;
6495 }
6496 std::vector<audio_latency_mode_t> latencyModes;
6497 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6498 if (status != NO_ERROR) {
6499 latencyModes.clear();
6500 }
6501 if (latencyModes != mSupportedLatencyModes) {
6502 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6503 __func__, mId, status, toString(latencyModes).c_str());
6504 mSupportedLatencyModes.swap(latencyModes);
6505 sendHalLatencyModesChangedEvent_l();
6506 }
6507}
6508
Andy Hungee58e4a2023-07-07 13:47:37 -07006509status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006510 std::vector<audio_latency_mode_t>* modes) {
6511 if (modes == nullptr) {
6512 return BAD_VALUE;
6513 }
Andy Hung972bec12023-08-31 16:13:39 -07006514 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006515 *modes = mSupportedLatencyModes;
6516 return NO_ERROR;
6517}
6518
Andy Hungee58e4a2023-07-07 13:47:37 -07006519void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006520 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006521 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006522 if (modes != mSupportedLatencyModes) {
6523 ALOGD("%s: thread(%d) supported latency modes: %s",
6524 __func__, mId, toString(modes).c_str());
6525 mSupportedLatencyModes.swap(modes);
6526 sendHalLatencyModesChangedEvent_l();
6527 }
6528}
6529
Andy Hungee58e4a2023-07-07 13:47:37 -07006530status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006531 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6532 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6533 return INVALID_OPERATION;
6534 }
6535 mBluetoothLatencyModesEnabled.store(enabled);
6536 return NO_ERROR;
6537}
6538
Eric Laurent81784c32012-11-19 14:55:58 -08006539// ----------------------------------------------------------------------------
6540
Andy Hungee58e4a2023-07-07 13:47:37 -07006541/* static */
6542sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006543 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006544 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6545 const audio_offload_info_t& offloadInfo) {
6546 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006547 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006548}
6549
Andy Hung583043b2023-07-17 17:05:00 -07006550DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006551 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6552 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006553 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006554 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006555{
Andy Hung583043b2023-07-17 17:05:00 -07006556 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006557}
6558
Andy Hungee58e4a2023-07-07 13:47:37 -07006559DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006560{
6561}
6562
Andy Hungee58e4a2023-07-07 13:47:37 -07006563void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006564{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006565 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006566 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6567 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6568}
6569
Andy Hungee58e4a2023-07-07 13:47:37 -07006570void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006571{
Andy Hung972bec12023-08-31 16:13:39 -07006572 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006573 if (mMasterBalance != balance) {
6574 mMasterBalance.store(balance);
6575 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6576 broadcast_l();
6577 }
6578}
6579
Andy Hungee58e4a2023-07-07 13:47:37 -07006580void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006581{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006582 float left, right;
6583
Andy Hung333ab962019-05-28 20:23:35 -07006584 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006585 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006586
Andy Hung398ffa22022-12-13 19:19:53 -08006587 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6588 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6589
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006590 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6591 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006592
6593 const int64_t volumeShaperFrames =
6594 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6595 const auto [shaperVolume, shaperActive] =
6596 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006597 mVolumeShaperActive = shaperActive;
6598
Vlad Popae2f5aef2022-07-25 16:00:20 +02006599 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6600 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6601 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6602
6603 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6604
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006605 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006606 left = right = 0;
6607 } else {
6608 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006609 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006610
Glenn Kastenc56f3422014-03-21 17:53:17 -07006611 if (left > GAIN_FLOAT_UNITY) {
6612 left = GAIN_FLOAT_UNITY;
6613 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006614 if (right > GAIN_FLOAT_UNITY) {
6615 right = GAIN_FLOAT_UNITY;
6616 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006617 left *= v;
6618 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006619 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006620 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6621 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6622 right *= mMasterBalanceRight;
6623 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006624 }
6625
Andy Hung583043b2023-07-17 17:05:00 -07006626 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006627 /*muteState=*/{mMasterMute,
6628 mStreamTypes[track->streamType()].volume == 0.f,
6629 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006630 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006631 clientVolumeMute,
6632 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006633
Eric Laurentbfb1b832013-01-07 09:53:42 -08006634 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006635 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006636 if (left != mLeftVolFloat || right != mRightVolFloat) {
6637 mLeftVolFloat = left;
6638 mRightVolFloat = right;
6639
Eric Laurentbfb1b832013-01-07 09:53:42 -08006640 // Delegate volume control to effect in track effect chain if needed
6641 // only one effect chain can be present on DirectOutputThread, so if
6642 // there is one, the track is connected to it
6643 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006644 // if effect chain exists, volume is handled by it.
6645 // Convert volumes from float to 8.24
6646 uint32_t vl = (uint32_t)(left * (1 << 24));
6647 uint32_t vr = (uint32_t)(right * (1 << 24));
6648 // Direct/Offload effect chains set output volume in setVolume_l().
6649 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6650 } else {
6651 // otherwise we directly set the volume.
6652 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006653 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006654 }
6655 }
6656}
6657
Andy Hungee58e4a2023-07-07 13:47:37 -07006658void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006659{
Andy Hung8d31fd22023-06-26 19:20:57 -07006660 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6661 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006662
Eric Laurent0f0631e2015-07-06 18:01:25 -07006663 if (previousTrack != 0 && latestTrack != 0) {
6664 if (mType == DIRECT) {
6665 if (previousTrack.get() != latestTrack.get()) {
6666 mFlushPending = true;
6667 }
6668 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006669 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6670 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006671 mFlushPending = true;
6672 }
6673 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006674 } else if (previousTrack == 0) {
6675 // there could be an old track added back during track transition for direct
6676 // output, so always issues flush to flush data of the previous track if it
6677 // was already destroyed with HAL paused, then flush can resume the playback
6678 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006679 }
6680 PlaybackThread::onAddNewTrack_l();
6681}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006682
Andy Hungee58e4a2023-07-07 13:47:37 -07006683PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006684 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006685)
6686{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006687 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006688 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006689 bool doHwPause = false;
6690 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006691
6692 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006693 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006694 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006695 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006696 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006697 continue;
6698 }
6699
Andy Hung8d31fd22023-06-26 19:20:57 -07006700 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006701#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006702 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006703#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006704 // Only consider last track started for volume and mixer state control.
6705 // In theory an older track could underrun and restart after the new one starts
6706 // but as we only care about the transition phase between two tracks on a
6707 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006708 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006709 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006710
Kuowei Li23666472021-01-20 10:23:25 +08006711 if (track->isPausePending()) {
6712 track->pauseAck();
6713 // It is possible a track might have been flushed or stopped.
6714 // Other operations such as flush pending might occur on the next prepare.
6715 if (track->isPausing()) {
6716 track->setPaused();
6717 }
6718 // Always perform pause, as an immediate flush will change
6719 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006720 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006721 doHwPause = true;
6722 mHwPaused = true;
6723 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006724 } else if (track->isFlushPending()) {
6725 track->flushAck();
6726 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006727 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006728 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006729 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006730 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006731 if (last) {
6732 mLeftVolFloat = mRightVolFloat = -1.0;
6733 if (mHwPaused) {
6734 doHwResume = true;
6735 mHwPaused = false;
6736 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006737 }
6738 }
6739
Eric Laurent81784c32012-11-19 14:55:58 -08006740 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006741 // for all its buffers to be filled before processing it.
6742 // Allow draining the buffer in case the client
6743 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006744 // hence the test on (track->retryCount() > 1).
6745 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006746 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6747 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006748 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006749
6750 // target retry count that we will use is based on the time we wait for retries.
6751 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6752 // the retry threshold is when we accept any size for PCM data. This is slightly
6753 // smaller than the retry count so we can push small bits of data without a glitch.
6754 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006755 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006756 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006757 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006758 minFrames = mNormalFrameCount;
6759 } else {
6760 minFrames = 1;
6761 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006762
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006763 const size_t framesReady = track->framesReady();
6764 const int trackId = track->id();
6765 if (ATRACE_ENABLED()) {
6766 std::string traceName("nRdy");
6767 traceName += std::to_string(trackId);
6768 ATRACE_INT(traceName.c_str(), framesReady);
6769 }
6770 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006771 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006772 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006773 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006774
Andy Hung8d31fd22023-06-26 19:20:57 -07006775 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6776 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006777 if (last) {
6778 // make sure processVolume_l() will apply new volume even if 0
6779 mLeftVolFloat = mRightVolFloat = -1.0;
6780 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006781 if (!mHwSupportsPause) {
6782 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006783 }
6784 }
6785
6786 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006787 processVolume_l(track, last);
6788 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006789 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006790 if (previousTrack != 0) {
6791 if (track != previousTrack.get()) {
6792 // Flush any data still being written from last track
6793 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006794 // Invalidate previous track to force a seek when resuming.
6795 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006796 }
6797 }
6798 mPreviousTrack = track;
6799
Eric Laurentd595b7c2013-04-03 17:27:56 -07006800 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006801 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006802 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006803 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006804 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006805 doHwResume = true;
6806 mHwPaused = false;
6807 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006808 }
Eric Laurent81784c32012-11-19 14:55:58 -08006809 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006810 // clear effect chain input buffer if the last active track started underruns
6811 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006812 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006813 mEffectChains[0]->clearInputBuffer();
6814 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006815 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006816 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006817 if (last && mHwPaused) {
6818 doHwResume = true;
6819 mHwPaused = false;
6820 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006821 }
6822 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6823 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006824 // We have consumed all the buffers of this track.
6825 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006826 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006827 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006828 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006829 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006830 if (presComplete) {
6831 mOutput->presentationComplete();
6832 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006833 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006834 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006835 }
Eric Laurent81784c32012-11-19 14:55:58 -08006836 if (track->isStopped()) {
6837 track->reset();
6838 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006839 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006840 }
6841 } else {
6842 // No buffers for this track. Give it a few chances to
6843 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006844 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006845 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006846 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006847 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006848 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006849 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006850 } else {
6851 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6852 tracksToRemove->add(track);
6853 // indicate to client process that the track was disabled because of
6854 // underrun; it will then automatically call start() when data is available
6855 track->disable();
6856 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6857 // unlike mixerthread, HAL can be paused for direct output
6858 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6859 "minFrames = %u, mFormat = %#x",
6860 framesReady, minFrames, mFormat);
6861 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6862 doHwPause = true;
6863 mHwPaused = true;
6864 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006865 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006866 } else if (last) {
6867 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006868 }
6869 }
6870 }
6871 }
6872
Eric Laurentd1f69b02014-12-15 14:33:13 -08006873 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006874 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006875 for (size_t i = 0; i < mTracks.size(); i++) {
6876 if (mTracks[i]->isFlushPending()) {
6877 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006878 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006879 }
6880 }
6881 }
6882
6883 // make sure the pause/flush/resume sequence is executed in the right order.
6884 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6885 // before flush and then resume HW. This can happen in case of pause/flush/resume
6886 // if resume is received before pause is executed.
6887 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006888 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006889 status_t result = mOutput->stream->pause();
6890 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006891 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006892 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006893 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006894 flushHw_l();
6895 }
6896 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006897 status_t result = mOutput->stream->resume();
6898 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006899 }
Eric Laurent81784c32012-11-19 14:55:58 -08006900 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006901 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006902
6903 return mixerStatus;
6904}
6905
Andy Hungee58e4a2023-07-07 13:47:37 -07006906void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006907{
Eric Laurent81784c32012-11-19 14:55:58 -08006908 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006909 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006910 // output audio to hardware
6911 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006912 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006913 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006914 status_t status = mActiveTrack->getNextBuffer(&buffer);
6915 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006916 // no need to pad with 0 for compressed audio
6917 if (audio_has_proportional_frames(mFormat)) {
6918 memset(curBuf, 0, frameCount * mFrameSize);
6919 }
Eric Laurent81784c32012-11-19 14:55:58 -08006920 break;
6921 }
6922 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6923 frameCount -= buffer.frameCount;
6924 curBuf += buffer.frameCount * mFrameSize;
6925 mActiveTrack->releaseBuffer(&buffer);
6926 }
Andy Hung2098f272014-02-27 14:00:06 -08006927 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006928 mSleepTimeUs = 0;
6929 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006930 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006931}
6932
Andy Hungee58e4a2023-07-07 13:47:37 -07006933void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006934{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006935 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006936 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006937 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006938 return;
6939 }
Andy Hung85ba3332021-04-27 17:40:26 -07006940 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6941 mSleepTimeUs = mActiveSleepTimeUs;
6942 } else {
6943 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006944 }
Andy Hung85ba3332021-04-27 17:40:26 -07006945 // Note: In S or later, we do not write zeroes for
6946 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006947}
6948
Andy Hungee58e4a2023-07-07 13:47:37 -07006949void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006950{
6951 {
Andy Hung972bec12023-08-31 16:13:39 -07006952 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006953 for (size_t i = 0; i < mTracks.size(); i++) {
6954 if (mTracks[i]->isFlushPending()) {
6955 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006956 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006957 }
6958 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006959 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006960 flushHw_l();
6961 }
6962 }
6963 PlaybackThread::threadLoop_exit();
6964}
6965
6966// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07006967bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006968{
6969 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006970 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006971
6972 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6973 // after a timeout and we will enter standby then.
6974 if (mTracks.size() > 0) {
6975 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006976 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07006977 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006978 }
6979
Eric Laurent5cff4032015-05-26 13:49:58 -07006980 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006981}
6982
Andy Hungc5007f82023-08-29 14:26:09 -07006983// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006984bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006985 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006986{
6987 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006988 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006989
Eric Laurent10351942014-05-08 18:49:52 -07006990 AudioParameter param = AudioParameter(keyValuePair);
6991 int value;
6992 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006993 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006994 }
Eric Laurent10351942014-05-08 18:49:52 -07006995 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6996 // do not accept frame count changes if tracks are open as the track buffer
6997 // size depends on frame count and correct behavior would not be garantied
6998 // if frame count is changed after track creation
6999 if (!mTracks.isEmpty()) {
7000 status = INVALID_OPERATION;
7001 } else {
7002 reconfig = true;
7003 }
7004 }
7005 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007006 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007007 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007008 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007009 if (!mStandby) {
7010 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007011 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007012 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007013 }
Eric Laurent10351942014-05-08 18:49:52 -07007014 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007015 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007016 }
7017 if (status == NO_ERROR && reconfig) {
7018 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007019 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007020 }
7021 }
7022
Dean Wheatley68918102021-03-19 22:09:19 +11007023 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007024}
7025
Andy Hungee58e4a2023-07-07 13:47:37 -07007026uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007027{
7028 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007029 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007030 time = PlaybackThread::activeSleepTimeUs();
7031 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007032 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007033 }
7034 return time;
7035}
7036
Andy Hungee58e4a2023-07-07 13:47:37 -07007037uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007038{
7039 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007040 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007041 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7042 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007043 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007044 }
7045 return time;
7046}
7047
Andy Hungee58e4a2023-07-07 13:47:37 -07007048uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007049{
7050 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007051 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007052 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7053 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007054 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007055 }
7056 return time;
7057}
7058
Andy Hungee58e4a2023-07-07 13:47:37 -07007059void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007060{
7061 PlaybackThread::cacheParameters_l();
7062
7063 // use shorter standby delay as on normal output to release
7064 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007065 // no delay on outputs with HW A/V sync
7066 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007067 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007068 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007069 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007070 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007071 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007072 }
Eric Laurent81784c32012-11-19 14:55:58 -08007073}
7074
Andy Hungee58e4a2023-07-07 13:47:37 -07007075void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007076{
ziyangch8f194f12021-12-01 13:48:04 -08007077 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007078 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007079 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007080 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007081 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007082 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007083 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007084}
7085
Andy Hungee58e4a2023-07-07 13:47:37 -07007086int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007087 // If a VolumeShaper is active, we must wake up periodically to update volume.
7088 const int64_t NS_PER_MS = 1000000;
7089 return mVolumeShaperActive ?
7090 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7091}
7092
Eric Laurent81784c32012-11-19 14:55:58 -08007093// ----------------------------------------------------------------------------
7094
Andy Hungee58e4a2023-07-07 13:47:37 -07007095AsyncCallbackThread::AsyncCallbackThread(
7096 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007097 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007098 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007099 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007100 mDrainSequence(0),
7101 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007102{
7103}
7104
Andy Hungee58e4a2023-07-07 13:47:37 -07007105void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007106{
7107 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7108}
7109
Andy Hungee58e4a2023-07-07 13:47:37 -07007110bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007111{
7112 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007113 uint32_t writeAckSequence;
7114 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007115 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007116
7117 {
Andy Hungc5007f82023-08-29 14:26:09 -07007118 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007119 while (!((mWriteAckSequence & 1) ||
7120 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007121 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007122 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007123 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007124 }
7125
Eric Laurentbfb1b832013-01-07 09:53:42 -08007126 if (exitPending()) {
7127 break;
7128 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007129 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7130 mWriteAckSequence, mDrainSequence);
7131 writeAckSequence = mWriteAckSequence;
7132 mWriteAckSequence &= ~1;
7133 drainSequence = mDrainSequence;
7134 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007135 asyncError = mAsyncError;
7136 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007137 }
7138 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007139 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007140 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007141 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007142 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007143 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007144 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007145 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007146 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007147 if (asyncError) {
7148 playbackThread->onAsyncError();
7149 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007150 }
7151 }
7152 }
7153 return false;
7154}
7155
Andy Hungee58e4a2023-07-07 13:47:37 -07007156void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007157{
7158 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007159 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007160 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007161 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007162}
7163
Andy Hungee58e4a2023-07-07 13:47:37 -07007164void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007165{
Andy Hung972bec12023-08-31 16:13:39 -07007166 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007167 // bit 0 is cleared
7168 mWriteAckSequence = sequence << 1;
7169}
7170
Andy Hungee58e4a2023-07-07 13:47:37 -07007171void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007172{
Andy Hung972bec12023-08-31 16:13:39 -07007173 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007174 // ignore unexpected callbacks
7175 if (mWriteAckSequence & 2) {
7176 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007177 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007178 }
7179}
7180
Andy Hungee58e4a2023-07-07 13:47:37 -07007181void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007182{
Andy Hung972bec12023-08-31 16:13:39 -07007183 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007184 // bit 0 is cleared
7185 mDrainSequence = sequence << 1;
7186}
7187
Andy Hungee58e4a2023-07-07 13:47:37 -07007188void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007189{
Andy Hung972bec12023-08-31 16:13:39 -07007190 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007191 // ignore unexpected callbacks
7192 if (mDrainSequence & 2) {
7193 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007194 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007195 }
7196}
7197
Andy Hungee58e4a2023-07-07 13:47:37 -07007198void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007199{
Andy Hung972bec12023-08-31 16:13:39 -07007200 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007201 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007202 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007203}
7204
Eric Laurentbfb1b832013-01-07 09:53:42 -08007205
7206// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007207
7208/* static */
7209sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007210 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007211 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7212 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007213 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007214}
7215
Andy Hung583043b2023-07-17 17:05:00 -07007216OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007217 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7218 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007219 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007220 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007221{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007222 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007223 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007224 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007225}
7226
Andy Hungee58e4a2023-07-07 13:47:37 -07007227void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007228{
7229 if (mFlushPending || mHwPaused) {
7230 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007231 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007232 flushHw_l();
7233 } else {
7234 mMixerStatus = MIXER_DRAIN_ALL;
7235 threadLoop_drain();
7236 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007237 if (mUseAsyncWrite) {
7238 ALOG_ASSERT(mCallbackThread != 0);
7239 mCallbackThread->exit();
7240 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007241 PlaybackThread::threadLoop_exit();
7242}
7243
Andy Hungee58e4a2023-07-07 13:47:37 -07007244PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007245 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007246)
7247{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007248 size_t count = mActiveTracks.size();
7249
7250 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007251 bool doHwPause = false;
7252 bool doHwResume = false;
7253
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007254 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007255
Eric Laurentbfb1b832013-01-07 09:53:42 -08007256 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007257 for (const sp<IAfTrack>& t : mActiveTracks) {
7258 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007259#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007260 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007261#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007262 // Only consider last track started for volume and mixer state control.
7263 // In theory an older track could underrun and restart after the new one starts
7264 // but as we only care about the transition phase between two tracks on a
7265 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007266 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007267 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007268
Haynes Mathew George7844f672014-01-15 12:32:55 -08007269 if (track->isInvalid()) {
7270 ALOGW("An invalidated track shouldn't be in active list");
7271 tracksToRemove->add(track);
7272 continue;
7273 }
7274
Andy Hung8d31fd22023-06-26 19:20:57 -07007275 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007276 ALOGW("An idle track shouldn't be in active list");
7277 continue;
7278 }
7279
Kuowei Li23666472021-01-20 10:23:25 +08007280 if (track->isPausePending()) {
7281 track->pauseAck();
7282 // It is possible a track might have been flushed or stopped.
7283 // Other operations such as flush pending might occur on the next prepare.
7284 if (track->isPausing()) {
7285 track->setPaused();
7286 }
7287 // Always perform pause if last, as an immediate flush will change
7288 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007289 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007290 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007291 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007292 mHwPaused = true;
7293 }
7294 // If we were part way through writing the mixbuffer to
7295 // the HAL we must save this until we resume
7296 // BUG - this will be wrong if a different track is made active,
7297 // in that case we want to discard the pending data in the
7298 // mixbuffer and tell the client to present it again when the
7299 // track is resumed
7300 mPausedWriteLength = mCurrentWriteLength;
7301 mPausedBytesRemaining = mBytesRemaining;
7302 mBytesRemaining = 0; // stop writing
7303 }
7304 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007305 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007306 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007307 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007308 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007309 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007310 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007311 track->flushAck();
7312 if (last) {
7313 mFlushPending = true;
7314 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007315 } else if (track->isResumePending()){
7316 track->resumeAck();
7317 if (last) {
7318 if (mPausedBytesRemaining) {
7319 // Need to continue write that was interrupted
7320 mCurrentWriteLength = mPausedWriteLength;
7321 mBytesRemaining = mPausedBytesRemaining;
7322 mPausedBytesRemaining = 0;
7323 }
7324 if (mHwPaused) {
7325 doHwResume = true;
7326 mHwPaused = false;
7327 // threadLoop_mix() will handle the case that we need to
7328 // resume an interrupted write
7329 }
7330 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007331 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007332
Eric Laurent3df841a2016-07-15 15:15:40 -07007333 mLeftVolFloat = mRightVolFloat = -1.0;
7334
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007335 // Do not handle new data in this iteration even if track->framesReady()
7336 mixerStatus = MIXER_TRACKS_ENABLED;
7337 }
7338 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007339 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007340 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007341 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7342 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007343 if (last) {
7344 // make sure processVolume_l() will apply new volume even if 0
7345 mLeftVolFloat = mRightVolFloat = -1.0;
7346 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007347 }
7348
7349 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007350 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007351 if (previousTrack != 0) {
7352 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007353 // Flush any data still being written from last track
7354 mBytesRemaining = 0;
7355 if (mPausedBytesRemaining) {
7356 // Last track was paused so we also need to flush saved
7357 // mixbuffer state and invalidate track so that it will
7358 // re-submit that unwritten data when it is next resumed
7359 mPausedBytesRemaining = 0;
7360 // Invalidate is a bit drastic - would be more efficient
7361 // to have a flag to tell client that some of the
7362 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007363 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007364 }
7365 // flush data already sent to the DSP if changing audio session as audio
7366 // comes from a different source. Also invalidate previous track to force a
7367 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007368 if (previousTrack->sessionId() != track->sessionId()) {
7369 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007370 }
7371 }
7372 }
7373 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007374 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007375 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007376 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007377 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007378 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007379 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007380 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381 mixerStatus = MIXER_TRACKS_READY;
7382 }
7383 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007384 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007385 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007386 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007387 // Hardware buffer can hold a large amount of audio so we must
7388 // wait for all current track's data to drain before we say
7389 // that the track is stopped.
7390 if (mBytesRemaining == 0) {
7391 // Only start draining when all data in mixbuffer
7392 // has been written
7393 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007394 track->setState(IAfTrackBase::STOPPING_2);
7395 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007396 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7397 if (last && !mStandby) {
7398 // do not modify drain sequence if we are already draining. This happens
7399 // when resuming from pause after drain.
7400 if ((mDrainSequence & 1) == 0) {
7401 mSleepTimeUs = 0;
7402 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7403 mixerStatus = MIXER_DRAIN_TRACK;
7404 mDrainSequence += 2;
7405 }
7406 if (mHwPaused) {
7407 // It is possible to move from PAUSED to STOPPING_1 without
7408 // a resume so we must ensure hardware is running
7409 doHwResume = true;
7410 mHwPaused = false;
7411 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007412 }
7413 }
Eric Laurente93cc032016-05-05 10:15:10 -07007414 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007415 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007416 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007417 }
7418 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007419 // Drain has completed or we are in standby, signal presentation complete
7420 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007421 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007422 mOutput->presentationComplete();
7423 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007424 track->reset();
7425 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007426 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007427 if (!mUseAsyncWrite) {
7428 // If we don't get explicit drain notification we must
7429 // register discontinuity regardless of whether this is
7430 // the previous (!last) or the upcoming (last) track
7431 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007432 mTimestampVerifier.discontinuity(
7433 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007434 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007435 }
7436 } else {
7437 // No buffers for this track. Give it a few chances to
7438 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007439 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007440 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007441 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007442 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007443 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007444 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007445 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7446 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007447 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007448 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007449 // it will then automatically call start() when data is available
7450 track->disable();
7451 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007452 } else if (last){
7453 mixerStatus = MIXER_TRACKS_ENABLED;
7454 }
7455 }
7456 }
7457 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007458 if (track->isReady()) { // check ready to prevent premature start.
7459 processVolume_l(track, last);
7460 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007461 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007462
Eric Laurentea0fade2013-10-04 16:23:48 -07007463 // make sure the pause/flush/resume sequence is executed in the right order.
7464 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7465 // before flush and then resume HW. This can happen in case of pause/flush/resume
7466 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007467 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007468 status_t result = mOutput->stream->pause();
7469 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007470 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007471 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007472 if (mFlushPending) {
7473 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007474 }
Eric Laurentfd477972013-10-25 18:10:40 -07007475 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007476 status_t result = mOutput->stream->resume();
7477 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007478 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007479
Eric Laurentbfb1b832013-01-07 09:53:42 -08007480 // remove all the tracks that need to be...
7481 removeTracks_l(*tracksToRemove);
7482
7483 return mixerStatus;
7484}
7485
Eric Laurentbfb1b832013-01-07 09:53:42 -08007486// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007487bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007488{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007489 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7490 mWriteAckSequence, mDrainSequence);
7491 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007492 return true;
7493 }
7494 return false;
7495}
7496
Andy Hungee58e4a2023-07-07 13:47:37 -07007497bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007498{
Andy Hung972bec12023-08-31 16:13:39 -07007499 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007500 return waitingAsyncCallback_l();
7501}
7502
Andy Hungee58e4a2023-07-07 13:47:37 -07007503void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007504{
Eric Laurente659ef42014-09-29 13:06:46 -07007505 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007506 // Flush anything still waiting in the mixbuffer
7507 mCurrentWriteLength = 0;
7508 mBytesRemaining = 0;
7509 mPausedWriteLength = 0;
7510 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007511 // reset bytes written count to reflect that DSP buffers are empty after flush.
7512 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007513
Eric Laurentbfb1b832013-01-07 09:53:42 -08007514 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007515 // discard any pending drain or write ack by incrementing sequence
7516 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7517 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007518 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007519 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7520 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007521 }
7522}
7523
Andy Hungee58e4a2023-07-07 13:47:37 -07007524void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007525{
Andy Hung972bec12023-08-31 16:13:39 -07007526 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007527 if (PlaybackThread::invalidateTracks_l(streamType)) {
7528 mFlushPending = true;
7529 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007530}
7531
Andy Hungee58e4a2023-07-07 13:47:37 -07007532void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007533 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007534 if (PlaybackThread::invalidateTracks_l(portIds)) {
7535 mFlushPending = true;
7536 }
7537}
7538
Eric Laurentbfb1b832013-01-07 09:53:42 -08007539// ----------------------------------------------------------------------------
7540
Andy Hungee58e4a2023-07-07 13:47:37 -07007541/* static */
7542sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007543 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007544 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007545 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007546}
7547
Andy Hung583043b2023-07-17 17:05:00 -07007548DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007549 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007550 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007551 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007552 mWaitTimeMs(UINT_MAX)
7553{
7554 addOutputTrack(mainThread);
7555}
7556
Andy Hungee58e4a2023-07-07 13:47:37 -07007557DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007558{
7559 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7560 mOutputTracks[i]->destroy();
7561 }
7562}
7563
Andy Hungee58e4a2023-07-07 13:47:37 -07007564void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007565{
7566 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007567 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007568 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007569 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007570 if (mMixerBufferValid) {
7571 memset(mMixerBuffer, 0, mMixerBufferSize);
7572 } else {
7573 memset(mSinkBuffer, 0, mSinkBufferSize);
7574 }
Eric Laurent81784c32012-11-19 14:55:58 -08007575 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007576 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007577 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007578 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007579 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007580}
7581
Andy Hungee58e4a2023-07-07 13:47:37 -07007582void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007583{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007584 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007585 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007586 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007587 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007588 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007589 }
7590 } else if (mBytesWritten != 0) {
7591 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7592 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007593 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007594 } else {
7595 // flush remaining overflow buffers in output tracks
7596 writeFrames = 0;
7597 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007598 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007599 }
7600}
7601
Andy Hungee58e4a2023-07-07 13:47:37 -07007602ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007603{
7604 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007605 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7606
7607 // Consider the first OutputTrack for timestamp and frame counting.
7608
7609 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7610 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7611 // we always claim success.
7612 if (i == 0) {
7613 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7614 ALOGD_IF(correction != 0 && writeFrames != 0,
7615 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7616 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7617 mFramesWritten -= correction;
7618 }
7619
7620 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007621 }
Andy Hungcf10d742020-04-28 15:38:24 -07007622 if (mStandby) {
7623 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007624 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007625 mStandby = false;
7626 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007627 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007628}
7629
Andy Hungee58e4a2023-07-07 13:47:37 -07007630void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007631{
7632 // DuplicatingThread implements standby by stopping all tracks
7633 for (size_t i = 0; i < outputTracks.size(); i++) {
7634 outputTracks[i]->stop();
7635 }
7636}
7637
Andy Hung8a5abfd2023-12-07 19:35:12 -08007638void DuplicatingThread::threadLoop_exit()
7639{
7640 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7641 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7642 // Do so here in the threadLoop_exit().
7643
7644 SortedVector <sp<IAfOutputTrack>> localTracks;
7645 {
7646 audio_utils::lock_guard l(mutex());
7647 localTracks = std::move(mOutputTracks);
7648 mOutputTracks.clear();
7649 }
7650 localTracks.clear();
7651 outputTracks.clear();
7652 PlaybackThread::threadLoop_exit();
7653}
7654
Andy Hungee58e4a2023-07-07 13:47:37 -07007655void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007656{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007657 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007658
7659 std::stringstream ss;
7660 const size_t numTracks = mOutputTracks.size();
7661 ss << " " << numTracks << " OutputTracks";
7662 if (numTracks > 0) {
7663 ss << ":";
7664 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007665 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007666 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007667 if (thread.get() != nullptr) {
7668 ss << thread.get() << ", " << thread->id();
7669 } else {
7670 ss << "null";
7671 }
7672 ss << ")";
7673 }
7674 }
7675 ss << "\n";
7676 std::string result = ss.str();
7677 write(fd, result.c_str(), result.size());
7678}
7679
Andy Hungee58e4a2023-07-07 13:47:37 -07007680void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007681{
7682 outputTracks = mOutputTracks;
7683}
7684
Andy Hungee58e4a2023-07-07 13:47:37 -07007685void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007686{
7687 outputTracks.clear();
7688}
7689
Andy Hungee58e4a2023-07-07 13:47:37 -07007690void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007691{
Andy Hung972bec12023-08-31 16:13:39 -07007692 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007693 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7694 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7695 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7696 const size_t frameCount =
7697 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7698 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7699 // from different OutputTracks and their associated MixerThreads (e.g. one may
7700 // nearly empty and the other may be dropping data).
7701
Svet Ganov33761132021-05-13 22:51:08 +00007702 // TODO b/182392769: use attribution source util, move to server edge
7703 AttributionSourceState attributionSource = AttributionSourceState();
7704 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007705 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007706 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007707 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007708 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007709 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007710 this,
7711 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007712 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007713 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007714 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007715 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007716 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7717 if (status != NO_ERROR) {
7718 ALOGE("addOutputTrack() initCheck failed %d", status);
7719 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007720 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007721 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7722 mOutputTracks.add(outputTrack);
7723 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7724 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007725}
7726
Andy Hungee58e4a2023-07-07 13:47:37 -07007727void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007728{
Andy Hung972bec12023-08-31 16:13:39 -07007729 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007730 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7731 if (mOutputTracks[i]->thread() == thread) {
7732 mOutputTracks[i]->destroy();
7733 mOutputTracks.removeAt(i);
7734 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007735 // NO_THREAD_SAFETY_ANALYSIS
7736 // Lambda workaround: as thread != this
7737 // we can safely call the remote thread getOutput.
7738 const bool equalOutput =
7739 [&](){ return thread->getOutput() == mOutput; }();
7740 if (equalOutput) {
7741 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007742 }
Eric Laurent81784c32012-11-19 14:55:58 -08007743 return;
7744 }
7745 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007746 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007747}
7748
Andy Hungc5007f82023-08-29 14:26:09 -07007749// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007750void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007751{
7752 mWaitTimeMs = UINT_MAX;
7753 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007754 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007755 if (strong != 0) {
7756 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7757 if (waitTimeMs < mWaitTimeMs) {
7758 mWaitTimeMs = waitTimeMs;
7759 }
7760 }
7761 }
7762}
7763
Andy Hungee58e4a2023-07-07 13:47:37 -07007764bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007765{
7766 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007767 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007768 if (thread == 0) {
7769 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7770 outputTracks[i].get());
7771 return false;
7772 }
Andy Hung87c693c2023-07-06 20:56:16 -07007773 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007774 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007775 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007776 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7777 thread.get());
7778 return false;
7779 }
7780 }
7781 return true;
7782}
7783
Andy Hungee58e4a2023-07-07 13:47:37 -07007784void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007785 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007786{
Kevin Rocard12381092018-04-11 09:19:59 -07007787 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7788 outputTrack->setMetadatas(metadata.tracks);
7789 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007790}
7791
Andy Hungee58e4a2023-07-07 13:47:37 -07007792uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007793{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007794 // return half the wait time in microseconds.
7795 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007796}
7797
Andy Hungee58e4a2023-07-07 13:47:37 -07007798void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007799{
7800 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7801 updateWaitTime_l();
7802
7803 MixerThread::cacheParameters_l();
7804}
7805
Eric Laurentb3f315a2021-07-13 15:09:05 +02007806// ----------------------------------------------------------------------------
7807
Andy Hungee58e4a2023-07-07 13:47:37 -07007808/* static */
7809sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007810 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007811 AudioStreamOut* output,
7812 audio_io_handle_t id,
7813 bool systemReady,
7814 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007815 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007816}
7817
Andy Hung583043b2023-07-17 17:05:00 -07007818SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007819 AudioStreamOut* output,
7820 audio_io_handle_t id,
7821 bool systemReady,
7822 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007823 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007824{
7825}
7826
Andy Hungee58e4a2023-07-07 13:47:37 -07007827void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007828 // if mSupportedLatencyModes is empty, the HAL stream does not support
7829 // latency mode control and we can exit.
7830 if (mSupportedLatencyModes.empty()) {
7831 return;
7832 }
7833 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7834 if (mSupportedLatencyModes.size() == 1) {
7835 // If the HAL only support one latency mode currently, confirm the choice
7836 latencyMode = mSupportedLatencyModes[0];
7837 } else if (mSupportedLatencyModes.size() > 1) {
7838 // Request low latency if:
7839 // - The low latency mode is requested by the spatializer controller
7840 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7841 // AND
7842 // - At least one active track is spatialized
7843 bool hasSpatializedActiveTrack = false;
7844 for (const auto& track : mActiveTracks) {
7845 if (track->isSpatialized()) {
7846 hasSpatializedActiveTrack = true;
7847 break;
7848 }
7849 }
7850 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7851 latencyMode = AUDIO_LATENCY_MODE_LOW;
7852 }
7853 }
7854
7855 if (latencyMode != mSetLatencyMode) {
7856 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007857 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7858 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007859 if (status == NO_ERROR) {
7860 mSetLatencyMode = latencyMode;
7861 }
7862 }
7863}
7864
Andy Hungee58e4a2023-07-07 13:47:37 -07007865status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007866 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7867 return BAD_VALUE;
7868 }
Andy Hung972bec12023-08-31 16:13:39 -07007869 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007870 mRequestedLatencyMode = mode;
7871 return NO_ERROR;
7872}
7873
Andy Hungee58e4a2023-07-07 13:47:37 -07007874void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007875NO_THREAD_SAFETY_ANALYSIS
7876// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007877{
7878 bool hasVirtualizer = false;
7879 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007880 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007881 {
Andy Hung972bec12023-08-31 16:13:39 -07007882 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007883 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007884 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007885 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007886 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7887 }
7888
7889 finalDownMixer = mFinalDownMixer;
7890 mFinalDownMixer.clear();
7891 }
7892
7893 if (hasVirtualizer) {
7894 if (finalDownMixer != nullptr) {
7895 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007896 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007897 }
7898 finalDownMixer.clear();
7899 } else if (!hasDownMixer) {
7900 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007901 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007902 EFFECT_UIID_DOWNMIX, &descriptors);
7903 if (status != NO_ERROR) {
7904 return;
7905 }
7906 ALOG_ASSERT(!descriptors.empty(),
7907 "%s getDescriptors() returned no error but empty list", __func__);
7908
7909 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7910 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007911 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007912
7913 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7914 ALOGW("%s error creating downmixer %d", __func__, status);
7915 finalDownMixer.clear();
7916 } else {
7917 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007918 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007919 }
7920 }
7921
7922 {
Andy Hung972bec12023-08-31 16:13:39 -07007923 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007924 mFinalDownMixer = finalDownMixer;
7925 }
7926}
7927
Andy Hunge2514462023-12-06 14:59:24 -08007928void SpatializerThread::threadLoop_exit()
7929{
7930 // The Spatializer EffectHandle must be released on the PlaybackThread
7931 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
7932 mFinalDownMixer.clear();
7933
7934 PlaybackThread::threadLoop_exit();
7935}
7936
Eric Laurent81784c32012-11-19 14:55:58 -08007937// ----------------------------------------------------------------------------
7938// Record
7939// ----------------------------------------------------------------------------
7940
Andy Hung583043b2023-07-17 17:05:00 -07007941sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007942 AudioStreamIn* input,
7943 audio_io_handle_t id,
7944 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007945 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007946}
7947
Andy Hung583043b2023-07-17 17:05:00 -07007948RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007949 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007950 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007951 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007952 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007953 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007954 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007955 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007956 mActiveTracks(&this->mLocalLog),
7957 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007958 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007959 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007960 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7961 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007962 // mFastCapture below
7963 , mFastCaptureFutex(0)
7964 // mInputSource
7965 // mPipeSink
7966 // mPipeSource
7967 , mPipeFramesP2(0)
7968 // mPipeMemory
7969 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007970 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007971 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007972{
Glenn Kastend7dca052015-03-05 16:05:54 -08007973 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07007974 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007975
George Burgess IVa8f90c12020-05-14 11:27:19 -07007976 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007977 mIsMsdDevice = strcmp(
7978 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7979 }
7980
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007981 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007982
Andy Hungc8fddf32018-08-08 18:32:37 -07007983 // TODO: We may also match on address as well as device type for
7984 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007985 // TODO: This property should be ensure that only contains one single device type.
7986 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7987 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007988 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7989 : AUDIO_DEVICE_NONE));
7990
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007991 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007992 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007993 size_t numCounterOffers = 0;
7994 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007995#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007996 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007997#else
7998 (void)
7999#endif
8000 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008001 ALOG_ASSERT(index == 0);
8002
8003 // initialize fast capture depending on configuration
8004 bool initFastCapture;
8005 switch (kUseFastCapture) {
8006 case FastCapture_Never:
8007 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008008 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008009 break;
8010 case FastCapture_Always:
8011 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008012 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008013 break;
8014 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008015 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008016 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008017 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008018 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8019 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8020 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008021 break;
8022 // case FastCapture_Dynamic:
8023 }
8024
8025 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008026 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008027 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008028 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8029 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008030 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008031 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008032 const sp<MemoryDealer> roHeap(readOnlyHeap());
8033 sp<IMemory> pipeMemory;
8034 if ((roHeap == 0) ||
8035 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008036 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008037 ALOGE("not enough memory for pipe buffer size=%zu; "
8038 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8039 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8040 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008041 goto failed;
8042 }
8043 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8044 memset(pipeBuffer, 0, pipeSize);
8045 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008046 const NBAIO_Format offersFast[1] = {format};
8047 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008048 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008049 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008050 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008051 mPipeSink = pipe;
8052 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008053 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008054 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008055 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008056 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008057 mPipeSource = pipeReader;
8058 mPipeFramesP2 = pipeFramesP2;
8059 mPipeMemory = pipeMemory;
8060
8061 // create fast capture
8062 mFastCapture = new FastCapture();
8063 FastCaptureStateQueue *sq = mFastCapture->sq();
8064#ifdef STATE_QUEUE_DUMP
8065 // FIXME
8066#endif
8067 FastCaptureState *state = sq->begin();
8068 state->mCblk = NULL;
8069 state->mInputSource = mInputSource.get();
8070 state->mInputSourceGen++;
8071 state->mPipeSink = pipe;
8072 state->mPipeSinkGen++;
8073 state->mFrameCount = mFrameCount;
8074 state->mCommand = FastCaptureState::COLD_IDLE;
8075 // already done in constructor initialization list
8076 //mFastCaptureFutex = 0;
8077 state->mColdFutexAddr = &mFastCaptureFutex;
8078 state->mColdGen++;
8079 state->mDumpState = &mFastCaptureDumpState;
8080#ifdef TEE_SINK
8081 // FIXME
8082#endif
Andy Hung583043b2023-07-17 17:05:00 -07008083 mFastCaptureNBLogWriter =
8084 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008085 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8086 sq->end();
8087 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8088
8089 // start the fast capture
8090 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8091 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008092 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008093 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008094#ifdef AUDIO_WATCHDOG
8095 // FIXME
8096#endif
8097
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008098 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008099 }
Andy Hung8946a282018-04-19 20:04:56 -07008100#ifdef TEE_SINK
8101 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8102 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8103#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008104failed: ;
8105
8106 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008107}
8108
Andy Hungee58e4a2023-07-07 13:47:37 -07008109RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008110{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008111 if (mFastCapture != 0) {
8112 FastCaptureStateQueue *sq = mFastCapture->sq();
8113 FastCaptureState *state = sq->begin();
8114 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8115 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8116 if (old == -1) {
8117 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8118 }
8119 }
8120 state->mCommand = FastCaptureState::EXIT;
8121 sq->end();
8122 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8123 mFastCapture->join();
8124 mFastCapture.clear();
8125 }
Andy Hung583043b2023-07-17 17:05:00 -07008126 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8127 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008128 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008129}
8130
Andy Hungee58e4a2023-07-07 13:47:37 -07008131void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008132{
Glenn Kastend7dca052015-03-05 16:05:54 -08008133 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008134}
8135
Andy Hungee58e4a2023-07-07 13:47:37 -07008136void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008137{
8138 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008139 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008140 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008141 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008142 track->invalidate();
8143 }
8144 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008145 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008146}
8147
Andy Hungee58e4a2023-07-07 13:47:37 -07008148bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008149{
Eric Laurent81784c32012-11-19 14:55:58 -08008150 nsecs_t lastWarning = 0;
8151
8152 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008153
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008154reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008155 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008156 {
Andy Hung972bec12023-08-31 16:13:39 -07008157 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008158 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008159 }
8160
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008161 // used to request a deferred sleep, to be executed later while mutex is unlocked
8162 uint32_t sleepUs = 0;
8163
Andy Hung95c94a22023-10-20 16:41:18 -07008164 // timestamp correction enable is determined under lock, used in processing step.
8165 bool timestampCorrectionEnabled = false;
8166
Andy Hung446f4df2019-02-21 12:26:41 -08008167 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8168
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008169 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008170 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008171 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008172
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008173 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008174 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008175
Glenn Kasten735f45f2014-08-18 15:51:59 -07008176 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008177 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008178
Glenn Kasten735f45f2014-08-18 15:51:59 -07008179 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008180 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008181
Eric Laurent33403f02020-05-29 18:35:06 -07008182 bool silenceFastCapture = false;
8183
Andy Hungc5007f82023-08-29 14:26:09 -07008184 { // scope for mutex()
8185 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008186
Eric Laurent021cf962014-05-13 10:18:14 -07008187 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008188
Eric Laurent000a4192014-01-29 15:17:32 -08008189 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008190 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008191 if (exitPending()) {
8192 break;
8193 }
8194
Eric Laurent5c25d562016-07-13 17:17:45 -07008195 // sleep with mutex unlocked
8196 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008197 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008198 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008199 ATRACE_END();
8200 sleepUs = 0;
8201 continue;
8202 }
8203
Glenn Kasten2b806402013-11-20 16:37:38 -08008204 // if no active track(s), then standby and release wakelock
8205 size_t size = mActiveTracks.size();
8206 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008207 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008208 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008209 releaseWakeLock_l();
8210 ALOGV("RecordThread: loop stopping");
8211 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008212 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008213 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008214 goto reacquire_wakelock;
8215 }
8216
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008217 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008218 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008219 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008220
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008221 activeTrack = mActiveTracks[i];
8222 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008223 if (activeTrack->isFastTrack()) {
8224 ALOG_ASSERT(fastTrackToRemove == 0);
8225 fastTrackToRemove = activeTrack;
8226 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008227 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008228 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008229 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008230 continue;
8231 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008232
Andy Hung8d31fd22023-06-26 19:20:57 -07008233 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008234 switch (activeTrackState) {
8235
Andy Hung8d31fd22023-06-26 19:20:57 -07008236 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008237 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008238 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008239 if (activeTrack->isFastTrack()) {
8240 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8241 // Keep a ref on fast track to wait for FastCapture thread to get updated
8242 // state before potential track removal
8243 fastTrackToRemove = activeTrack;
8244 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008245 doBroadcast = true;
8246 size--;
8247 continue;
8248
Andy Hung8d31fd22023-06-26 19:20:57 -07008249 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008250 sleepUs = 10000;
8251 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008252 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008253 continue;
8254
Andy Hung8d31fd22023-06-26 19:20:57 -07008255 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008256 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008257 if (mStandby) {
8258 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008259 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008260 mStandby = false;
8261 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008262 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008263 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008264 break;
8265
Andy Hung8d31fd22023-06-26 19:20:57 -07008266 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008267 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008268 break;
8269
Andy Hung8d31fd22023-06-26 19:20:57 -07008270 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8271 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8272 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008273 default:
Andy Hungce685402018-10-05 17:23:27 -07008274 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8275 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008276 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008277
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008278 if (activeTrack->isFastTrack()) {
8279 ALOG_ASSERT(!mFastTrackAvail);
8280 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008281 // if the active fast track is silenced either:
8282 // 1) silence the whole capture from fast capture buffer if this is
8283 // the only active track
8284 // 2) invalidate this track: this will cause the client to reconnect and possibly
8285 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008286 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008287 if (activeTrack->isSilenced()) {
8288 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008289 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008290 } else {
8291 silenceFastCapture = true;
8292 }
8293 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008294 // Invalidate fast tracks if access to audio history is required as this is not
8295 // possible with fast tracks. Once the fast track has been invalidated, no new
8296 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8297 if (mMaxSharedAudioHistoryMs != 0) {
8298 invalidate = true;
8299 }
8300 if (invalidate) {
8301 activeTrack->invalidate();
8302 ALOG_ASSERT(fastTrackToRemove == 0);
8303 fastTrackToRemove = activeTrack;
8304 removeTrack_l(activeTrack);
8305 mActiveTracks.remove(activeTrack);
8306 size--;
8307 continue;
8308 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008309 fastTrack = activeTrack;
8310 }
Eric Laurent33403f02020-05-29 18:35:06 -07008311
8312 activeTracks.add(activeTrack);
8313 i++;
8314
Glenn Kasten9e982352013-08-14 14:39:50 -07008315 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008316
Andy Hungab65b182023-09-06 19:41:47 -07008317 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008318
Kevin Rocard069c2712018-03-29 19:09:14 -07008319 updateMetadata_l();
8320
Eric Laurent5c25d562016-07-13 17:17:45 -07008321 if (allStopped) {
8322 standbyIfNotAlreadyInStandby();
8323 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008324 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008325 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008326 }
8327
8328 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008329 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008330 if (sleepUs == 0) {
8331 sleepUs = kRecordThreadSleepUs;
8332 }
8333 continue;
8334 }
8335 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008336
Andy Hung95c94a22023-10-20 16:41:18 -07008337 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008338 lockEffectChains_l(effectChains);
8339 }
8340
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008341 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008342
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008343 size_t size = effectChains.size();
8344 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008345 // thread mutex is not locked, but effect chain is locked
8346 effectChains[i]->process_l();
8347 }
8348
Glenn Kasten735f45f2014-08-18 15:51:59 -07008349 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008350 if (mFastCapture != 0) {
8351 FastCaptureStateQueue *sq = mFastCapture->sq();
8352 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008353 bool didModify = false;
8354 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008355 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8356 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8357 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8358 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8359 if (old == -1) {
8360 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8361 }
8362 }
8363 state->mCommand = FastCaptureState::READ_WRITE;
8364#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008365 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008366 FastThreadDumpState::kSamplingNforLowRamDevice :
8367 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008368#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008369 didModify = true;
8370 }
8371 audio_track_cblk_t *cblkOld = state->mCblk;
8372 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8373 if (cblkNew != cblkOld) {
8374 state->mCblk = cblkNew;
8375 // block until acked if removing a fast track
8376 if (cblkOld != NULL) {
8377 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8378 }
8379 didModify = true;
8380 }
jiabin01c8f562018-07-19 17:47:28 -07008381 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8382 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8383 if (state->mFastPatchRecordBufferProvider != abp) {
8384 state->mFastPatchRecordBufferProvider = abp;
8385 state->mFastPatchRecordFormat = fastTrack == 0 ?
8386 AUDIO_FORMAT_INVALID : fastTrack->format();
8387 didModify = true;
8388 }
Eric Laurent33403f02020-05-29 18:35:06 -07008389 if (state->mSilenceCapture != silenceFastCapture) {
8390 state->mSilenceCapture = silenceFastCapture;
8391 didModify = true;
8392 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008393 sq->end(didModify);
8394 if (didModify) {
8395 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008396#if 0
8397 if (kUseFastCapture == FastCapture_Dynamic) {
8398 mNormalSource = mPipeSource;
8399 }
8400#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008401 }
8402 }
8403
Glenn Kasten735f45f2014-08-18 15:51:59 -07008404 // now run the fast track destructor with thread mutex unlocked
8405 fastTrackToRemove.clear();
8406
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008407 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8408 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8409 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8410 // If destination is non-contiguous, first read past the nominal end of buffer, then
8411 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008412
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008413 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008414 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008415 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008416
8417 // If an NBAIO source is present, use it to read the normal capture's data
8418 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008419 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008420
8421 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8422 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8423 // we immediately retry the read() to get data and prevent another overflow.
8424 for (int retries = 0; retries <= 2; ++retries) {
8425 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8426 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8427 framesToRead);
8428 if (framesRead != OVERRUN) break;
8429 }
8430
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008431 const ssize_t availableToRead = mPipeSource->availableToRead();
8432 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008433 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008434 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008435 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8436 "more frames to read than fifo size, %zd > %zu",
8437 availableToRead, mPipeFramesP2);
8438 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8439 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8440 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8441 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008442 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8443 }
8444 if (framesRead < 0) {
8445 status_t status = (status_t) framesRead;
8446 switch (status) {
8447 case OVERRUN:
8448 ALOGW("overrun on read from pipe");
8449 framesRead = 0;
8450 break;
8451 case NEGOTIATE:
8452 ALOGE("re-negotiation is needed");
8453 framesRead = -1; // Will cause an attempt to recover.
8454 break;
8455 default:
8456 ALOGE("unknown error %d on read from pipe", status);
8457 break;
8458 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008459 }
8460 // otherwise use the HAL / AudioStreamIn directly
8461 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008462 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008463 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008464 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008465 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008466 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008467 if (result < 0) {
8468 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008469 } else {
8470 framesRead = bytesRead / mFrameSize;
8471 }
8472 }
8473
Andy Hung446f4df2019-02-21 12:26:41 -08008474 const int64_t lastIoEndNs = systemTime(); // end IO timing
8475
Andy Hung3f0c9022016-01-15 17:49:46 -08008476 // Update server timestamp with server stats
8477 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008478 if (framesRead >= 0) {
8479 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8480 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8481 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008482
8483 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008484 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008485 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008486 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008487 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8488 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8489 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008490 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008491 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8492
8493 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008494 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008495 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008496 id(), (long long)time, (long long)position);
8497 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8498 position = correctedTimestamp.mFrames;
8499 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008500 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008501 id(), (long long)time, (long long)position);
8502 }
8503
Andy Hung3f0c9022016-01-15 17:49:46 -08008504 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8505 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8506 // Note: In general record buffers should tend to be empty in
8507 // a properly running pipeline.
8508 //
8509 // Also, it is not advantageous to call get_presentation_position during the read
8510 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008511 } else {
8512 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008513 }
8514 }
Andy Hunge6c37112019-02-26 17:38:10 -08008515
8516 // From the timestamp, input read latency is negative output write latency.
8517 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008518 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008519 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8520 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8521 mLatencyMs.add(latencyMs);
8522 }
8523
Andy Hung3f0c9022016-01-15 17:49:46 -08008524 // Use this to track timestamp information
8525 // ALOGD("%s", mTimestamp.toString().c_str());
8526
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008527 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008528 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008529 // Force input into standby so that it tries to recover at next read attempt
8530 inputStandBy();
8531 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008532 }
8533 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008534 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008535 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008536 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008537 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008538
Andy Hung8946a282018-04-19 20:04:56 -07008539#ifdef TEE_SINK
8540 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8541#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008542 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008543 {
8544 size_t part1 = mRsmpInFramesP2 - rear;
8545 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008546 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008547 (framesRead - part1) * mFrameSize);
8548 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008549 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008550 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008551
8552 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008553
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008554 // loop over each active track
8555 for (size_t i = 0; i < size; i++) {
8556 activeTrack = activeTracks[i];
8557
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008558 // skip fast tracks, as those are handled directly by FastCapture
8559 if (activeTrack->isFastTrack()) {
8560 continue;
8561 }
8562
Andy Hung73c02e42015-03-29 01:13:58 -07008563 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008564 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8565
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008566 enum {
8567 OVERRUN_UNKNOWN,
8568 OVERRUN_TRUE,
8569 OVERRUN_FALSE
8570 } overrun = OVERRUN_UNKNOWN;
8571
8572 // loop over getNextBuffer to handle circular sink
8573 for (;;) {
8574
Andy Hung8d31fd22023-06-26 19:20:57 -07008575 activeTrack->sinkBuffer().frameCount = ~0;
8576 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8577 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008578 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8579
Andy Hung73c02e42015-03-29 01:13:58 -07008580 // check available frames and handle overrun conditions
8581 // if the record track isn't draining fast enough.
8582 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008583 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008584 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008585 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008586 overrun = OVERRUN_TRUE;
8587 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008588 if (framesOut == 0 || framesIn == 0) {
8589 break;
8590 }
8591
Andy Hung6770c6f2015-04-07 13:43:36 -07008592 // Don't allow framesOut to be larger than what is possible with resampling
8593 // from framesIn.
8594 // This isn't strictly necessary but helps limit buffer resizing in
8595 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008596 if (audio_is_linear_pcm(activeTrack->format())) {
8597 framesOut = min(framesOut,
8598 destinationFramesPossible(
8599 framesIn, mSampleRate, activeTrack->sampleRate()));
8600 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008601
8602 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008603 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008604 // straight from RecordThread buffer to RecordTrack buffer.
8605 AudioBufferProvider::Buffer buffer;
8606 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008607 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008608 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008609 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008610 ALOGV_IF(buffer.frameCount != framesOut,
8611 "%s() read less than expected (%zu vs %zu)",
8612 __func__, buffer.frameCount, framesOut);
8613 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008614 memcpy(activeTrack->sinkBuffer().raw,
8615 buffer.raw, buffer.frameCount * mFrameSize);
8616 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008617 } else {
8618 framesOut = 0;
8619 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008620 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008621 }
8622 } else {
8623 // process frames from the RecordThread buffer provider to the RecordTrack
8624 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008625 framesOut = activeTrack->recordBufferConverter()->convert(
8626 activeTrack->sinkBuffer().raw,
8627 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008628 framesOut);
8629 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008630
8631 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8632 overrun = OVERRUN_FALSE;
8633 }
8634
Andy Hung93bb5732023-05-04 21:16:34 -07008635 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8636 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008637 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008638 if (framesToDrop == 0) {
8639 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008640 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008641 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008642 // Sanitize before releasing if the track has no access to the source data
8643 // An idle UID receives silence from non virtual devices until active
8644 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008645 memset(activeTrack->sinkBuffer().raw,
8646 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008647 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008648 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008649 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008650 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008651 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008652 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008653 }
8654 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008655
8656 switch (overrun) {
8657 case OVERRUN_TRUE:
8658 // client isn't retrieving buffers fast enough
8659 if (!activeTrack->setOverflow()) {
8660 nsecs_t now = systemTime();
8661 // FIXME should lastWarning per track?
8662 if ((now - lastWarning) > kWarningThrottleNs) {
8663 ALOGW("RecordThread: buffer overflow");
8664 lastWarning = now;
8665 }
8666 }
8667 break;
8668 case OVERRUN_FALSE:
8669 activeTrack->clearOverflow();
8670 break;
8671 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008672 break;
8673 }
8674
Andy Hung3f0c9022016-01-15 17:49:46 -08008675 // update frame information and push timestamp out
8676 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008677 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008678 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8679 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008680 }
8681
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008682unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008683 // enable changes in effect chain
8684 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008685 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008686 if (audio_has_proportional_frames(mFormat)
8687 && loopCount == lastLoopCountRead + 1) {
8688 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8689 const double jitterMs =
8690 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8691 {framesRead, readPeriodNs},
8692 {0, 0} /* lastTimestamp */, mSampleRate);
8693 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8694
Andy Hung972bec12023-08-31 16:13:39 -07008695 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008696 mIoJitterMs.add(jitterMs);
8697 mProcessTimeMs.add(processMs);
8698 }
8699 // update timing info.
8700 mLastIoBeginNs = lastIoBeginNs;
8701 mLastIoEndNs = lastIoEndNs;
8702 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008703 }
8704
Glenn Kasten93e471f2013-08-19 08:40:07 -07008705 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008706
8707 {
Andy Hung972bec12023-08-31 16:13:39 -07008708 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008709 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008710 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008711 track->invalidate();
8712 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008713 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008714 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008715 }
8716
8717 releaseWakeLock();
8718
8719 ALOGV("RecordThread %p exiting", this);
8720 return false;
8721}
8722
Andy Hungee58e4a2023-07-07 13:47:37 -07008723void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008724{
8725 if (!mStandby) {
8726 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008727 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008728 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008729 mStandby = true;
8730 }
8731}
8732
Andy Hungee58e4a2023-07-07 13:47:37 -07008733void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008734{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008735 // Idle the fast capture if it's currently running
8736 if (mFastCapture != 0) {
8737 FastCaptureStateQueue *sq = mFastCapture->sq();
8738 FastCaptureState *state = sq->begin();
8739 if (!(state->mCommand & FastCaptureState::IDLE)) {
8740 state->mCommand = FastCaptureState::COLD_IDLE;
8741 state->mColdFutexAddr = &mFastCaptureFutex;
8742 state->mColdGen++;
8743 mFastCaptureFutex = 0;
8744 sq->end();
8745 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8746 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8747#if 0
8748 if (kUseFastCapture == FastCapture_Dynamic) {
8749 // FIXME
8750 }
8751#endif
8752#ifdef AUDIO_WATCHDOG
8753 // FIXME
8754#endif
8755 } else {
8756 sq->end(false /*didModify*/);
8757 }
8758 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008759 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008760 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008761
8762 // If going into standby, flush the pipe source.
8763 if (mPipeSource.get() != nullptr) {
8764 const ssize_t flushed = mPipeSource->flush();
8765 if (flushed > 0) {
8766 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8767 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8768 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8769 }
8770 }
Eric Laurent81784c32012-11-19 14:55:58 -08008771}
8772
Andy Hungc5007f82023-08-29 14:26:09 -07008773// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008774sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008775 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008776 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008777 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008778 audio_format_t format,
8779 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008780 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008781 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008782 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008783 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008784 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008785 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008786 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008787 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008788 audio_port_handle_t portId,
8789 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008790{
Glenn Kasten74935e42013-12-19 08:56:45 -08008791 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008792 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008793 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008794 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008795 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008796 audio_input_flags_t requestedFlags = *flags;
8797 uint32_t sampleRate;
8798
8799 lStatus = initCheck();
8800 if (lStatus != NO_ERROR) {
8801 ALOGE("createRecordTrack_l() audio driver not initialized");
8802 goto Exit;
8803 }
8804
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008805 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8806 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8807 lStatus = BAD_VALUE;
8808 goto Exit;
8809 }
8810
Eric Laurentec376dc2021-04-08 20:41:22 +02008811 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008812 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008813 lStatus = PERMISSION_DENIED;
8814 goto Exit;
8815 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008816 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008817 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008818 lStatus = BAD_VALUE;
8819 goto Exit;
8820 }
8821 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008822 if (*pSampleRate == 0) {
8823 *pSampleRate = mSampleRate;
8824 }
8825 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008826
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008827 // special case for FAST flag considered OK if fast capture is present and access to
8828 // audio history is not required
8829 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008830 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8831 }
8832
Eric Laurentf14db3c2017-12-08 14:20:36 -08008833 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008834 if ((*flags & inputFlags) != *flags) {
8835 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8836 " input flags (%08x)",
8837 *flags, inputFlags);
8838 *flags = (audio_input_flags_t)(*flags & inputFlags);
8839 }
Eric Laurent81784c32012-11-19 14:55:58 -08008840
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008841 // client expresses a preference for FAST and no access to audio history,
8842 // but we get the final say
8843 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008844 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008845 // we formerly checked for a callback handler (non-0 tid),
8846 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008847 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008848 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008849 // Frame count is not specified (0), or is less than or equal the pipe depth.
8850 // It is OK to provide a higher capacity than requested.
8851 // We will force it to mPipeFramesP2 below.
8852 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008853 // PCM data
8854 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008855 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008856 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008857 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008858 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008859 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008860 hasFastCapture() &&
8861 // there are sufficient fast track slots available
8862 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008863 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008864 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008865 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008866 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008867 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008868 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008869 audio_input_flags_t old = *flags;
8870 chain->checkInputFlagCompatibility(flags);
8871 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008872 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8873 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008874 }
8875 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008876 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008877 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8878 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008879 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008880 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8881 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008882 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008883 this, frameCount, mFrameCount, mPipeFramesP2,
8884 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008885 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008886 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008887 }
8888 }
8889
Eric Laurentf14db3c2017-12-08 14:20:36 -08008890 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8891 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8892 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8893 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8894 lStatus = BAD_TYPE;
8895 goto Exit;
8896 }
8897
Glenn Kasten74105912014-07-03 12:28:53 -07008898 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008899 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008900 // fast track: frame count is exactly the pipe depth
8901 frameCount = mPipeFramesP2;
8902 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008903 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008904 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008905 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8906 // or 20 ms if there is a fast capture
8907 // TODO This could be a roundupRatio inline, and const
8908 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8909 * sampleRate + mSampleRate - 1) / mSampleRate;
8910 // minimum number of notification periods is at least kMinNotifications,
8911 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8912 static const size_t kMinNotifications = 3;
8913 static const uint32_t kMinMs = 30;
8914 // TODO This could be a roundupRatio inline
8915 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8916 // TODO This could be a roundupRatio inline
8917 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8918 maxNotificationFrames;
8919 const size_t minFrameCount = maxNotificationFrames *
8920 max(kMinNotifications, minNotificationsByMs);
8921 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008922 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8923 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008924 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008925 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008926 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008927 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008928
Andy Hungc5007f82023-08-29 14:26:09 -07008929 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07008930 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008931 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008932 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008933 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008934 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008935 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008936 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008937 }
Eric Laurent81784c32012-11-19 14:55:58 -08008938
Andy Hung8d31fd22023-06-26 19:20:57 -07008939 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008940 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008941 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008942 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008943 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008944
Glenn Kasten03003332013-08-06 15:40:54 -07008945 lStatus = track->initCheck();
8946 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008947 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008948 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008949 goto Exit;
8950 }
8951 mTracks.add(track);
8952
Eric Laurent05067782016-06-01 18:27:28 -07008953 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008954 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8955 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8956 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008957 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008958 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008959
8960 if (maxSharedAudioHistoryMs != 0) {
8961 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8962 }
Eric Laurent81784c32012-11-19 14:55:58 -08008963 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008964
Eric Laurent81784c32012-11-19 14:55:58 -08008965 lStatus = NO_ERROR;
8966
8967Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008968 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008969 return track;
8970}
8971
Andy Hungee58e4a2023-07-07 13:47:37 -07008972status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008973 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008974 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008975{
8976 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8977 sp<ThreadBase> strongMe = this;
8978 status_t status = NO_ERROR;
8979
8980 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008981 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008982 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008983 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07008984 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008985 event, triggerSession,
8986 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008987 }
8988
8989 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008990 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07008991 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07008992 if (recordTrack->isInvalid()) {
8993 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008994 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8995 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008996 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008997 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008998 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008999 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9000 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009001 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009002 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009003 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009004 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009005 }
9006 return status;
9007 }
9008
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009009 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9010 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9011 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009012 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009013 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009014 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009015 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009016 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009017 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009018 if (recordTrack->isInvalid()) {
9019 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009020 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9021 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009022 // STARTING_2 forces destroy to call stopInput.
9023 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009024 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9025 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009026 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009027 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009028 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009029 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009030 // Someone else has changed state, let them take over,
9031 // leave mState in the new state.
9032 recordTrack->clearSyncStartEvent();
9033 return INVALID_OPERATION;
9034 }
9035 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009036 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009037 ALOGW("%s(%d): startInput failed, status %d",
9038 __func__, recordTrack->id(), status);
9039 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9040 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009041 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009042 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009043 return status;
9044 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009045 sendIoConfigEvent_l(
9046 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009047 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009048
9049 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9050
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009051 // Catch up with current buffer indices if thread is already running.
9052 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9053 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9054 // see previously buffered data before it called start(), but with greater risk of overrun.
9055
Andy Hung8d31fd22023-06-26 19:20:57 -07009056 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009057 if (!recordTrack->isDirect()) {
9058 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009059 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009060 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009061 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009062 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009063 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009064 return status;
9065 }
Eric Laurent81784c32012-11-19 14:55:58 -08009066}
9067
Andy Hungee58e4a2023-07-07 13:47:37 -07009068void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009069{
Andy Hungee58e4a2023-07-07 13:47:37 -07009070 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009071
9072 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009073 sp<IAfTrackBase> ptr =
9074 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9075 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009076 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009077 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009078 }
Eric Laurent81784c32012-11-19 14:55:58 -08009079 }
9080}
9081
Andy Hungee58e4a2023-07-07 13:47:37 -07009082bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009083 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009084 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009085 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009086 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009087 return false;
9088 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009089 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009090 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009091
Andy Hungabfab202019-03-07 19:45:54 -08009092 // NOTE: Waiting here is important to keep stop synchronous.
9093 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009094 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009095 mWaitWorkCV.notify_all(); // signal thread to stop
9096 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009097 }
Andy Hungce685402018-10-05 17:23:27 -07009098
Andy Hung8d31fd22023-06-26 19:20:57 -07009099 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009100 ALOGV("Record stopped OK");
9101 return true;
9102 }
Andy Hungce685402018-10-05 17:23:27 -07009103
9104 // don't handle anything - we've been invalidated or restarted and in a different state
9105 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009106 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009107 return false;
9108}
9109
Andy Hungee58e4a2023-07-07 13:47:37 -07009110bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009111{
9112 return false;
9113}
9114
Andy Hungee58e4a2023-07-07 13:47:37 -07009115status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009116{
9117#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9118 if (!isValidSyncEvent(event)) {
9119 return BAD_VALUE;
9120 }
9121
Glenn Kastend848eb42016-03-08 13:42:11 -08009122 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009123 status_t ret = NAME_NOT_FOUND;
9124
Andy Hung972bec12023-08-31 16:13:39 -07009125 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009126
9127 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009128 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009129 if (eventSession == track->sessionId()) {
9130 (void) track->setSyncEvent(event);
9131 ret = NO_ERROR;
9132 }
9133 }
9134 return ret;
9135#else
9136 return BAD_VALUE;
9137#endif
9138}
9139
Andy Hungee58e4a2023-07-07 13:47:37 -07009140status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009141 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009142{
9143 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009144 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009145 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009146 return NO_INIT;
9147 }
jiabin9ff780e2018-03-19 18:19:52 -07009148 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9149 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009150}
9151
Andy Hungee58e4a2023-07-07 13:47:37 -07009152status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009153 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009154{
Paul McLean12340082019-03-19 09:35:05 -06009155 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009156 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009157 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009158 return NO_INIT;
9159 }
Paul McLean12340082019-03-19 09:35:05 -06009160 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009161}
9162
Andy Hungee58e4a2023-07-07 13:47:37 -07009163status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009164{
Paul McLean12340082019-03-19 09:35:05 -06009165 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009166 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009167 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009168 return NO_INIT;
9169 }
Paul McLean12340082019-03-19 09:35:05 -06009170 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009171}
9172
Andy Hungee58e4a2023-07-07 13:47:37 -07009173status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009174 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9175 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009176 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009177 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9178}
9179
Andy Hungee58e4a2023-07-07 13:47:37 -07009180status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009181 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9182 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009183
Eric Laurentec376dc2021-04-08 20:41:22 +02009184 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9185 return BAD_VALUE;
9186 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009187
9188 if (sharedAudioStartMs < 0
9189 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009190 return BAD_VALUE;
9191 }
9192
Eric Laurent2407ce32021-04-26 14:56:03 +02009193 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9194 // As we cannot detect more than one wraparound, only accept values up current write position
9195 // after one wraparound
9196 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9197 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009198 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009199 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9200 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009201 // Bring the start frame position within the input buffer to match the documented
9202 // "best effort" behavior of the API.
9203 if (sharedOffset < 0) {
9204 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009205 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009206 sharedAudioStartFrames =
9207 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009208 }
9209
Eric Laurentec376dc2021-04-08 20:41:22 +02009210 mSharedAudioPackageName = sharedAudioPackageName;
9211 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009212 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009213 } else {
9214 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009215 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009216 }
9217 return NO_ERROR;
9218}
9219
Andy Hungee58e4a2023-07-07 13:47:37 -07009220void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009221 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9222 mSharedAudioStartFrames = -1;
9223 mSharedAudioPackageName = "";
9224}
9225
Andy Hungee58e4a2023-07-07 13:47:37 -07009226ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009227{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009228 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009229 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009230 }
9231 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009232 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009233 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009234 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009235 }
9236 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009237 MetadataUpdate change;
9238 change.recordMetadataUpdate = metadata.tracks;
9239 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009240}
9241
Andy Hungc5007f82023-08-29 14:26:09 -07009242// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009243void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009244{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009245 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009246 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009247
Eric Laurent81784c32012-11-19 14:55:58 -08009248 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009249 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009250 removeTrack_l(track);
9251 }
9252}
9253
Andy Hungee58e4a2023-07-07 13:47:37 -07009254void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009255{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009256 String8 result;
9257 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009258 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009259
Eric Laurent81784c32012-11-19 14:55:58 -08009260 mTracks.remove(track);
9261 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009262 if (track->isFastTrack()) {
9263 ALOG_ASSERT(!mFastTrackAvail);
9264 mFastTrackAvail = true;
9265 }
Eric Laurent81784c32012-11-19 14:55:58 -08009266}
9267
Andy Hungee58e4a2023-07-07 13:47:37 -07009268void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009269{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009270 AudioStreamIn *input = mInput;
9271 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9272 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009273 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009274 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009275 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009276 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009277 }
Andy Hungbfa64962017-06-12 14:43:19 -07009278
9279 if (input != nullptr) {
9280 dprintf(fd, " Hal stream dump:\n");
9281 (void)input->stream->dump(fd);
9282 }
9283
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009284 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009285 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009286
Glenn Kasten2f90c512015-12-02 11:40:09 -08009287 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9288 // while we are dumping it. It may be inconsistent, but it won't mutate!
9289 // This is a large object so we place it on the heap.
9290 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009291 const std::unique_ptr<FastCaptureDumpState> copy =
9292 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009293 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009294}
9295
Andy Hungee58e4a2023-07-07 13:47:37 -07009296void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009297{
Eric Laurent81784c32012-11-19 14:55:58 -08009298 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009299 size_t numtracks = mTracks.size();
9300 size_t numactive = mActiveTracks.size();
9301 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009302 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009303 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009304 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009305 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009306 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009307 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009308 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009309 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009310 if (track != 0) {
9311 bool active = mActiveTracks.indexOf(track) >= 0;
9312 if (active) {
9313 numactiveseen++;
9314 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009315 result.append(prefix);
9316 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009317 }
Eric Laurent81784c32012-11-19 14:55:58 -08009318 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009319 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009320 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009321 }
9322
Marco Nelissenb2208842014-02-07 14:00:50 -08009323 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009324 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009325 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009326 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009327 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009328 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009329 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009330 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009331 result.append(prefix);
9332 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009333 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009334 }
Eric Laurent81784c32012-11-19 14:55:58 -08009335
9336 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009337 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009338}
9339
Andy Hungee58e4a2023-07-07 13:47:37 -07009340void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009341{
Andy Hung972bec12023-08-31 16:13:39 -07009342 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009343 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009344 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009345 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009346 track->setSilenced(silenced);
9347 }
9348 }
9349}
Andy Hung73c02e42015-03-29 01:13:58 -07009350
Andy Hung8d31fd22023-06-26 19:20:57 -07009351void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009352{
Andy Hung87c693c2023-07-06 20:56:16 -07009353 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009354 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009355 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009356 const int32_t rear = recordThread->mRsmpInRear;
9357 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009358 if (mRecordTrack->startFrames() >= 0) {
9359 int32_t startFrames = mRecordTrack->startFrames();
9360 // Accept a recent wraparound of mRsmpInRear
9361 if (startFrames <= rear) {
9362 deltaFrames = rear - startFrames;
9363 } else {
9364 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009365 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009366 // start frame cannot be further in the past than start of resampling buffer
9367 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9368 deltaFrames = recordThread->mRsmpInFrames;
9369 }
9370 }
9371 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009372}
9373
Andy Hung8d31fd22023-06-26 19:20:57 -07009374void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009375 size_t *framesAvailable, bool *hasOverrun)
9376{
Andy Hung87c693c2023-07-06 20:56:16 -07009377 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009378 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009379 const int32_t rear = recordThread->mRsmpInRear;
9380 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009381 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009382
9383 size_t framesIn;
9384 bool overrun = false;
9385 if (filled < 0) {
9386 // should not happen, but treat like a massive overrun and re-sync
9387 framesIn = 0;
9388 mRsmpInFront = rear;
9389 overrun = true;
9390 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9391 framesIn = (size_t) filled;
9392 } else {
9393 // client is not keeping up with server, but give it latest data
9394 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009395 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9396 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009397 overrun = true;
9398 }
9399 if (framesAvailable != NULL) {
9400 *framesAvailable = framesIn;
9401 }
9402 if (hasOverrun != NULL) {
9403 *hasOverrun = overrun;
9404 }
9405}
9406
Eric Laurent81784c32012-11-19 14:55:58 -08009407// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009408status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009409 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009410{
Andy Hung87c693c2023-07-06 20:56:16 -07009411 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009412 if (threadBase == 0) {
9413 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009414 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009415 return NOT_ENOUGH_DATA;
9416 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009417 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009418 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009419 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009420 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009421 // FIXME should not be P2 (don't want to increase latency)
9422 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009423 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009424 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009425
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009426 front &= recordThread->mRsmpInFramesP2 - 1;
9427 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009428 if (part1 > (size_t) filled) {
9429 part1 = filled;
9430 }
9431 size_t ask = buffer->frameCount;
9432 ALOG_ASSERT(ask > 0);
9433 if (part1 > ask) {
9434 part1 = ask;
9435 }
9436 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009437 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009438 buffer->raw = NULL;
9439 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009440 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009441 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009442 }
9443
Andy Hung57446612015-04-19 23:56:46 -07009444 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009445 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009446 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009447 return NO_ERROR;
9448}
9449
9450// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009451void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009452 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009453{
Hongwei Wang95e37682019-04-12 11:13:36 -07009454 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009455 if (stepCount == 0) {
9456 return;
9457 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009458 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009459 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009460 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009461 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009462 buffer->frameCount = 0;
9463}
9464
Andy Hungee58e4a2023-07-07 13:47:37 -07009465void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009466{
Andy Hung972bec12023-08-31 16:13:39 -07009467 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009468 checkBtNrec_l();
9469}
9470
Andy Hungee58e4a2023-07-07 13:47:37 -07009471void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009472{
9473 // disable AEC and NS if the device is a BT SCO headset supporting those
9474 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009475 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009476 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009477 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9478 for (size_t i = 0; i < mEffectChains.size(); i++) {
9479 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9480 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9481 }
9482 }
9483}
9484
Andy Hung97a893e2015-03-29 01:03:07 -07009485
Andy Hungee58e4a2023-07-07 13:47:37 -07009486bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009487 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009488{
9489 bool reconfig = false;
9490
Eric Laurent10351942014-05-08 18:49:52 -07009491 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009492
Eric Laurent10351942014-05-08 18:49:52 -07009493 audio_format_t reqFormat = mFormat;
9494 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009495 // 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 +08009496 [[maybe_unused]] audio_channel_mask_t channelMask =
9497 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009498
9499 AudioParameter param = AudioParameter(keyValuePair);
9500 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009501
9502 // scope for AutoPark extends to end of method
9503 AutoPark<FastCapture> park(mFastCapture);
9504
Eric Laurent10351942014-05-08 18:49:52 -07009505 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9506 // channel count change can be requested. Do we mandate the first client defines the
9507 // HAL sampling rate and channel count or do we allow changes on the fly?
9508 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9509 samplingRate = value;
9510 reconfig = true;
9511 }
9512 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009513 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009514 status = BAD_VALUE;
9515 } else {
9516 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009517 reconfig = true;
9518 }
Eric Laurent10351942014-05-08 18:49:52 -07009519 }
9520 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9521 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009522 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009523 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009524 status = BAD_VALUE;
9525 } else {
9526 channelMask = mask;
9527 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009528 }
Eric Laurent10351942014-05-08 18:49:52 -07009529 }
9530 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9531 // do not accept frame count changes if tracks are open as the track buffer
9532 // size depends on frame count and correct behavior would not be guaranteed
9533 // if frame count is changed after track creation
9534 if (mActiveTracks.size() > 0) {
9535 status = INVALID_OPERATION;
9536 } else {
9537 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009538 }
Eric Laurent10351942014-05-08 18:49:52 -07009539 }
9540 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009541 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009542 }
9543 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9544 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009545 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009546 }
Glenn Kastene198c362013-08-13 09:13:36 -07009547
Eric Laurent10351942014-05-08 18:49:52 -07009548 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009549 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009550 if (status == INVALID_OPERATION) {
9551 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009552 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009553 }
9554 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009555 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009556 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9557 if (mInput->stream->getAudioProperties(&config) == OK &&
9558 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9559 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009560 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009561 status = NO_ERROR;
9562 }
Eric Laurent81784c32012-11-19 14:55:58 -08009563 }
Eric Laurent10351942014-05-08 18:49:52 -07009564 if (status == NO_ERROR) {
9565 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009566 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009567 }
9568 }
Eric Laurent81784c32012-11-19 14:55:58 -08009569 }
Eric Laurent10351942014-05-08 18:49:52 -07009570
Eric Laurent81784c32012-11-19 14:55:58 -08009571 return reconfig;
9572}
9573
Andy Hungee58e4a2023-07-07 13:47:37 -07009574String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009575{
Andy Hung972bec12023-08-31 16:13:39 -07009576 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009577 if (initCheck() == NO_ERROR) {
9578 String8 out_s8;
9579 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9580 return out_s8;
9581 }
Eric Laurent81784c32012-11-19 14:55:58 -08009582 }
Andy Hung920f6572022-10-06 12:09:49 -07009583 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009584}
9585
Andy Hungab65b182023-09-06 19:41:47 -07009586void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009587 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009588 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009589 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009590 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009591 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009592 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009593 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9594 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009595 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009596 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009597 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009598 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009599 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009600 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009601 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009602 break;
9603 }
Andy Hungab65b182023-09-06 19:41:47 -07009604 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009605}
9606
Andy Hungee58e4a2023-07-07 13:47:37 -07009607void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009608{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009609 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9610 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009611 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009612 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9613 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009614 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9615 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009616 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009617 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009618 ALOGI("HAL format %#x is not linear pcm", mFormat);
9619 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009620 result = mInput->stream->getFrameSize(&mFrameSize);
9621 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009622 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9623 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009624 result = mInput->stream->getBufferSize(&mBufferSize);
9625 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009626 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009627 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9628 "mBufferSize=%zu, mFrameCount=%zu",
9629 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009630
Eric Laurentec376dc2021-04-08 20:41:22 +02009631 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9632 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009633 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009634
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009635 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9636 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009637
9638 audio_input_flags_t flags = mInput->flags;
9639 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9640 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009641 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009642 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9643 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9644 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9645 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9646 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9647 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009648}
9649
Andy Hungee58e4a2023-07-07 13:47:37 -07009650uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009651{
Andy Hung972bec12023-08-31 16:13:39 -07009652 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009653 uint32_t result;
9654 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9655 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009656 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009657 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009658}
9659
Andy Hungee58e4a2023-07-07 13:47:37 -07009660KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009661{
Glenn Kastend848eb42016-03-08 13:42:11 -08009662 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009663 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009664 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009665 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009666 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009667 if (ids.indexOfKey(sessionId) < 0) {
9668 ids.add(sessionId, true);
9669 }
9670 }
9671 return ids;
9672}
9673
Andy Hungee58e4a2023-07-07 13:47:37 -07009674AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009675{
Andy Hung972bec12023-08-31 16:13:39 -07009676 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009677 AudioStreamIn *input = mInput;
9678 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009679 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009680 return input;
9681}
9682
Andy Hungc5007f82023-08-29 14:26:09 -07009683// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009684sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009685{
9686 if (mInput == NULL) {
9687 return NULL;
9688 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009689 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009690}
9691
Andy Hungee58e4a2023-07-07 13:47:37 -07009692status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009693{
Eric Laurent81784c32012-11-19 14:55:58 -08009694 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009695 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009696 chain->setInBuffer(NULL);
9697 chain->setOutBuffer(NULL);
9698
9699 checkSuspendOnAddEffectChain_l(chain);
9700
Eric Laurent1b928682014-10-02 19:41:47 -07009701 // make sure enabled pre processing effects state is communicated to the HAL as we
9702 // just moved them to a new input stream.
9703 chain->syncHalEffectsState();
9704
Eric Laurent81784c32012-11-19 14:55:58 -08009705 mEffectChains.add(chain);
9706
9707 return NO_ERROR;
9708}
9709
Andy Hungee58e4a2023-07-07 13:47:37 -07009710size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009711{
9712 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009713
9714 for (size_t i = 0; i < mEffectChains.size(); i++) {
9715 if (chain == mEffectChains[i]) {
9716 mEffectChains.removeAt(i);
9717 break;
9718 }
Eric Laurent81784c32012-11-19 14:55:58 -08009719 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009720 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009721}
9722
Andy Hungee58e4a2023-07-07 13:47:37 -07009723status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009724 audio_patch_handle_t *handle)
9725{
9726 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009727
9728 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009729 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009730 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009731 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009732 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009733 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009734 }
9735
Eric Laurentd8365c52017-07-16 15:27:05 -07009736 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009737
9738 // store new source and send to effects
9739 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9740 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009741 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009742 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009743 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009744 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009745
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009746 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009747 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9748 status = hwDevice->createAudioPatch(patch->num_sources,
9749 patch->sources,
9750 patch->num_sinks,
9751 patch->sinks,
9752 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009753 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009754 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9755 patch->sinks[0].ext.mix.usecase.source,
9756 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009757 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009758 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009759
jiabinc52b1ff2019-10-31 17:20:42 -07009760 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009761 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009762 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009763 }
Eric Laurent296fb132015-05-01 11:38:42 -07009764
Andy Hungc2b11cb2020-04-22 09:04:01 -07009765 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009766 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009767 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009768 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009769 // also dispatch to active AudioRecords
9770 for (const auto &track : mActiveTracks) {
9771 track->logEndInterval();
9772 track->logBeginInterval(pathSourcesAsString);
9773 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009774 // Force meteadata update after a route change
9775 mActiveTracks.setHasChanged();
9776
Eric Laurent1c333e22014-05-20 10:48:17 -07009777 return status;
9778}
9779
Andy Hungee58e4a2023-07-07 13:47:37 -07009780status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009781{
9782 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009783
jiabinc52b1ff2019-10-31 17:20:42 -07009784 mPatch = audio_patch{};
9785 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009786
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009787 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009788 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9789 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009790 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009791 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009792 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009793 // Force meteadata update after a route change
9794 mActiveTracks.setHasChanged();
9795
Eric Laurent1c333e22014-05-20 10:48:17 -07009796 return status;
9797}
9798
Andy Hungee58e4a2023-07-07 13:47:37 -07009799void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009800{
Andy Hung972bec12023-08-31 16:13:39 -07009801 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009802 mOutDevices = outDevices;
9803 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9804 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009805 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009806 }
9807}
9808
Andy Hungee58e4a2023-07-07 13:47:37 -07009809int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009810{
9811 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009812 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009813 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009814 int32_t oldestFront = mRsmpInRear;
9815 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009816 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009817 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009818 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009819 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009820 if (filled > maxFilled) {
9821 oldestFront = front;
9822 maxFilled = filled;
9823 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009824 }
Andy Hung920f6572022-10-06 12:09:49 -07009825 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009826 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9827 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009828 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009829}
9830
Andy Hungee58e4a2023-07-07 13:47:37 -07009831void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009832{
9833 if (offset == 0) {
9834 return;
9835 }
9836 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009837 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009838 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009839 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009840 }
9841}
9842
Andy Hungee58e4a2023-07-07 13:47:37 -07009843void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009844{
9845 // This is the formula for calculating the temporary buffer size.
9846 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9847 // 1 full output buffer, regardless of the alignment of the available input.
9848 // The value is somewhat arbitrary, and could probably be even larger.
9849 // A larger value should allow more old data to be read after a track calls start(),
9850 // without increasing latency.
9851 //
9852 // Note this is independent of the maximum downsampling ratio permitted for capture.
9853 size_t minRsmpInFrames = mFrameCount * 7;
9854
9855 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9856 // capture history available to another client using the same session ID:
9857 // dimension the resampler input buffer accordingly.
9858
9859 // Get oldest client read position: getOldestFront_l() must be called before altering
9860 // mRsmpInRear, or mRsmpInFrames
9861 int32_t previousFront = getOldestFront_l();
9862 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9863 int32_t previousRear = mRsmpInRear;
9864 mRsmpInRear = 0;
9865
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009866 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009867 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009868 "resizeInputBuffer_l() called with invalid max shared history %d",
9869 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009870 if (maxSharedAudioHistoryMs != 0) {
9871 // resizeInputBuffer_l should never be called with a non zero shared history if the
9872 // buffer was not already allocated
9873 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9874 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9875 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9876 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009877 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009878 return;
9879 }
9880 mRsmpInFrames = rsmpInFrames;
9881 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009882 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009883 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9884 // initialized
9885 if (mRsmpInFrames < minRsmpInFrames) {
9886 mRsmpInFrames = minRsmpInFrames;
9887 }
9888 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9889
9890 // TODO optimize audio capture buffer sizes ...
9891 // Here we calculate the size of the sliding buffer used as a source
9892 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9893 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9894 // be better to have it derived from the pipe depth in the long term.
9895 // The current value is higher than necessary. However it should not add to latency.
9896
9897 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9898 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9899
9900 void *rsmpInBuffer;
9901 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9902 // if posix_memalign fails, will segv here.
9903 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9904
9905 // Copy audio history if any from old buffer before freeing it
9906 if (previousRear != 0) {
9907 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9908 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9909
9910 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9911 previousFront &= previousRsmpInFramesP2 - 1;
9912 size_t part1 = previousRsmpInFramesP2 - previousFront;
9913 if (part1 > (size_t) unread) {
9914 part1 = unread;
9915 }
9916 if (part1 != 0) {
9917 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9918 part1 * mFrameSize);
9919 mRsmpInRear = part1;
9920 part1 = unread - part1;
9921 if (part1 != 0) {
9922 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9923 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9924 mRsmpInRear += part1;
9925 }
9926 }
9927 // Update front for all clients according to new rear
9928 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9929 } else {
9930 mRsmpInRear = 0;
9931 }
9932 free(mRsmpInBuffer);
9933 mRsmpInBuffer = rsmpInBuffer;
9934}
9935
Andy Hungee58e4a2023-07-07 13:47:37 -07009936void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009937{
Andy Hung972bec12023-08-31 16:13:39 -07009938 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009939 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009940 if (record->getSource()) {
9941 mSource = record->getSource();
9942 }
Eric Laurent83b88082014-06-20 18:31:16 -07009943}
9944
Andy Hungee58e4a2023-07-07 13:47:37 -07009945void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009946{
Andy Hung972bec12023-08-31 16:13:39 -07009947 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009948 if (mSource == record->getSource()) {
9949 mSource = mInput;
9950 }
Eric Laurent83b88082014-06-20 18:31:16 -07009951 destroyTrack_l(record);
9952}
9953
Andy Hungee58e4a2023-07-07 13:47:37 -07009954void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009955{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009956 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009957 config->role = AUDIO_PORT_ROLE_SINK;
9958 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9959 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009960 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9961 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9962 config->flags.input = mInput->flags;
9963 }
Eric Laurent83b88082014-06-20 18:31:16 -07009964}
Eric Laurent1c333e22014-05-20 10:48:17 -07009965
Eric Laurent6acd1d42017-01-04 14:23:29 -08009966// ----------------------------------------------------------------------------
9967// Mmap
9968// ----------------------------------------------------------------------------
9969
Andy Hung7aa7d102023-07-07 15:58:48 -07009970// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9971// MmapPlaybackThread or MmapCaptureThread instance.
9972class MmapThreadHandle : public MmapStreamInterface {
9973public:
9974 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9975 ~MmapThreadHandle() override;
9976
9977 // MmapStreamInterface virtuals
9978 status_t createMmapBuffer(int32_t minSizeFrames,
9979 struct audio_mmap_buffer_info* info) final;
9980 status_t getMmapPosition(struct audio_mmap_position* position) final;
9981 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9982 status_t start(const AudioClient& client,
9983 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9984 status_t stop(audio_port_handle_t handle) final;
9985 status_t standby() final;
9986 status_t reportData(const void* buffer, size_t frameCount) final;
9987private:
9988 const sp<IAfMmapThread> mThread;
9989};
9990
9991/* static */
9992sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9993 const sp<IAfMmapThread>& mmapThread) {
9994 return sp<MmapThreadHandle>::make(mmapThread);
9995}
9996
9997MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009998 : mThread(thread)
9999{
Phil Burk9fabbf82017-08-03 12:02:00 -070010000 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010001}
10002
Andy Hung7aa7d102023-07-07 15:58:48 -070010003// MmapStreamInterface could be directly implemented by MmapThread excepting this
10004// special handling on adapter dtor.
10005MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010006{
Phil Burk9fabbf82017-08-03 12:02:00 -070010007 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010008}
10009
Andy Hung7aa7d102023-07-07 15:58:48 -070010010status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010011 struct audio_mmap_buffer_info *info)
10012{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010013 return mThread->createMmapBuffer(minSizeFrames, info);
10014}
10015
Andy Hung7aa7d102023-07-07 15:58:48 -070010016status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010017{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 return mThread->getMmapPosition(position);
10019}
10020
Andy Hung7aa7d102023-07-07 15:58:48 -070010021status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010022 int64_t *timeNanos) {
10023 return mThread->getExternalPosition(position, timeNanos);
10024}
10025
Andy Hung7aa7d102023-07-07 15:58:48 -070010026status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010027 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010028{
jiabind1f1cb62020-03-24 11:57:57 -070010029 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010030}
10031
Andy Hung7aa7d102023-07-07 15:58:48 -070010032status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010033{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010034 return mThread->stop(handle);
10035}
10036
Andy Hung7aa7d102023-07-07 15:58:48 -070010037status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010038{
Eric Laurent18b57012017-02-13 16:23:52 -080010039 return mThread->standby();
10040}
10041
Andy Hung7aa7d102023-07-07 15:58:48 -070010042status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10043{
jiabinfc791ee2023-02-15 19:43:40 +000010044 return mThread->reportData(buffer, frameCount);
10045}
10046
Eric Laurent6acd1d42017-01-04 14:23:29 -080010047
Andy Hungee58e4a2023-07-07 13:47:37 -070010048MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010049 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010050 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010051 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010052 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010053 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010054 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010055 mActiveTracks(&this->mLocalLog),
10056 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10057 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010058{
Eric Laurent18b57012017-02-13 16:23:52 -080010059 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060 readHalParameters_l();
10061}
10062
Andy Hungee58e4a2023-07-07 13:47:37 -070010063void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064{
10065 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10066}
10067
Andy Hungee58e4a2023-07-07 13:47:37 -070010068void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010069{
Andy Hung8d31fd22023-06-26 19:20:57 -070010070 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010071 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010072 {
Andy Hung972bec12023-08-31 16:13:39 -070010073 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010074 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010075 activeTracks.add(t);
10076 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010077 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010078 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010079 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010080 stop(t->portId());
10081 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010082 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010083 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010084 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010085 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010086 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010087 }
10088}
10089
10090
Andy Hung8d672e02023-09-15 18:19:28 -070010091void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010092 audio_stream_type_t streamType __unused,
10093 audio_session_t sessionId,
10094 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010095 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010096 audio_port_handle_t portId)
10097{
10098 mAttr = *attr;
10099 mSessionId = sessionId;
10100 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010101 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010102 mPortId = portId;
10103}
10104
Andy Hungee58e4a2023-07-07 13:47:37 -070010105status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106 struct audio_mmap_buffer_info *info)
10107{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010108 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010109 if (mHalStream == 0) {
10110 return NO_INIT;
10111 }
Eric Laurent18b57012017-02-13 16:23:52 -080010112 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010113 return mHalStream->createMmapBuffer(minSizeFrames, info);
10114}
10115
Andy Hungee58e4a2023-07-07 13:47:37 -070010116status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010117{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010118 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010119 if (mHalStream == 0) {
10120 return NO_INIT;
10121 }
10122 return mHalStream->getMmapPosition(position);
10123}
10124
Andy Hungee58e4a2023-07-07 13:47:37 -070010125status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010126{
Eric Laurentdda206a2022-07-08 17:28:35 +020010127 // The HAL must receive track metadata before starting the stream
10128 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010129 status_t ret = mHalStream->start();
10130 if (ret != NO_ERROR) {
10131 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10132 return ret;
10133 }
Andy Hungcf10d742020-04-28 15:38:24 -070010134 if (mStandby) {
10135 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010136 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010137 mStandby = false;
10138 }
Eric Laurent331679c2018-04-16 17:03:16 -070010139 return NO_ERROR;
10140}
10141
Andy Hungee58e4a2023-07-07 13:47:37 -070010142status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010143 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144 audio_port_handle_t *handle)
10145{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010146 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010147 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010148 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149 if (mHalStream == 0) {
10150 return NO_INIT;
10151 }
10152
10153 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010154
Eric Laurentdda206a2022-07-08 17:28:35 +020010155 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010156 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010157 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010158 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010159 }
10160
10161 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10162
10163 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010164 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010165 client.attributionSource);
10166
Andy Hung3f49ebb2023-09-19 14:48:41 -070010167 const auto localSessionId = mSessionId;
10168 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010169 if (isOutput()) {
10170 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10171 config.sample_rate = mSampleRate;
10172 config.channel_mask = mChannelMask;
10173 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010174 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010175 audio_output_flags_t flags =
10176 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010177 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010178 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010179 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010180 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010181 mutex().unlock();
10182 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10183 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010184 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010185 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010186 &config,
10187 flags,
10188 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010189 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010190 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010191 &isSpatialized,
10192 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010193 mutex().lock();
10194 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010195 ALOGD_IF(!secondaryOutputs.empty(),
10196 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010197 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010198 audio_config_base_t config;
10199 config.sample_rate = mSampleRate;
10200 config.channel_mask = mChannelMask;
10201 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010202 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010203 mutex().unlock();
10204 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010205 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010206 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010207 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010208 &config,
10209 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10210 &deviceId,
10211 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010212 mutex().lock();
10213 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010214 }
10215 // APM should not chose a different input or output stream for the same set of attributes
10216 // and audo configuration
10217 if (ret != NO_ERROR || io != mId) {
10218 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10219 __FUNCTION__, ret, io, mId);
10220 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010221 }
10222
10223 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010224 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010225 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010226 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010227 } else {
jiabin09609032022-06-15 19:26:01 +000010228 {
10229 // Add the track record before starting input so that the silent status for the
10230 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010231 setClientSilencedState_l(portId, false /*silenced*/);
10232 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010233 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010234 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010235 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010236 }
10237
10238 // abort if start is rejected by audio policy manager
10239 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010240 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010241 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010242 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010244 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010246 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010247 }
Andy Hungc5007f82023-08-29 14:26:09 -070010248 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010249 } else {
10250 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010251 }
jiabin09609032022-06-15 19:26:01 +000010252 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010253 return PERMISSION_DENIED;
10254 }
10255
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010256 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010257 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10258 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010259 mChannelMask, mSessionId, isOutput(),
10260 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010261 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010262 if (!isOutput()) {
10263 track->setSilenced_l(isClientSilenced_l(portId));
10264 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265
Eric Laurent4eb58f12018-12-07 16:41:02 -080010266 if (isOutput()) {
10267 // force volume update when a new track is added
10268 mHalVolFloat = -1.0f;
10269 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010270 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010271 if (t->isSilenced_l()
10272 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010273 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010274 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010275 }
10276 }
10277
Eric Laurent6acd1d42017-01-04 14:23:29 -080010278 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010279 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010280 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010281 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010282 chain->incTrackCnt();
10283 chain->incActiveTrackCnt();
10284 }
10285
Andy Hungc2b11cb2020-04-22 09:04:01 -070010286 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010287 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010288
10289 if (mActiveTracks.size() == 1) {
10290 ret = exitStandby_l();
10291 }
10292
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 broadcast_l();
10294
Eric Laurentdda206a2022-07-08 17:28:35 +020010295 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010296
Eric Laurentdda206a2022-07-08 17:28:35 +020010297 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298}
10299
Andy Hungee58e4a2023-07-07 13:47:37 -070010300status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010301{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010302 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010303 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010304
10305 if (mHalStream == 0) {
10306 return NO_INIT;
10307 }
10308
Eric Laurenta54f1282017-07-01 19:39:32 -070010309 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010310 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010311 return NO_ERROR;
10312 }
10313
Andy Hung8d31fd22023-06-26 19:20:57 -070010314 sp<IAfMmapTrack> track;
10315 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 if (handle == t->portId()) {
10317 track = t;
10318 break;
10319 }
10320 }
10321 if (track == 0) {
10322 return BAD_VALUE;
10323 }
10324
10325 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010326 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327
Andy Hungc5007f82023-08-29 14:26:09 -070010328 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010330 AudioSystem::stopOutput(track->portId());
10331 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010333 AudioSystem::stopInput(track->portId());
10334 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335 }
Andy Hungc5007f82023-08-29 14:26:09 -070010336 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010337
Andy Hung116bc262023-06-20 18:56:17 -070010338 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010339 if (chain != 0) {
10340 chain->decActiveTrackCnt();
10341 chain->decTrackCnt();
10342 }
10343
Eric Laurentdda206a2022-07-08 17:28:35 +020010344 if (mActiveTracks.isEmpty()) {
10345 mHalStream->stop();
10346 }
10347
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348 broadcast_l();
10349
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 return NO_ERROR;
10351}
10352
Andy Hungee58e4a2023-07-07 13:47:37 -070010353status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010354NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010355{
10356 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010357 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010358
10359 if (mHalStream == 0) {
10360 return NO_INIT;
10361 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010362 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010363 return INVALID_OPERATION;
10364 }
10365 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010366 if (!mStandby) {
10367 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010368 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010369 mStandby = true;
10370 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010371 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010372 return NO_ERROR;
10373}
10374
Andy Hungee58e4a2023-07-07 13:47:37 -070010375status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010376 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10377 return INVALID_OPERATION;
10378}
10379
Andy Hungee58e4a2023-07-07 13:47:37 -070010380void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381{
10382 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10383 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10384 mFormat = mHALFormat;
10385 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10386 result = mHalStream->getFrameSize(&mFrameSize);
10387 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010388 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10389 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390 result = mHalStream->getBufferSize(&mBufferSize);
10391 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10392 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010393
Andy Hungcf10d742020-04-28 15:38:24 -070010394 // TODO: make a readHalParameters call?
10395 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010396 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010397 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010398 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10399 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10400 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10401 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10402 /*
10403 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10404 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10405 (int32_t)mHapticChannelMask)
10406 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10407 (int32_t)mHapticChannelCount)
10408 */
10409 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010410 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010411 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10412 (int32_t)mFrameCount) // sic - added HAL
10413 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414}
10415
Andy Hungee58e4a2023-07-07 13:47:37 -070010416bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010417{
Andy Hungab65b182023-09-06 19:41:47 -070010418 {
10419 audio_utils::unique_lock _l(mutex());
10420 checkSilentMode_l();
10421 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422
10423 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10424
10425 while (!exitPending())
10426 {
Andy Hung116bc262023-06-20 18:56:17 -070010427 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428
Andy Hung13850be2019-03-14 11:33:09 -070010429 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010430 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010431
Eric Laurent6acd1d42017-01-04 14:23:29 -080010432 if (mSignalPending) {
10433 // A signal was raised while we were unlocked
10434 mSignalPending = false;
10435 } else {
10436 if (mConfigEvents.isEmpty()) {
10437 // we're about to wait, flush the binder command buffer
10438 IPCThreadState::self()->flushCommands();
10439
10440 if (exitPending()) {
10441 break;
10442 }
10443
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010445 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010446 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010447 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448
10449 checkSilentMode_l();
10450
10451 continue;
10452 }
10453 }
10454
10455 processConfigEvents_l();
10456
10457 processVolume_l();
10458
10459 checkInvalidTracks_l();
10460
Andy Hungab65b182023-09-06 19:41:47 -070010461 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462
Kevin Rocard069c2712018-03-29 19:09:14 -070010463 updateMetadata_l();
10464
Eric Laurent6acd1d42017-01-04 14:23:29 -080010465 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010466 } // release Thread lock
10467
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010469 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470 }
Andy Hung13850be2019-03-14 11:33:09 -070010471
10472 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010473 unlockEffectChains(effectChains);
10474 // Effect chains will be actually deleted here if they were removed from
10475 // mEffectChains list during mixing or effects processing
10476 }
10477
10478 threadLoop_exit();
10479
10480 if (!mStandby) {
10481 threadLoop_standby();
10482 mStandby = true;
10483 }
10484
Eric Laurent6acd1d42017-01-04 14:23:29 -080010485 ALOGV("Thread %p type %d exiting", this, mType);
10486 return false;
10487}
10488
Andy Hungc5007f82023-08-29 14:26:09 -070010489// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010490bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 status_t& status)
10492{
10493 AudioParameter param = AudioParameter(keyValuePair);
10494 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010495 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010497 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010498 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010499 if (sendToHal) {
10500 status = mHalStream->setParameters(keyValuePair);
10501 } else {
10502 status = NO_ERROR;
10503 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010504
10505 return false;
10506}
10507
Andy Hungee58e4a2023-07-07 13:47:37 -070010508String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010509{
Andy Hung972bec12023-08-31 16:13:39 -070010510 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010511 String8 out_s8;
10512 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10513 return out_s8;
10514 }
Andy Hung920f6572022-10-06 12:09:49 -070010515 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010516}
10517
Andy Hungab65b182023-09-06 19:41:47 -070010518void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010519 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010520 sp<AudioIoDescriptor> desc;
10521 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010522 switch (event) {
10523 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010524 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010525 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010526 isInput = true;
10527 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010528 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010529 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010530 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010531 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10532 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010533 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010534 case AUDIO_INPUT_CLOSED:
10535 case AUDIO_OUTPUT_CLOSED:
10536 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010537 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010538 break;
10539 }
Andy Hungab65b182023-09-06 19:41:47 -070010540 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010541}
10542
Andy Hungee58e4a2023-07-07 13:47:37 -070010543status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010544 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010545NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010546{
10547 status_t status = NO_ERROR;
10548
10549 // store new device and send to effects
10550 audio_devices_t type = AUDIO_DEVICE_NONE;
10551 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010552 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10553 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10554 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555 if (isOutput()) {
10556 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010557 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10558 && !mAudioHwDev->supportsAudioPatches(),
10559 "Enumerated device type(%#x) must not be used "
10560 "as it does not support audio patches",
10561 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010562 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010563 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10564 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565 }
10566 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010567 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010568 } else {
10569 type = patch->sources[0].ext.device.type;
10570 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010571 numDevices = mPatch.num_sources;
10572 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010573 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010574 }
10575
10576 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010577 if (isOutput()) {
10578 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10579 } else {
10580 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10581 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 }
10583
jiabinc52b1ff2019-10-31 17:20:42 -070010584 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585 // store new source and send to effects
10586 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10587 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10588 for (size_t i = 0; i < mEffectChains.size(); i++) {
10589 mEffectChains[i]->setAudioSource_l(mAudioSource);
10590 }
10591 }
10592 }
10593
10594 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010595 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10596 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010597 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010598 audio_port_config port;
10599 std::optional<audio_source_t> source;
10600 if (isOutput()) {
10601 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010603 port = patch->sources[0];
10604 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010605 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010606 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 *handle = AUDIO_PATCH_HANDLE_NONE;
10608 }
10609
jiabinc52b1ff2019-10-31 17:20:42 -070010610 if (numDevices == 0 || mDeviceId != deviceId) {
10611 if (isOutput()) {
10612 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10613 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010614 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010615 } else {
10616 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10617 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10618 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010619 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010620 if (mDeviceId != deviceId && callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010621 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010622 callback->onRoutingChanged(deviceId);
Andy Hungc5007f82023-08-29 14:26:09 -070010623 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624 }
jiabinc52b1ff2019-10-31 17:20:42 -070010625 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010626 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010628 // Force meteadata update after a route change
10629 mActiveTracks.setHasChanged();
10630
Eric Laurent6acd1d42017-01-04 14:23:29 -080010631 return status;
10632}
10633
Andy Hungee58e4a2023-07-07 13:47:37 -070010634status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010635{
10636 status_t status = NO_ERROR;
10637
jiabinc52b1ff2019-10-31 17:20:42 -070010638 mPatch = audio_patch{};
10639 mOutDeviceTypeAddrs.clear();
10640 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010641
10642 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10643 supportsAudioPatches : false;
10644
10645 if (supportsAudioPatches) {
10646 status = mHalDevice->releaseAudioPatch(handle);
10647 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010648 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010650 // Force meteadata update after a route change
10651 mActiveTracks.setHasChanged();
10652
Eric Laurent6acd1d42017-01-04 14:23:29 -080010653 return status;
10654}
10655
Andy Hungee58e4a2023-07-07 13:47:37 -070010656void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010657NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010658{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010659 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660 if (isOutput()) {
10661 config->role = AUDIO_PORT_ROLE_SOURCE;
10662 config->ext.mix.hw_module = mAudioHwDev->handle();
10663 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10664 } else {
10665 config->role = AUDIO_PORT_ROLE_SINK;
10666 config->ext.mix.hw_module = mAudioHwDev->handle();
10667 config->ext.mix.usecase.source = mAudioSource;
10668 }
10669}
10670
Andy Hungee58e4a2023-07-07 13:47:37 -070010671status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010672{
10673 audio_session_t session = chain->sessionId();
10674
10675 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10676 // Attach all tracks with same session ID to this chain.
10677 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010678 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010679 if (session == track->sessionId()) {
10680 chain->incTrackCnt();
10681 chain->incActiveTrackCnt();
10682 }
10683 }
10684
10685 chain->setThread(this);
10686 chain->setInBuffer(nullptr);
10687 chain->setOutBuffer(nullptr);
10688 chain->syncHalEffectsState();
10689
10690 mEffectChains.add(chain);
10691 checkSuspendOnAddEffectChain_l(chain);
10692 return NO_ERROR;
10693}
10694
Andy Hungee58e4a2023-07-07 13:47:37 -070010695size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696{
10697 audio_session_t session = chain->sessionId();
10698
10699 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10700
10701 for (size_t i = 0; i < mEffectChains.size(); i++) {
10702 if (chain == mEffectChains[i]) {
10703 mEffectChains.removeAt(i);
10704 // detach all active tracks from the chain
10705 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010706 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 if (session == track->sessionId()) {
10708 chain->decActiveTrackCnt();
10709 chain->decTrackCnt();
10710 }
10711 }
10712 break;
10713 }
10714 }
10715 return mEffectChains.size();
10716}
10717
Andy Hungee58e4a2023-07-07 13:47:37 -070010718void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719{
10720 mHalStream->standby();
10721}
10722
Andy Hungee58e4a2023-07-07 13:47:37 -070010723void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010724{
Phil Burk7dce7282017-09-27 13:51:41 -070010725 // Do not call callback->onTearDown() because it is redundant for thread exit
10726 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727}
10728
Andy Hungee58e4a2023-07-07 13:47:37 -070010729status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010730{
10731 return BAD_VALUE;
10732}
10733
Andy Hungee58e4a2023-07-07 13:47:37 -070010734bool MmapThread::isValidSyncEvent(
10735 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736{
10737 return false;
10738}
10739
Andy Hungee58e4a2023-07-07 13:47:37 -070010740status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010741 const effect_descriptor_t *desc, audio_session_t sessionId)
10742{
10743 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010744 if (audio_is_global_session(sessionId)) {
10745 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010746 desc->name, mThreadName);
10747 return BAD_VALUE;
10748 }
10749
10750 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10751 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10752 desc->name);
10753 return BAD_VALUE;
10754 }
10755 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010756 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10757 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010758 return BAD_VALUE;
10759 }
10760
10761 // Only allow effects without processing load or latency
10762 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10763 return BAD_VALUE;
10764 }
10765
Andy Hung116bc262023-06-20 18:56:17 -070010766 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010767 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10768 return BAD_VALUE;
10769 }
10770
Eric Laurent6acd1d42017-01-04 14:23:29 -080010771 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010772}
10773
Andy Hungee58e4a2023-07-07 13:47:37 -070010774void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010775{
Eric Laurent039c24a2022-10-07 14:01:59 +020010776 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010777 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010778 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010779 callback = mCallback.promote();
10780 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10781 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10782 mNoCallbackWarningCount++;
10783 }
10784 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010785 }
10786 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010787 if (callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010788 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010789 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungc5007f82023-08-29 14:26:09 -070010790 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010791 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010792}
10793
Andy Hungee58e4a2023-07-07 13:47:37 -070010794void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010795{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010796 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10797 mAttr.content_type, mAttr.usage, mAttr.source);
10798 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010799 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010800 dprintf(fd, " No active clients\n");
10801 }
10802}
10803
Andy Hungee58e4a2023-07-07 13:47:37 -070010804void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010805{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010806 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010807 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010808 dprintf(fd, " %zu Tracks\n", numtracks);
10809 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010810 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010811 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010812 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010813 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010814 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010815 result.append(prefix);
10816 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010817 }
10818 } else {
10819 dprintf(fd, "\n");
10820 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010821 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010822}
10823
Andy Hungee58e4a2023-07-07 13:47:37 -070010824/* static */
10825sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010826 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010827 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010828 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010829}
10830
10831MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010832 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010833 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010834 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010835 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010836 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837{
10838 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10839 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010840 mMasterVolume = afThreadCallback->masterVolume_l();
10841 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010842
10843 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10844 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10845 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010846 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010847 }
10848 // Audio patch and call assistant volume are always max
10849 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10850 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10851 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10852 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10853
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854 if (mAudioHwDev) {
10855 if (mAudioHwDev->canSetMasterVolume()) {
10856 mMasterVolume = 1.0;
10857 }
10858
10859 if (mAudioHwDev->canSetMasterMute()) {
10860 mMasterMute = false;
10861 }
10862 }
10863}
10864
Andy Hungee58e4a2023-07-07 13:47:37 -070010865void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010866 audio_stream_type_t streamType,
10867 audio_session_t sessionId,
10868 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010869 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010870 audio_port_handle_t portId)
10871{
Andy Hung8d672e02023-09-15 18:19:28 -070010872 audio_utils::lock_guard l(mutex());
10873 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010874 mStreamType = streamType;
10875}
10876
Andy Hungee58e4a2023-07-07 13:47:37 -070010877AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010878{
Andy Hung972bec12023-08-31 16:13:39 -070010879 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010880 AudioStreamOut *output = mOutput;
10881 mOutput = NULL;
10882 return output;
10883}
10884
Andy Hungee58e4a2023-07-07 13:47:37 -070010885void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886{
Andy Hung972bec12023-08-31 16:13:39 -070010887 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010888 // Don't apply master volume in SW if our HAL can do it for us.
10889 if (mAudioHwDev &&
10890 mAudioHwDev->canSetMasterVolume()) {
10891 mMasterVolume = 1.0;
10892 } else {
10893 mMasterVolume = value;
10894 }
10895}
10896
Andy Hungee58e4a2023-07-07 13:47:37 -070010897void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010898{
Andy Hung972bec12023-08-31 16:13:39 -070010899 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010900 // Don't apply master mute in SW if our HAL can do it for us.
10901 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10902 mMasterMute = false;
10903 } else {
10904 mMasterMute = muted;
10905 }
10906}
10907
Andy Hungee58e4a2023-07-07 13:47:37 -070010908void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010909{
Andy Hung972bec12023-08-31 16:13:39 -070010910 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010911 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010913 broadcast_l();
10914 }
10915}
10916
Andy Hungee58e4a2023-07-07 13:47:37 -070010917float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010918{
Andy Hung972bec12023-08-31 16:13:39 -070010919 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010920 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010921}
10922
Andy Hungee58e4a2023-07-07 13:47:37 -070010923void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010924{
Andy Hung972bec12023-08-31 16:13:39 -070010925 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010926 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010927 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010928 broadcast_l();
10929 }
10930}
10931
Andy Hungee58e4a2023-07-07 13:47:37 -070010932void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010933{
Andy Hung972bec12023-08-31 16:13:39 -070010934 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010936 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937 track->invalidate();
10938 }
10939 broadcast_l();
10940 }
10941}
10942
Andy Hungee58e4a2023-07-07 13:47:37 -070010943void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010944{
Andy Hung972bec12023-08-31 16:13:39 -070010945 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010946 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010947 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010948 if (portIds.find(track->portId()) != portIds.end()) {
10949 track->invalidate();
10950 trackMatch = true;
10951 portIds.erase(track->portId());
10952 }
10953 if (portIds.empty()) {
10954 break;
10955 }
10956 }
10957 if (trackMatch) {
10958 broadcast_l();
10959 }
10960}
10961
Andy Hungee58e4a2023-07-07 13:47:37 -070010962void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010963NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010964{
10965 float volume;
10966
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010967 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010968 volume = 0;
10969 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010970 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010971 }
10972
10973 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010974 // Convert volumes from float to 8.24
10975 uint32_t vol = (uint32_t)(volume * (1 << 24));
10976
10977 // Delegate volume control to effect in track effect chain if needed
10978 // only one effect chain can be present on DirectOutputThread, so if
10979 // there is one, the track is connected to it
10980 if (!mEffectChains.isEmpty()) {
10981 mEffectChains[0]->setVolume_l(&vol, &vol);
10982 volume = (float)vol / (1 << 24);
10983 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010984 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010985 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10986 mHalVolFloat = volume; // HW volume control worked, so update value.
10987 mNoCallbackWarningCount = 0;
10988 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010989 sp<MmapStreamCallback> callback = mCallback.promote();
10990 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010991 mHalVolFloat = volume; // SW volume control worked, so update value.
10992 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070010993 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010994 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070010995 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010996 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010997 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10998 ALOGW("Could not set MMAP stream volume: no volume callback!");
10999 mNoCallbackWarningCount++;
11000 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011001 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011002 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011003 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011004 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070011005 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011006 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011007 streamVolume_l() == 0.f,
11008 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011009 // TODO(b/241533526): adjust logic to include mute from AppOps
11010 false /*muteFromPlaybackRestricted*/,
11011 false /*muteFromClientVolume*/,
11012 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011013 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011014 }
11015}
11016
Andy Hungee58e4a2023-07-07 13:47:37 -070011017ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011018{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011019 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011020 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011021 }
11022 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011023 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011024 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011025 playback_track_metadata_v7_t trackMetadata;
11026 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011027 .usage = track->attributes().usage,
11028 .content_type = track->attributes().content_type,
11029 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011030 };
11031 trackMetadata.channel_mask = track->channelMask(),
11032 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11033 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011034 }
11035 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011036
11037 MetadataUpdate change;
11038 change.playbackMetadataUpdate = metadata.tracks;
11039 return change;
11040};
Kevin Rocard069c2712018-03-29 19:09:14 -070011041
Andy Hungee58e4a2023-07-07 13:47:37 -070011042void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043{
11044 if (!mMasterMute) {
11045 char value[PROPERTY_VALUE_MAX];
11046 if (property_get("ro.audio.silent", value, "0") > 0) {
11047 char *endptr;
11048 unsigned long ul = strtoul(value, &endptr, 0);
11049 if (*endptr == '\0' && ul != 0) {
11050 ALOGD("Silence is golden");
11051 // The setprop command will not allow a property to be changed after
11052 // the first time it is set, so we don't have to worry about un-muting.
11053 setMasterMute_l(true);
11054 }
11055 }
11056 }
11057}
11058
Andy Hungee58e4a2023-07-07 13:47:37 -070011059void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011060{
11061 MmapThread::toAudioPortConfig(config);
11062 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11063 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11064 config->flags.output = mOutput->flags;
11065 }
11066}
11067
Andy Hungee58e4a2023-07-07 13:47:37 -070011068status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011069 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011070{
11071 if (mOutput == nullptr) {
11072 return NO_INIT;
11073 }
11074 struct timespec timestamp;
11075 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11076 if (status == NO_ERROR) {
11077 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11078 }
11079 return status;
11080}
11081
Andy Hungee58e4a2023-07-07 13:47:37 -070011082status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011083 // Send to MelProcessor for sound dose measurement.
11084 auto processor = mMelProcessor.load();
11085 if (processor) {
11086 processor->process(buffer, frameCount * mFrameSize);
11087 }
11088
jiabinfc791ee2023-02-15 19:43:40 +000011089 return NO_ERROR;
11090}
11091
Andy Hungc5007f82023-08-29 14:26:09 -070011092// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011093void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011094 const sp<audio_utils::MelProcessor>& processor)
11095{
11096 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011097 mMelProcessor.store(processor);
11098 if (processor) {
11099 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011100 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011101
11102 // no need to update output format for MMapPlaybackThread since it is
11103 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011104}
11105
Andy Hungc5007f82023-08-29 14:26:09 -070011106// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011107void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011108{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011109 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11110 auto melProcessor = mMelProcessor.load();
11111 if (melProcessor != nullptr) {
11112 melProcessor->pause();
11113 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011114}
11115
Andy Hungee58e4a2023-07-07 13:47:37 -070011116void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011117{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011118 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011119
Glenn Kastend3bb6452016-12-05 18:14:37 -080011120 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011121 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011122 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11123}
11124
Andy Hungee58e4a2023-07-07 13:47:37 -070011125/* static */
11126sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011127 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011128 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011129 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011130}
11131
11132MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011133 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011134 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011135 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011136 mInput(input)
11137{
11138 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11139 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11140}
11141
Andy Hungee58e4a2023-07-07 13:47:37 -070011142status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011143{
Phil Burkf054fc32018-12-06 09:45:59 -080011144 {
11145 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011146 if (mInput != nullptr && mInput->stream != nullptr) {
11147 mInput->stream->setGain(1.0f);
11148 }
11149 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011150 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011151}
11152
Andy Hungee58e4a2023-07-07 13:47:37 -070011153AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011154{
Andy Hung972bec12023-08-31 16:13:39 -070011155 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011156 AudioStreamIn *input = mInput;
11157 mInput = NULL;
11158 return input;
11159}
Kevin Rocard069c2712018-03-29 19:09:14 -070011160
Andy Hungee58e4a2023-07-07 13:47:37 -070011161void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011162{
11163 bool changed = false;
11164 bool silenced = false;
11165
11166 sp<MmapStreamCallback> callback = mCallback.promote();
11167 if (callback == 0) {
11168 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11169 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11170 mNoCallbackWarningCount++;
11171 }
11172 }
11173
11174 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11175 // track is silenced and unmute otherwise
11176 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11177 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11178 changed = true;
11179 silenced = mActiveTracks[i]->isSilenced_l();
11180 }
11181 }
11182
11183 if (changed) {
11184 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11185 }
11186}
11187
Andy Hungee58e4a2023-07-07 13:47:37 -070011188ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011189{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011190 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011191 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011192 }
11193 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011194 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011195 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011196 record_track_metadata_v7_t trackMetadata;
11197 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011198 .source = track->attributes().source,
11199 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011200 };
11201 trackMetadata.channel_mask = track->channelMask(),
11202 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11203 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011204 }
11205 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011206 MetadataUpdate change;
11207 change.recordMetadataUpdate = metadata.tracks;
11208 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011209}
11210
Andy Hungee58e4a2023-07-07 13:47:37 -070011211void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011212{
Andy Hung972bec12023-08-31 16:13:39 -070011213 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011214 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011215 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011216 mActiveTracks[i]->setSilenced_l(silenced);
11217 broadcast_l();
11218 }
11219 }
jiabin09609032022-06-15 19:26:01 +000011220 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011221}
11222
Andy Hungee58e4a2023-07-07 13:47:37 -070011223void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011224{
11225 MmapThread::toAudioPortConfig(config);
11226 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11227 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11228 config->flags.input = mInput->flags;
11229 }
11230}
11231
Andy Hungee58e4a2023-07-07 13:47:37 -070011232status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011233 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011234{
11235 if (mInput == nullptr) {
11236 return NO_INIT;
11237 }
11238 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11239}
11240
jiabinc658e452022-10-21 20:52:21 +000011241// ----------------------------------------------------------------------------
11242
Andy Hungee58e4a2023-07-07 13:47:37 -070011243/* static */
11244sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011245 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011246 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011247 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011248}
11249
Andy Hung583043b2023-07-17 17:05:00 -070011250BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011251 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011252 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011253
Andy Hungee58e4a2023-07-07 13:47:37 -070011254PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011255 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011256 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11257 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011258 float volumeLeft = 1.0f;
11259 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011260 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11261 const int trackId = mActiveTracks[0]->id();
11262 mAudioMixer->setParameter(
11263 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11264 mAudioMixer->setParameter(
11265 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11266 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011267 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011268 mIsBitPerfect = true;
11269 } else {
11270 mIsBitPerfect = false;
11271 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11272 // active.
11273 for (const auto& track : mActiveTracks) {
11274 const int trackId = track->id();
11275 mAudioMixer->setParameter(
11276 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11277 }
11278 }
jiabin76d94692022-12-15 21:51:21 +000011279 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11280 mVolumeLeft = volumeLeft;
11281 mVolumeRight = volumeRight;
11282 setVolumeForOutput_l(volumeLeft, volumeRight);
11283 }
jiabinc658e452022-10-21 20:52:21 +000011284 return result;
11285}
11286
Andy Hungee58e4a2023-07-07 13:47:37 -070011287void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011288 MixerThread::threadLoop_mix();
11289 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11290}
11291
Glenn Kasten63238ef2015-03-02 15:50:29 -080011292} // namespace android