blob: de6f6944b49e7766638150bbf224cad07724e4fd [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");
2341 dprintf(fd, " Suspend count: %d\n", mSuspended);
2342 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2343 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2344 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2345 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002346 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002347 AudioStreamOut *output = mOutput;
2348 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002349 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002350 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002351 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2352 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2353 if (mPipeSink.get() != nullptr) {
2354 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2355 }
2356 if (output != nullptr) {
2357 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002358 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002359 }
Eric Laurent81784c32012-11-19 14:55:58 -08002360}
2361
Andy Hungc5007f82023-08-29 14:26:09 -07002362// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002363sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002364 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002365 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002366 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002367 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002368 audio_format_t format,
2369 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002370 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002371 size_t *pNotificationFrameCount,
2372 uint32_t notificationsPerBuffer,
2373 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002374 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002375 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002376 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002377 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002378 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002379 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002380 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002381 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002382 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002383 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002384 bool isBitPerfect,
2385 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002386{
Glenn Kasten74935e42013-12-19 08:56:45 -08002387 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002388 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002389 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002390 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002391 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002392 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002393 uint32_t sampleRate;
2394
2395 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2396 lStatus = BAD_VALUE;
2397 goto Exit;
2398 }
Eric Laurent21da6472017-11-09 16:29:26 -08002399
2400 if (*pSampleRate == 0) {
2401 *pSampleRate = mSampleRate;
2402 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002403 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002404
2405 // special case for FAST flag considered OK if fast mixer is present
2406 if (hasFastMixer()) {
2407 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2408 }
2409
2410 // Check if requested flags are compatible with output stream flags
2411 if ((*flags & outputFlags) != *flags) {
2412 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2413 *flags, outputFlags);
2414 *flags = (audio_output_flags_t)(*flags & outputFlags);
2415 }
Eric Laurent81784c32012-11-19 14:55:58 -08002416
jiabinc658e452022-10-21 20:52:21 +00002417 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002418 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002419 if (chain.get() != nullptr) {
2420 // Bit-perfect is required according to the configuration and preferred mixer
2421 // attributes, but it is not in the output flag from the client's request. Explicitly
2422 // adding bit-perfect flag to check the compatibility
2423 audio_output_flags_t flagsToCheck =
2424 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2425 chain->checkOutputFlagCompatibility(&flagsToCheck);
2426 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2427 ALOGE("%s cannot create track as there is data-processing effect attached to "
2428 "given session id(%d)", __func__, sessionId);
2429 lStatus = BAD_VALUE;
2430 goto Exit;
2431 }
2432 *flags = flagsToCheck;
2433 }
2434 }
2435
Eric Laurent81784c32012-11-19 14:55:58 -08002436 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002437 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002438 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002439 // PCM data
2440 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002441 // TODO: extract as a data library function that checks that a computationally
2442 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002443 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002444 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2445 (channelMask == AUDIO_CHANNEL_OUT_MONO
2446 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002447 // hardware sample rate
2448 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002449 // normal mixer has an associated fast mixer
2450 hasFastMixer() &&
2451 // there are sufficient fast track slots available
2452 (mFastTrackAvailMask != 0)
2453 // FIXME test that MixerThread for this fast track has a capable output HAL
2454 // FIXME add a permission test also?
2455 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002456 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2457 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002458 // read the fast track multiplier property the first time it is needed
2459 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2460 if (ok != 0) {
2461 ALOGE("%s pthread_once failed: %d", __func__, ok);
2462 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002463 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002464 }
Eric Laurent4c415062016-06-17 16:14:16 -07002465
2466 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002467 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002468 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002469 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002470 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002471 AUDIO_SESSION_OUTPUT_STAGE,
2472 AUDIO_SESSION_OUTPUT_MIX,
2473 sessionId,
2474 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002475 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002476 if (chain.get() != nullptr) {
2477 audio_output_flags_t old = *flags;
2478 chain->checkOutputFlagCompatibility(flags);
2479 if (old != *flags) {
2480 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2481 (int)session, (int)old, (int)*flags);
2482 }
Eric Laurent4c415062016-06-17 16:14:16 -07002483 }
2484 }
2485 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002486 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002487 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2488 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002489 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002490 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002491 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002492 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002493 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002494 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002495 audio_is_linear_pcm(format), channelMask, sampleRate,
2496 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002497 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002498 }
2499 }
Eric Laurent21da6472017-11-09 16:29:26 -08002500
2501 if (!audio_has_proportional_frames(format)) {
2502 if (sharedBuffer != 0) {
2503 // Same comment as below about ignoring frameCount parameter for set()
2504 frameCount = sharedBuffer->size();
2505 } else if (frameCount == 0) {
2506 frameCount = mNormalFrameCount;
2507 }
2508 if (notificationFrameCount != frameCount) {
2509 notificationFrameCount = frameCount;
2510 }
2511 } else if (sharedBuffer != 0) {
2512 // FIXME: Ensure client side memory buffers need
2513 // not have additional alignment beyond sample
2514 // (e.g. 16 bit stereo accessed as 32 bit frame).
2515 size_t alignment = audio_bytes_per_sample(format);
2516 if (alignment & 1) {
2517 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2518 alignment = 1;
2519 }
2520 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2521 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2522 if (channelCount > 1) {
2523 // More than 2 channels does not require stronger alignment than stereo
2524 alignment <<= 1;
2525 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002526 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002527 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002528 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002529 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002530 goto Exit;
2531 }
Eric Laurent21da6472017-11-09 16:29:26 -08002532
2533 // When initializing a shared buffer AudioTrack via constructors,
2534 // there's no frameCount parameter.
2535 // But when initializing a shared buffer AudioTrack via set(),
2536 // there _is_ a frameCount parameter. We silently ignore it.
2537 frameCount = sharedBuffer->size() / frameSize;
2538 } else {
2539 size_t minFrameCount = 0;
2540 // For fast tracks we try to respect the application's request for notifications per buffer.
2541 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2542 if (notificationsPerBuffer > 0) {
2543 // Avoid possible arithmetic overflow during multiplication.
2544 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2545 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2546 notificationsPerBuffer, mFrameCount);
2547 } else {
2548 minFrameCount = mFrameCount * notificationsPerBuffer;
2549 }
2550 }
2551 } else {
2552 // For normal PCM streaming tracks, update minimum frame count.
2553 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2554 // cover audio hardware latency.
2555 // This is probably too conservative, but legacy application code may depend on it.
2556 // If you change this calculation, also review the start threshold which is related.
2557 uint32_t latencyMs = latency_l();
2558 if (latencyMs == 0) {
2559 ALOGE("Error when retrieving output stream latency");
2560 lStatus = UNKNOWN_ERROR;
2561 goto Exit;
2562 }
2563
2564 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2565 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2566
Eric Laurent81784c32012-11-19 14:55:58 -08002567 }
Eric Laurent21da6472017-11-09 16:29:26 -08002568 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002569 frameCount = minFrameCount;
2570 }
Eric Laurent81784c32012-11-19 14:55:58 -08002571 }
Eric Laurent21da6472017-11-09 16:29:26 -08002572
2573 // Make sure that application is notified with sufficient margin before underrun.
2574 // The client can divide the AudioTrack buffer into sub-buffers,
2575 // and expresses its desire to server as the notification frame count.
2576 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2577 size_t maxNotificationFrames;
2578 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2579 // notify every HAL buffer, regardless of the size of the track buffer
2580 maxNotificationFrames = mFrameCount;
2581 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002582 // Triple buffer the notification period for a triple buffered mixer period;
2583 // otherwise, double buffering for the notification period is fine.
2584 //
2585 // TODO: This should be moved to AudioTrack to modify the notification period
2586 // on AudioTrack::setBufferSizeInFrames() changes.
2587 const int nBuffering =
2588 (uint64_t{frameCount} * mSampleRate)
2589 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2590
Eric Laurent21da6472017-11-09 16:29:26 -08002591 maxNotificationFrames = frameCount / nBuffering;
2592 // If client requested a fast track but this was denied, then use the smaller maximum.
2593 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2594 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2595 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2596 maxNotificationFrames = maxNotificationFramesFastDenied;
2597 }
2598 }
2599 }
2600 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2601 if (notificationFrameCount == 0) {
2602 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2603 maxNotificationFrames, frameCount);
2604 } else {
2605 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2606 notificationFrameCount, maxNotificationFrames, frameCount);
2607 }
2608 notificationFrameCount = maxNotificationFrames;
2609 }
2610 }
2611
Glenn Kasten74935e42013-12-19 08:56:45 -08002612 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002613 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002614
Glenn Kastenc3df8382014-03-13 15:05:25 -07002615 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002616 case BIT_PERFECT:
2617 if (isBitPerfect) {
2618 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2619 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2620 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2621 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2622 mChannelMask);
2623 lStatus = BAD_VALUE;
2624 goto Exit;
2625 }
2626 }
2627 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002628
2629 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002630 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002631 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002632 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2633 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002634 sampleRate, format, channelMask, mOutput, mFormat);
2635 lStatus = BAD_VALUE;
2636 goto Exit;
2637 }
2638 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002639 break;
2640
2641 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002643 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2644 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 sampleRate, format, channelMask, mOutput, mFormat);
2646 lStatus = BAD_VALUE;
2647 goto Exit;
2648 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002649 break;
2650
2651 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002652 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002653 ALOGE("createTrack_l() Bad parameter: format %#x \""
2654 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 format, mOutput, mFormat);
2656 lStatus = BAD_VALUE;
2657 goto Exit;
2658 }
Andy Hungcd044842014-08-07 11:04:34 -07002659 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002660 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2661 lStatus = BAD_VALUE;
2662 goto Exit;
2663 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002664 break;
2665
Eric Laurent81784c32012-11-19 14:55:58 -08002666 }
2667
2668 lStatus = initCheck();
2669 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002670 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002671 goto Exit;
2672 }
2673
Andy Hungc5007f82023-08-29 14:26:09 -07002674 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002675 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002676
2677 // all tracks in same audio session must share the same routing strategy otherwise
2678 // conflicts will happen when tracks are moved from one output to another by audio policy
2679 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002680 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002681 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002682 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002683 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002684 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002685 if (sessionId == t->sessionId() && strategy != actual) {
2686 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2687 strategy, actual);
2688 lStatus = BAD_VALUE;
2689 goto Exit;
2690 }
2691 }
2692 }
2693
yucliuc9c49cd2020-07-13 16:25:21 -07002694 // Set DIRECT flag if current thread is DirectOutputThread. This can
2695 // happen when the playback is rerouted to direct output thread by
2696 // dynamic audio policy.
2697 // Do NOT report the flag changes back to client, since the client
2698 // doesn't explicitly request a direct flag.
2699 audio_output_flags_t trackFlags = *flags;
2700 if (mType == DIRECT) {
2701 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2702 }
jiabin94ed47c2023-07-27 23:34:20 +00002703 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002704
Andy Hung8d31fd22023-06-26 19:20:57 -07002705 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002706 channelMask, frameCount,
2707 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002708 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002709 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002710 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002711
Glenn Kasten03003332013-08-06 15:40:54 -07002712 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2713 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002714 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002715 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002716 goto Exit;
2717 }
2718 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002719 {
Andy Hung972bec12023-08-31 16:13:39 -07002720 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002721 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002722 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002723 }
2724 }
Eric Laurent81784c32012-11-19 14:55:58 -08002725
Andy Hung116bc262023-06-20 18:56:17 -07002726 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002727 if (chain != 0) {
2728 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2729 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002730 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002731 chain->incTrackCnt();
2732 }
2733
Eric Laurent05067782016-06-01 18:27:28 -07002734 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002735 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2736 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2737 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002738 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002739 }
2740 }
2741
2742 lStatus = NO_ERROR;
2743
2744Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002745 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002746 return track;
2747}
2748
Andy Hung1bc088a2018-02-09 15:57:31 -08002749template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002750ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002751{
Andy Hungc0691382018-09-12 18:01:57 -07002752 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002753 const ssize_t index = mTracks.remove(track);
2754 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002755 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002756 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002757 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002758 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002759 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002760 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002761 }
2762 return index;
2763}
2764
Andy Hungee58e4a2023-07-07 13:47:37 -07002765uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002766{
2767 return latency;
2768}
2769
Andy Hungee58e4a2023-07-07 13:47:37 -07002770uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002771{
Andy Hung972bec12023-08-31 16:13:39 -07002772 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002773 return latency_l();
2774}
Andy Hungee58e4a2023-07-07 13:47:37 -07002775uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002776NO_THREAD_SAFETY_ANALYSIS
2777// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002778{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002779 uint32_t latency;
2780 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2781 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002782 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002783 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002784}
2785
Andy Hungee58e4a2023-07-07 13:47:37 -07002786void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002787{
Andy Hung972bec12023-08-31 16:13:39 -07002788 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002789 // Don't apply master volume in SW if our HAL can do it for us.
2790 if (mOutput && mOutput->audioHwDev &&
2791 mOutput->audioHwDev->canSetMasterVolume()) {
2792 mMasterVolume = 1.0;
2793 } else {
2794 mMasterVolume = value;
2795 }
2796}
2797
Andy Hungee58e4a2023-07-07 13:47:37 -07002798void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002799{
2800 mMasterBalance.store(balance);
2801}
2802
Andy Hungee58e4a2023-07-07 13:47:37 -07002803void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002804{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002805 if (isDuplicating()) {
2806 return;
2807 }
Andy Hung972bec12023-08-31 16:13:39 -07002808 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002809 // Don't apply master mute in SW if our HAL can do it for us.
2810 if (mOutput && mOutput->audioHwDev &&
2811 mOutput->audioHwDev->canSetMasterMute()) {
2812 mMasterMute = false;
2813 } else {
2814 mMasterMute = muted;
2815 }
2816}
2817
Andy Hungee58e4a2023-07-07 13:47:37 -07002818void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002819{
Andy Hung972bec12023-08-31 16:13:39 -07002820 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002821 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002822 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002823}
2824
Andy Hungee58e4a2023-07-07 13:47:37 -07002825void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002826{
Andy Hung972bec12023-08-31 16:13:39 -07002827 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002828 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002829 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002830}
2831
Andy Hungee58e4a2023-07-07 13:47:37 -07002832float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002833{
Andy Hung972bec12023-08-31 16:13:39 -07002834 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002835 return mStreamTypes[stream].volume;
2836}
2837
Andy Hungee58e4a2023-07-07 13:47:37 -07002838void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002839{
2840 mOutput->stream->setVolume(left, right);
2841}
2842
Andy Hungc5007f82023-08-29 14:26:09 -07002843// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002844status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hungc5007f82023-08-29 14:26:09 -07002845NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08002846{
2847 status_t status = ALREADY_EXISTS;
2848
Eric Laurent81784c32012-11-19 14:55:58 -08002849 if (mActiveTracks.indexOf(track) < 0) {
2850 // the track is newly added, make sure it fills up all its
2851 // buffers before playing. This is to ensure the client will
2852 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002853 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002854 IAfTrackBase::track_state state = track->state();
Andy Hungc5007f82023-08-29 14:26:09 -07002855 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002856 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002857 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002859 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002861 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002862 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002863 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864 }
2865 return INVALID_OPERATION;
2866 }
2867 // abort if start is rejected by audio policy manager
2868 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002869 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2870 // current playback thread is reopened, which may happen when clients set preferred
2871 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2872 // immediately.
2873 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 }
2875#ifdef ADD_BATTERY_DATA
2876 // to track the speaker usage
2877 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2878#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002879 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 }
2881
Eric Laurent51716182016-02-29 18:00:56 -08002882 // set retry count for buffer fill
2883 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002884 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002885 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002886 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002887 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002888 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002889 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002890 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002891 track->retryCount() = kMaxTrackStartupRetries;
2892 track->fillingStatus() =
2893 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002894 }
2895
Andy Hung116bc262023-06-20 18:56:17 -07002896 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002897 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2898 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2899 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002900 // Unlock due to VibratorService will lock for this call and will
2901 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002902 mutex().unlock();
Andy Hung7fb97e12023-07-20 21:23:42 -07002903 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002904 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002905 std::optional<media::AudioVibratorInfo> vibratorInfo;
2906 {
2907 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2908 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002909 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002910 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002911 }
Andy Hungc5007f82023-08-29 14:26:09 -07002912 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002913 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002914 if (vibratorInfo) {
2915 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2916 }
2917
jiabin57303cc2018-12-18 15:45:57 -08002918 // Haptic playback should be enabled by vibrator service.
2919 if (track->getHapticPlaybackEnabled()) {
2920 // Disable haptic playback of all active track to ensure only
2921 // one track playing haptic if current track should play haptic.
2922 for (const auto &t : mActiveTracks) {
2923 t->setHapticPlaybackEnabled(false);
2924 }
jiabin245cdd92018-12-07 17:55:15 -08002925 }
jiabine70bc7f2020-06-30 22:07:55 -07002926
2927 // Set haptic intensity for effect
2928 if (chain != nullptr) {
2929 chain->setHapticIntensity_l(track->id(), intensity);
2930 }
jiabin245cdd92018-12-07 17:55:15 -08002931 }
2932
Andy Hung8d31fd22023-06-26 19:20:57 -07002933 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002934 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002935 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002936 if (chain != 0) {
2937 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2938 track->sessionId());
2939 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002940 }
2941
Andy Hungc2b11cb2020-04-22 09:04:01 -07002942 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002943 status = NO_ERROR;
2944 }
2945
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002946 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002947 return status;
2948}
2949
Andy Hungee58e4a2023-07-07 13:47:37 -07002950bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002951{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002952 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002953 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002954 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002955 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002957 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002958 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002959 if (track->isPausePending()) {
2960 track->pauseAck();
2961 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002962 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002963 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002964
2965 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002966}
2967
Andy Hungee58e4a2023-07-07 13:47:37 -07002968void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002969{
2970 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002971
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002972 String8 result;
2973 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002974 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002975
Eric Laurent81784c32012-11-19 14:55:58 -08002976 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002977 {
Andy Hung972bec12023-08-31 16:13:39 -07002978 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002979 mAudioTrackCallbacks.erase(track);
2980 }
Eric Laurent81784c32012-11-19 14:55:58 -08002981 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002982 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002983 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002984 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2985 mFastTrackAvailMask |= 1 << index;
2986 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002987 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002988 }
Andy Hung116bc262023-06-20 18:56:17 -07002989 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002990 if (chain != 0) {
2991 chain->decTrackCnt();
2992 }
2993}
2994
Andy Hungee58e4a2023-07-07 13:47:37 -07002995String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002996{
Andy Hung972bec12023-08-31 16:13:39 -07002997 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002998 String8 out_s8;
2999 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3000 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003001 }
Andy Hung920f6572022-10-06 12:09:49 -07003002 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003003}
3004
Andy Hungee58e4a2023-07-07 13:47:37 -07003005status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003006 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003007 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003008 return NO_INIT;
3009 }
3010 return mOutput->stream->selectPresentation(presentationId, programId);
3011}
3012
Andy Hungab65b182023-09-06 19:41:47 -07003013void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003014 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003015 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003016 sp<AudioIoDescriptor> desc;
3017 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003018 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003019 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003020 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003021 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003022 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3023 mSampleRate, mFormat, mChannelMask,
3024 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3025 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003026 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003027 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003028 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003029 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003030 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003031 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003032 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003033 break;
3034 }
Andy Hungab65b182023-09-06 19:41:47 -07003035 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003036}
3037
Andy Hungee58e4a2023-07-07 13:47:37 -07003038void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003039{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003040 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003041}
3042
Andy Hungee58e4a2023-07-07 13:47:37 -07003043void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003044{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003045 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003046}
3047
Andy Hungee58e4a2023-07-07 13:47:37 -07003048void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003049{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003050 mCallbackThread->setAsyncError();
3051}
3052
Andy Hungee58e4a2023-07-07 13:47:37 -07003053void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003054 const std::basic_string<uint8_t>& metadataBs)
3055{
Andy Hungee58e4a2023-07-07 13:47:37 -07003056 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003057 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003058 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003059 if (playbackThread == nullptr) {
3060 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3061 return;
3062 }
3063
jiabinf6eb4c32020-02-25 14:06:25 -08003064 audio_utils::metadata::Data metadata =
3065 audio_utils::metadata::dataFromByteString(metadataBs);
3066 if (metadata.empty()) {
3067 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3068 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3069 (int)metadataBs.size());
3070 return;
3071 }
3072
3073 audio_utils::metadata::ByteString metaDataStr =
3074 audio_utils::metadata::byteStringFromData(metadata);
3075 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003076 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003077 for (const auto& callbackPair : mAudioTrackCallbacks) {
3078 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003079 }
3080 }).detach();
3081}
3082
Andy Hungee58e4a2023-07-07 13:47:37 -07003083void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003084{
Andy Hung972bec12023-08-31 16:13:39 -07003085 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003086 // reject out of sequence requests
3087 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3088 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003089 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003090 }
3091}
3092
Andy Hungee58e4a2023-07-07 13:47:37 -07003093void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094{
Andy Hung972bec12023-08-31 16:13:39 -07003095 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003096 // reject out of sequence requests
3097 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003098 // Register discontinuity when HW drain is completed because that can cause
3099 // the timestamp frame position to reset to 0 for direct and offload threads.
3100 // (Out of sequence requests are ignored, since the discontinuity would be handled
3101 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003102 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003103 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003104 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105 }
3106}
3107
Andy Hungee58e4a2023-07-07 13:47:37 -07003108void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003109NO_THREAD_SAFETY_ANALYSIS
3110// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003111{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003112 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003113 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3114 mSampleRate = audioConfig.sample_rate;
3115 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003116 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003117 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003118 }
Andy Hung81994d62023-07-20 21:44:14 -07003119 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003120 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3121 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003122 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003123
3124 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3125 mMixerChannelMask = mChannelMask;
3126 }
3127
Andy Hunge5412692014-05-16 11:25:07 -07003128 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003129 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003130
Eric Laurentf1f22e72021-07-13 14:04:14 +02003131 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3132
Phil Burkca5e6142015-07-14 09:42:29 -07003133 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003134 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003135 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003136 // Get format from the shim, which will be different than the HAL format
3137 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003138 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003139 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003140 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003141 }
Andy Hung81994d62023-07-20 21:44:14 -07003142 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003143 LOG_FATAL("HAL format %#x not supported for mixed output",
3144 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003145 }
Phil Burk062e67a2015-02-11 13:40:50 -08003146 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003147 result = mOutput->stream->getBufferSize(&mBufferSize);
3148 LOG_ALWAYS_FATAL_IF(result != OK,
3149 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003150 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003151 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003152 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003153 mFrameCount);
3154 }
3155
Eric Laurentd1f69b02014-12-15 14:33:13 -08003156 mHwSupportsPause = false;
3157 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003158 bool supportsPause = false, supportsResume = false;
3159 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3160 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003161 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003162 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003163 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003164 } else if (supportsResume) {
3165 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003166 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003167 }
3168 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003169 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3170 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3171 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003172
Andy Hungfbfc3952015-01-15 13:33:51 -08003173 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3174 // For best precision, we use float instead of the associated output
3175 // device format (typically PCM 16 bit).
3176
3177 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3178 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3179 mBufferSize = mFrameSize * mFrameCount;
3180
3181 // TODO: We currently use the associated output device channel mask and sample rate.
3182 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3183 // (if a valid mask) to avoid premature downmix.
3184 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3185 // instead of the output device sample rate to avoid loss of high frequency information.
3186 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3187 }
3188
Andy Hung09a50072014-02-27 14:30:47 -08003189 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003190 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003191 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003192 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3193 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003194 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3195 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003196
Eric Laurent81784c32012-11-19 14:55:58 -08003197 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3198 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3199 maxNormalFrameCount = maxNormalFrameCount & ~15;
3200 if (maxNormalFrameCount < minNormalFrameCount) {
3201 maxNormalFrameCount = minNormalFrameCount;
3202 }
3203 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3204 if (multiplier <= 1.0) {
3205 multiplier = 1.0;
3206 } else if (multiplier <= 2.0) {
3207 if (2 * mFrameCount <= maxNormalFrameCount) {
3208 multiplier = 2.0;
3209 } else {
3210 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3211 }
3212 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003213 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003214 }
3215 }
3216 mNormalFrameCount = multiplier * mFrameCount;
3217 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003218 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003219 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3220 }
Andy Hungab65b182023-09-06 19:41:47 -07003221 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3222 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003223
Andy Hung08fb1742015-05-31 23:22:10 -07003224 // Check if we want to throttle the processing to no more than 2x normal rate
3225 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003226 mThreadThrottleTimeMs = 0;
3227 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003228 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3229
Andy Hung010a1a12014-03-13 13:57:33 -07003230 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3231 // Originally this was int16_t[] array, need to remove legacy implications.
3232 free(mSinkBuffer);
3233 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003234
Andy Hung5b10a202014-03-13 13:59:29 -07003235 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3236 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3237 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003238 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003239
Andy Hung69aed5f2014-02-25 17:24:40 -08003240 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3241 // drives the output.
3242 free(mMixerBuffer);
3243 mMixerBuffer = NULL;
3244 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003245 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003246 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003247 * audio_bytes_per_sample(mMixerBufferFormat);
3248 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3249 }
Andy Hung98ef9782014-03-04 14:46:50 -08003250 free(mEffectBuffer);
3251 mEffectBuffer = NULL;
3252 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003253 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003254 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003255 * audio_bytes_per_sample(mEffectBufferFormat);
3256 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3257 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003258
Eric Laurentb62d0362021-10-26 17:40:18 +02003259 if (mType == SPATIALIZER) {
3260 free(mPostSpatializerBuffer);
3261 mPostSpatializerBuffer = nullptr;
3262 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3263 * audio_bytes_per_sample(mEffectBufferFormat);
3264 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3265 }
3266
Mikhail Naganov55773032020-10-01 15:08:13 -07003267 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3268 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003269 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3270 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003271 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003272
Eric Laurent81784c32012-11-19 14:55:58 -08003273 // force reconfiguration of effect chains and engines to take new buffer size and audio
3274 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003275 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003276 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3277 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003278 // create a copy of mEffectChains as calling moveEffectChain_ll()
3279 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003280 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003281 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003282 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003283 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003284 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003285
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003286 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003287 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003288 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003289 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003290 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3291 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3292 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3293 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3294 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3295 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3296 (int32_t)mHapticChannelMask)
3297 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3298 (int32_t)mHapticChannelCount)
3299 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003300 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003301 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3302 (int32_t)mFrameCount) // sic - added HAL
3303 ;
3304 uint32_t latencyMs;
3305 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3306 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3307 }
3308 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003309}
3310
Andy Hungee58e4a2023-07-07 13:47:37 -07003311ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003312{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003313 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003314 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003315 }
3316 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003317 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07003318 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003319 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003320 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003321 }
Kevin Rocard12381092018-04-11 09:19:59 -07003322 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003323 MetadataUpdate change;
3324 change.playbackMetadataUpdate = metadata.tracks;
3325 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003326}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003327
Andy Hungee58e4a2023-07-07 13:47:37 -07003328void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003329 const StreamOutHalInterface::SourceMetadata& metadata)
3330{
3331 mOutput->stream->updateSourceMetadata(metadata);
3332};
3333
Andy Hungee58e4a2023-07-07 13:47:37 -07003334status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003335 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003336{
3337 if (halFrames == NULL || dspFrames == NULL) {
3338 return BAD_VALUE;
3339 }
Andy Hung972bec12023-08-31 16:13:39 -07003340 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003341 if (initCheck() != NO_ERROR) {
3342 return INVALID_OPERATION;
3343 }
Andy Hung818e7a32016-02-16 18:08:07 -08003344 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003345 *halFrames = framesWritten;
3346
3347 if (isSuspended()) {
3348 // return an estimation of rendered frames when the output is suspended
3349 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003350 *dspFrames = (uint32_t)
3351 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003352 return NO_ERROR;
3353 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003354 status_t status;
3355 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003356 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003357 *dspFrames = (size_t)frames;
3358 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003359 }
3360}
3361
Andy Hungee58e4a2023-07-07 13:47:37 -07003362product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003363{
3364 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3365 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3366 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003367 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003368 }
3369 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003370 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003371 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003372 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003373 }
3374 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003375 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003376}
3377
3378
Andy Hungee58e4a2023-07-07 13:47:37 -07003379AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003380{
Andy Hung972bec12023-08-31 16:13:39 -07003381 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003382 return mOutput;
3383}
3384
Andy Hungee58e4a2023-07-07 13:47:37 -07003385AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003386{
Andy Hung972bec12023-08-31 16:13:39 -07003387 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003388 AudioStreamOut *output = mOutput;
3389 mOutput = NULL;
3390 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3391 // must push a NULL and wait for ack
3392 mOutputSink.clear();
3393 mPipeSink.clear();
3394 mNormalSink.clear();
3395 return output;
3396}
3397
Andy Hungc5007f82023-08-29 14:26:09 -07003398// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003399sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003400{
3401 if (mOutput == NULL) {
3402 return NULL;
3403 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003404 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003405}
3406
Andy Hungee58e4a2023-07-07 13:47:37 -07003407uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003408{
3409 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3410}
3411
Andy Hungee58e4a2023-07-07 13:47:37 -07003412status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003413{
3414 if (!isValidSyncEvent(event)) {
3415 return BAD_VALUE;
3416 }
3417
Andy Hung972bec12023-08-31 16:13:39 -07003418 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003419
3420 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003421 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003422 if (event->triggerSession() == track->sessionId()) {
3423 (void) track->setSyncEvent(event);
3424 return NO_ERROR;
3425 }
3426 }
3427
3428 return NAME_NOT_FOUND;
3429}
3430
Andy Hungee58e4a2023-07-07 13:47:37 -07003431bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003432{
3433 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3434}
3435
Andy Hungee58e4a2023-07-07 13:47:37 -07003436void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003437 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003438{
Andy Hungfe726a62018-09-27 15:17:25 -07003439 // Miscellaneous track cleanup when removed from the active list,
3440 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003441#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003442 for (const auto& track : tracksToRemove) {
3443 if (track->isExternalTrack()) {
3444 // to track the speaker usage
3445 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003446 }
3447 }
Andy Hungfe726a62018-09-27 15:17:25 -07003448#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003449}
3450
Andy Hungee58e4a2023-07-07 13:47:37 -07003451void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003452{
3453 if (!mMasterMute) {
3454 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003455 if (mOutDeviceTypeAddrs.empty()) {
3456 ALOGD("ro.audio.silent is ignored since no output device is set");
3457 return;
3458 }
Andy Hungab65b182023-09-06 19:41:47 -07003459 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003460 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3461 return;
3462 }
Eric Laurent81784c32012-11-19 14:55:58 -08003463 if (property_get("ro.audio.silent", value, "0") > 0) {
3464 char *endptr;
3465 unsigned long ul = strtoul(value, &endptr, 0);
3466 if (*endptr == '\0' && ul != 0) {
3467 ALOGD("Silence is golden");
3468 // The setprop command will not allow a property to be changed after
3469 // the first time it is set, so we don't have to worry about un-muting.
3470 setMasterMute_l(true);
3471 }
3472 }
3473 }
3474}
3475
3476// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003477ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003478{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003479 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003480 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003482 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003483
3484 // If an NBAIO sink is present, use it to write the normal mixer's submix
3485 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003486
Andy Hung010a1a12014-03-13 13:57:33 -07003487 const size_t count = mBytesRemaining / mFrameSize;
3488
Simon Wilson2d590962012-11-29 15:18:50 -08003489 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003490 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003491 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003492 if (screenState != mScreenState) {
3493 mScreenState = screenState;
3494 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3495 if (pipe != NULL) {
3496 pipe->setAvgFrames((mScreenState & 1) ?
3497 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3498 }
3499 }
Andy Hung010a1a12014-03-13 13:57:33 -07003500 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003501 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003502
Eric Laurent81784c32012-11-19 14:55:58 -08003503 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003504 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003505
Andy Hung8946a282018-04-19 20:04:56 -07003506#ifdef TEE_SINK
3507 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3508#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003509 } else {
3510 bytesWritten = framesWritten;
3511 }
3512 // otherwise use the HAL / AudioStreamOut directly
3513 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003515
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003517 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3518 mWriteAckSequence += 2;
3519 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003520 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003521 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003522 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003523 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003524 // FIXME We should have an implementation of timestamps for direct output threads.
3525 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003526 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003527 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003528
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529 if (mUseAsyncWrite &&
3530 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3531 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003532 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003533 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003534 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003535 }
Eric Laurent81784c32012-11-19 14:55:58 -08003536 }
3537
Eric Laurent81784c32012-11-19 14:55:58 -08003538 mNumWrites++;
3539 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003540 if (mStandby) {
3541 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003542 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003543 mStandby = false;
3544 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003545 return bytesWritten;
3546}
3547
Andy Hungc5007f82023-08-29 14:26:09 -07003548// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003549void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003550 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003551{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003552 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003553 if (outputSink != nullptr) {
3554 outputSink->startMelComputation(processor);
3555 }
Vlad Popab042ee62022-10-20 18:05:00 +02003556}
3557
Andy Hungc5007f82023-08-29 14:26:09 -07003558// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003559void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003560{
3561 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003562 if (outputSink != nullptr) {
3563 outputSink->stopMelComputation();
3564 }
Vlad Popab042ee62022-10-20 18:05:00 +02003565}
3566
Andy Hungee58e4a2023-07-07 13:47:37 -07003567void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003568{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003569 bool supportsDrain = false;
3570 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3572 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003573 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3574 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003575 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003576 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003577 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003578 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003579 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580 }
3581}
3582
Andy Hungee58e4a2023-07-07 13:47:37 -07003583void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003584{
Eric Laurent275e8e92014-11-30 15:14:47 -08003585 {
Andy Hung972bec12023-08-31 16:13:39 -07003586 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003587 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003588 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003589 track->invalidate();
3590 }
Andy Hungdae27702016-10-31 14:01:16 -07003591 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3592 // After we exit there are no more track changes sent to BatteryNotifier
3593 // because that requires an active threadLoop.
3594 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3595 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003596 }
Eric Laurent81784c32012-11-19 14:55:58 -08003597}
3598
3599/*
3600The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003601 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003602 - mActiveSleepTimeUs from activeSleepTimeUs()
3603 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003604 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3605 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003606 - maxPeriod from frame count and sample rate (MIXER only)
3607
3608The parameters that affect these derived values are:
3609 - frame count
3610 - frame size
3611 - sample rate
3612 - device type: A2DP or not
3613 - device latency
3614 - format: PCM or not
3615 - active sleep time
3616 - idle sleep time
3617*/
3618
Andy Hungee58e4a2023-07-07 13:47:37 -07003619void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003620{
Andy Hung25c2dac2014-02-27 14:56:00 -08003621 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003622 mActiveSleepTimeUs = activeSleepTimeUs();
3623 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003624
Andy Hung8fe87eb2023-07-20 21:31:38 -07003625 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003626
Eric Laurent42537be2016-01-08 17:16:42 -08003627 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3628 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003629 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003630 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3631 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3632 }
3633 }
Eric Laurent81784c32012-11-19 14:55:58 -08003634}
3635
Andy Hungee58e4a2023-07-07 13:47:37 -07003636bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003637{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003638 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003639 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003640 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003641 size_t size = mTracks.size();
3642 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003643 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003644 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003645 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003646 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003647 }
3648 }
Eric Laurent13084622016-05-17 10:51:49 -07003649 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003650}
3651
Andy Hungee58e4a2023-07-07 13:47:37 -07003652void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003653{
Andy Hung972bec12023-08-31 16:13:39 -07003654 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003655 invalidateTracks_l(streamType);
3656}
3657
Andy Hungee58e4a2023-07-07 13:47:37 -07003658void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003659 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003660 invalidateTracks_l(portIds);
3661}
3662
Andy Hungee58e4a2023-07-07 13:47:37 -07003663bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003664 bool trackMatch = false;
3665 const size_t size = mTracks.size();
3666 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003667 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003668 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3669 t->invalidate();
3670 portIds.erase(t->portId());
3671 trackMatch = true;
3672 }
3673 if (portIds.empty()) {
3674 break;
3675 }
3676 }
3677 return trackMatch;
3678}
3679
jiabinf042b9b2021-05-07 23:46:28 +00003680// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003681IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003682 audio_port_handle_t trackPortId) {
3683 for (size_t i = 0; i < mTracks.size(); i++) {
3684 if (mTracks[i]->portId() == trackPortId) {
3685 return mTracks[i].get();
3686 }
3687 }
3688 return nullptr;
3689}
3690
Andy Hungee58e4a2023-07-07 13:47:37 -07003691status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003692{
Glenn Kastend848eb42016-03-08 13:42:11 -08003693 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003694 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003695 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003696
Andy Hungd3639922022-04-28 18:00:49 -07003697 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003698 if (!audio_is_global_session(session)) {
3699 // player sessions on a spatializer output will use a dedicated input buffer and
3700 // will either output multi channel to mEffectBuffer if the track is spatilaized
3701 // or stereo to mPostSpatializerBuffer if not spatialized.
3702 uint32_t channelMask;
3703 bool isSessionSpatialized =
3704 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3705 if (isSessionSpatialized) {
3706 channelMask = mMixerChannelMask;
3707 } else {
3708 channelMask = mChannelMask;
3709 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003710 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003711 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003712 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003713 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003714 &halInBuffer);
3715 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003716
Andy Hung583043b2023-07-17 17:05:00 -07003717 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003718 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3719 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3720 &halOutBuffer);
3721 if (result != OK) return result;
3722
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003723 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003724
Mikhail Naganov022b9952017-01-04 16:36:51 -08003725 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3726 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003727 } else {
3728 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3729 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3730 // mPostSpatializerBuffer as output buffer
3731 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003732 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003733 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3734 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003735 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003736 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3737 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003738
Eric Laurentb62d0362021-10-26 17:40:18 +02003739 if (session == AUDIO_SESSION_DEVICE) {
3740 halInBuffer = halOutBuffer;
3741 }
3742 }
3743 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003744 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003745 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3746 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3747 &halInBuffer);
3748 if (result != OK) return result;
3749 halOutBuffer = halInBuffer;
3750 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3751 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003752 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003753 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003754 // Only one effect chain can be present in direct output thread and it uses
3755 // the sink buffer as input
3756 if (mType != DIRECT) {
3757 size_t numSamples = mNormalFrameCount
3758 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3759 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003760 const status_t allocateStatus =
3761 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003762 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003763 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003764 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003765
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003766 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003767 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3768 buffer, session);
3769 }
3770 }
3771 }
3772
3773 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003774 // Attach all tracks with same session ID to this chain.
3775 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003776 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003777 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003778 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3779 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003780 track->setMainBuffer(buffer);
3781 chain->incTrackCnt();
3782 }
3783 }
3784
3785 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003786 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003787 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003788 ALOGV("addEffectChain_l() activating track %p on session %d",
3789 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003790 chain->incActiveTrackCnt();
3791 }
3792 }
3793 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003794
Eric Laurentaaa44472014-09-12 17:41:50 -07003795 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003796 chain->setInBuffer(halInBuffer);
3797 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003798 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3799 // chains list in order to be processed last as it contains output device effects.
3800 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3801 // processing effects specific to an output stream before effects applied to all streams
3802 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003803 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3804 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003805 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003806 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003807 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003808 // Effect chain for other sessions are inserted at beginning of effect
3809 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003810 // sessions is not important.
3811 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003812 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3813 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003814 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003815 size_t size = mEffectChains.size();
3816 size_t i = 0;
3817 for (i = 0; i < size; i++) {
3818 if (mEffectChains[i]->sessionId() < session) {
3819 break;
3820 }
3821 }
3822 mEffectChains.insertAt(chain, i);
3823 checkSuspendOnAddEffectChain_l(chain);
3824
3825 return NO_ERROR;
3826}
3827
Andy Hungee58e4a2023-07-07 13:47:37 -07003828size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003829{
Glenn Kastend848eb42016-03-08 13:42:11 -08003830 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003831
3832 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3833
3834 for (size_t i = 0; i < mEffectChains.size(); i++) {
3835 if (chain == mEffectChains[i]) {
3836 mEffectChains.removeAt(i);
3837 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003838 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003839 if (session == track->sessionId()) {
3840 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3841 chain.get(), session);
3842 chain->decActiveTrackCnt();
3843 }
3844 }
3845
3846 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003847 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003848 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003849 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003850 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003851 chain->decTrackCnt();
3852 }
3853 }
3854 break;
3855 }
3856 }
3857 return mEffectChains.size();
3858}
3859
Andy Hungee58e4a2023-07-07 13:47:37 -07003860status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003861 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003862{
Andy Hung972bec12023-08-31 16:13:39 -07003863 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003864 return attachAuxEffect_l(track, EffectId);
3865}
3866
Andy Hungee58e4a2023-07-07 13:47:37 -07003867status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003868 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003869{
3870 status_t status = NO_ERROR;
3871
3872 if (EffectId == 0) {
3873 track->setAuxBuffer(0, NULL);
3874 } else {
3875 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003876 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003877 if (effect != 0) {
3878 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3879 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3880 } else {
3881 status = INVALID_OPERATION;
3882 }
3883 } else {
3884 status = BAD_VALUE;
3885 }
3886 }
3887 return status;
3888}
3889
Andy Hungee58e4a2023-07-07 13:47:37 -07003890void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003891{
3892 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003893 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003894 if (track->auxEffectId() == effectId) {
3895 attachAuxEffect_l(track, 0);
3896 }
3897 }
3898}
3899
Andy Hungee58e4a2023-07-07 13:47:37 -07003900bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003901NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003902{
Andy Hung78d8d952023-05-30 18:10:23 -07003903 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003904
Andy Hung8d31fd22023-06-26 19:20:57 -07003905 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003906
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003907 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003908 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003909
3910 // MIXER
3911 nsecs_t lastWarning = 0;
3912
3913 // DUPLICATING
3914 // FIXME could this be made local to while loop?
3915 writeFrames = 0;
3916
3917 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003918 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003919
Andy Hungd3639922022-04-28 18:00:49 -07003920 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003921 sleepTimeShift = 0;
3922 }
3923
3924 CpuStats cpuStats;
3925 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3926
3927 acquireWakeLock();
3928
Glenn Kasteneef598c2017-04-03 14:41:13 -07003929 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3930 // thread associated with this PlaybackThread.
3931 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3932 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003933 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3934 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003935 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003936 const char *logString = NULL;
3937
rago1bb90822017-05-02 18:31:48 -07003938 // Estimated time for next buffer to be written to hal. This is used only on
3939 // suspended mode (for now) to help schedule the wait time until next iteration.
3940 nsecs_t timeLoopNextNs = 0;
3941
Eric Laurent664539d2013-09-23 18:24:31 -07003942 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003943
Andy Hung2dbffc22018-08-08 18:50:41 -07003944 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003945
Eric Laurentb3f315a2021-07-13 15:09:05 +02003946 sendCheckOutputStageEffectsEvent();
3947
Andy Hung446f4df2019-02-21 12:26:41 -08003948 // loopCount is used for statistics and diagnostics.
3949 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003950 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003951 // Log merge requests are performed during AudioFlinger binder transactions, but
3952 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07003953 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003954
Eric Laurent81784c32012-11-19 14:55:58 -08003955 cpuStats.sample(myName);
3956
Andy Hung116bc262023-06-20 18:56:17 -07003957 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003958 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003959 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07003960 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003961
Andy Hung2dbffc22018-08-08 18:50:41 -07003962 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3963 //
Andy Hungc5007f82023-08-29 14:26:09 -07003964 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07003965 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003966 // Here, we try for the AF lock, but do not block on it as the latency
3967 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07003968 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07003969 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003970 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003971 status_t status = INVALID_OPERATION;
3972 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07003973 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07003974 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003975 && swPatches.size() > 0) {
3976 status = swPatches[0].getLatencyMs_l(&latencyMs);
3977 downstreamPatchHandle = swPatches[0].getPatchHandle();
3978 }
3979 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003980 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003981 lastDownstreamPatchHandle = downstreamPatchHandle;
3982 }
3983 if (status == OK) {
3984 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003985 // latency of 5 seconds).
3986 const double minLatency = 0., maxLatency = 5000.;
3987 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003988 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003989 } else {
3990 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003991 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003992 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003993 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003994 }
Andy Hung583043b2023-07-17 17:05:00 -07003995 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003996 }
3997 } else {
3998 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3999 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004000 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004001 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4002 }
4003 }
4004
Eric Laurentb3f315a2021-07-13 15:09:05 +02004005 if (mCheckOutputStageEffects.exchange(false)) {
4006 checkOutputStageEffects();
4007 }
4008
Vlad Popa7e81cea2023-01-19 16:34:16 +01004009 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004010 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004011
Andy Hungc5007f82023-08-29 14:26:09 -07004012 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004013
Eric Laurent021cf962014-05-13 10:18:14 -07004014 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004015 if (mCheckOutputStageEffects.load()) {
4016 continue;
4017 }
Eric Laurent10351942014-05-08 18:49:52 -07004018
Andy Hungc5007f82023-08-29 14:26:09 -07004019 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004020 if (logString != NULL) {
4021 mNBLogWriter->logTimestamp();
4022 mNBLogWriter->log(logString);
4023 logString = NULL;
4024 }
4025
Dean Wheatley12473e92021-03-18 23:00:55 +11004026 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004027
Eric Laurent81784c32012-11-19 14:55:58 -08004028 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004029 if (mSignalPending) {
4030 // A signal was raised while we were unlocked
4031 mSignalPending = false;
4032 } else if (waitingAsyncCallback_l()) {
4033 if (exitPending()) {
4034 break;
4035 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004036 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004037 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004038 releaseWakeLock_l();
4039 released = true;
4040 }
Andy Hung10cbff12017-02-21 17:30:14 -08004041
4042 const int64_t waitNs = computeWaitTimeNs_l();
4043 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004044 std::cv_status cvstatus =
4045 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4046 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004047 mSignalPending = true; // if timeout recheck everything
4048 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004049 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004050 if (released) {
4051 acquireWakeLock_l();
4052 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004053 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4054 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004055
4056 continue;
4057 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004058 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004059 isSuspended()) {
4060 // put audio hardware into standby after short delay
4061 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004062
4063 threadLoop_standby();
4064
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004065 // This is where we go into standby
4066 if (!mStandby) {
4067 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004068 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004069 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004070 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004071 }
Andy Hungd0979812019-02-21 15:51:44 -08004072 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004073 }
4074
Eric Tan39ec8d62018-07-24 09:49:29 -07004075 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004076 // we're about to wait, flush the binder command buffer
4077 IPCThreadState::self()->flushCommands();
4078
4079 clearOutputTracks();
4080
4081 if (exitPending()) {
4082 break;
4083 }
4084
4085 releaseWakeLock_l();
4086 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004087 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004088 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004089 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004090 acquireWakeLock_l();
4091
4092 mMixerStatus = MIXER_IDLE;
4093 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4094 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004095 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004096 checkSilentMode_l();
4097
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004098 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4099 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004100 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004101 sleepTimeShift = 0;
4102 }
4103
4104 continue;
4105 }
4106 }
Eric Laurent81784c32012-11-19 14:55:58 -08004107 // mMixerStatusIgnoringFastTracks is also updated internally
4108 mMixerStatus = prepareTracks_l(&tracksToRemove);
4109
Andy Hungab65b182023-09-06 19:41:47 -07004110 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004111
Vlad Popa7e81cea2023-01-19 16:34:16 +01004112 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004113
Eric Laurent81784c32012-11-19 14:55:58 -08004114 // prevent any changes in effect chain list and in each effect chain
4115 // during mixing and effect process as the audio buffers could be deleted
4116 // or modified if an effect is created or deleted
4117 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004118
4119 // Determine which session to pick up haptic data.
4120 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004121 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004122 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004123 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004124 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004125 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004126 if (effectChain != nullptr
4127 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004128 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004129 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004130 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004131 break;
4132 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004133 if (activeHapticSessionId == AUDIO_SESSION_NONE
4134 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004135 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004136 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004137 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004138 }
4139 }
4140 }
4141
Andy Hungc1646382019-04-30 16:12:10 -07004142 // Acquire a local copy of active tracks with lock (release w/o lock).
4143 //
4144 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4145 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4146 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4147 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004148
4149 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004150
Jiabin Huangfb476842022-12-06 03:18:10 +00004151 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004152 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004153 }
4154
Eric Laurent19952e12023-04-20 10:08:29 +02004155 // signal actual start of output stream when the render position reported by the kernel
4156 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004157 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4158 && (mKernelPositionOnStandby
4159 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004160 mHalStarted = true;
Andy Hungc5007f82023-08-29 14:26:09 -07004161 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004162 }
Andy Hungc5007f82023-08-29 14:26:09 -07004163 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004164
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 if (mBytesRemaining == 0) {
4166 mCurrentWriteLength = 0;
4167 if (mMixerStatus == MIXER_TRACKS_READY) {
4168 // threadLoop_mix() sets mCurrentWriteLength
4169 threadLoop_mix();
4170 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4171 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004172 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004173 // must be written to HAL
4174 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004175 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004176 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004177
4178 // Tally underrun frames as we are inserting 0s here.
4179 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004180 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004181 && !track->isStopped()
4182 && !track->isPaused()
4183 && !track->isTerminated()) {
4184 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4185 __func__, track->id(), track->getTrackStateAsString(),
4186 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004187 track->audioTrackServerProxy()->tallyUnderrunFrames(
4188 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004189 }
4190 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004191 }
4192 }
Andy Hung98ef9782014-03-04 14:46:50 -08004193 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004194 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004195 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004196 // or mSinkBuffer (if there are no effects and there is no data already copied to
4197 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004198 //
4199 // This is done pre-effects computation; if effects change to
4200 // support higher precision, this needs to move.
4201 //
4202 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004203 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004204 uint32_t mixerChannelCount = mEffectBufferValid ?
4205 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004206 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004207 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4208 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4209
David Li88ee0902022-06-22 10:01:21 +08004210 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4211 // do these processes after effects are applied.
4212 if (!mEffectBufferValid) {
4213 // mono blend occurs for mixer threads only (not direct or offloaded)
4214 // and is handled here if we're going directly to the sink.
4215 if (requireMonoBlend()) {
4216 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4217 mNormalFrameCount, true /*limit*/);
4218 }
Andy Hung2ddee192015-12-18 17:34:44 -08004219
David Li88ee0902022-06-22 10:01:21 +08004220 if (!hasFastMixer()) {
4221 // Balance must take effect after mono conversion.
4222 // We do it here if there is no FastMixer.
4223 // mBalance detects zero balance within the class for speed
4224 // (not needed here).
4225 mBalance.setBalance(mMasterBalance.load());
4226 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4227 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004228 }
4229
Andy Hung98ef9782014-03-04 14:46:50 -08004230 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004231 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004232
4233 // If we're going directly to the sink and there are haptic channels,
4234 // we should adjust channels as the sample data is partially interleaved
4235 // in this case.
4236 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4237 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4238 mChannelCount + mHapticChannelCount,
4239 audio_bytes_per_sample(format),
4240 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4241 }
Andy Hung98ef9782014-03-04 14:46:50 -08004242 }
4243
Eric Laurentbfb1b832013-01-07 09:53:42 -08004244 mBytesRemaining = mCurrentWriteLength;
4245 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004246 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4247 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4248 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4249 mBytesWritten += mBytesRemaining;
4250 mFramesWritten += framesRemaining;
4251 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004252 mBytesRemaining = 0;
4253 }
Eric Laurent81784c32012-11-19 14:55:58 -08004254
Eric Laurentbfb1b832013-01-07 09:53:42 -08004255 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004256 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004257 for (size_t i = 0; i < effectChains.size(); i ++) {
4258 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004259 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004260 if (activeHapticSessionId != AUDIO_SESSION_NONE
4261 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004262 // Haptic data is active in this case, copy it directly from
4263 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004264 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4265 audio_channel_count_from_out_mask(mMixerChannelMask) :
4266 mChannelCount;
4267 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4268 hapticSessionChannelCount = mChannelCount;
4269 }
4270
jiabin47affe52019-04-04 18:02:07 -07004271 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004272 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004273 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004274 memcpy_by_audio_format(
4275 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004276 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004277 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004278 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004279 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004280 }
Eric Laurent81784c32012-11-19 14:55:58 -08004281 }
4282 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004283 // Process effect chains for offloaded thread even if no audio
4284 // was read from audio track: process only updates effect state
4285 // and thus does have to be synchronized with audio writes but may have
4286 // to be called while waiting for async write callback
4287 if (mType == OFFLOAD) {
4288 for (size_t i = 0; i < effectChains.size(); i ++) {
4289 effectChains[i]->process_l();
4290 }
4291 }
Eric Laurent81784c32012-11-19 14:55:58 -08004292
Andy Hung98ef9782014-03-04 14:46:50 -08004293 // Only if the Effects buffer is enabled and there is data in the
4294 // Effects buffer (buffer valid), we need to
4295 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004296 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004297 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004298 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004299 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004300 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004301 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004302 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004303 }
4304
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004305 if (!hasFastMixer()) {
4306 // Balance must take effect after mono conversion.
4307 // We do it here if there is no FastMixer.
4308 // mBalance detects zero balance within the class for speed (not needed here).
4309 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004310 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004311 }
4312
Eric Laurentb62d0362021-10-26 17:40:18 +02004313 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4314 // mPostSpatializerBuffer if the haptics track is spatialized.
4315 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4316 // For other thread types, the haptics channels are already in mEffectBuffer.
4317 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4318 const size_t srcBufferSize = mNormalFrameCount *
4319 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4320 mEffectBufferFormat);
4321 const size_t dstBufferSize = mNormalFrameCount
4322 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4323
4324 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4325 mEffectBufferFormat,
4326 (uint8_t*)mEffectBuffer + srcBufferSize,
4327 mEffectBufferFormat,
4328 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004329 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004330 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4331 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4332 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4333 // Clamp PCM float values more than this distance from 0 to insulate
4334 // a HAL which doesn't handle NaN correctly.
4335 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4336 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4337 static_cast<const float*>(effectBuffer),
4338 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4339 } else {
4340 memcpy_by_audio_format(mSinkBuffer, mFormat,
4341 effectBuffer, mEffectBufferFormat, framesToCopy);
4342 }
jiabin245cdd92018-12-07 17:55:15 -08004343 // The sample data is partially interleaved when haptic channels exist,
4344 // we need to adjust channels here.
4345 if (mHapticChannelCount > 0) {
4346 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4347 mChannelCount + mHapticChannelCount,
4348 audio_bytes_per_sample(mFormat),
4349 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4350 }
Andy Hung98ef9782014-03-04 14:46:50 -08004351 }
4352
Eric Laurent81784c32012-11-19 14:55:58 -08004353 // enable changes in effect chain
4354 unlockEffectChains(effectChains);
4355
Vlad Popafce10862023-02-03 10:37:07 +01004356 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004357 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004358 metadataUpdate.playbackMetadataUpdate);
4359 }
4360
Eric Laurentbfb1b832013-01-07 09:53:42 -08004361 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004362 // mSleepTimeUs == 0 means we must write to audio hardware
4363 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004364 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004365 // writePeriodNs is updated >= 0 when ret > 0.
4366 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004367 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004368 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004369 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004370 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004371 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004372 if (ret < 0) {
4373 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004374 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004375 mBytesWritten += ret;
4376 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004377 const int64_t frames = ret / mFrameSize;
4378 mFramesWritten += frames;
4379
4380 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4381 // process information relating to write time.
4382 if (audio_has_proportional_frames(mFormat)) {
4383 // we are in a continuous mixing cycle
4384 if (mMixerStatus == MIXER_TRACKS_READY &&
4385 loopCount == lastLoopCountWritten + 1) {
4386
4387 const double jitterMs =
4388 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4389 {frames, writePeriodNs},
4390 {0, 0} /* lastTimestamp */, mSampleRate);
4391 const double processMs =
4392 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4393
Andy Hung972bec12023-08-31 16:13:39 -07004394 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004395 mIoJitterMs.add(jitterMs);
4396 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004397
4398 if (mPipeSink.get() != nullptr) {
4399 // Using the Monopipe availableToWrite, we estimate the current
4400 // buffer size.
4401 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4402 const ssize_t
4403 availableToWrite = mPipeSink->availableToWrite();
4404 const size_t pipeFrames = monoPipe->maxFrames();
4405 const size_t
4406 remainingFrames = pipeFrames - max(availableToWrite, 0);
4407 mMonopipePipeDepthStats.add(remainingFrames);
4408 }
Andy Hung446f4df2019-02-21 12:26:41 -08004409 }
4410
4411 // write blocked detection
4412 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004413 if ((mType == MIXER || mType == SPATIALIZER)
4414 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004415 mNumDelayedWrites++;
4416 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4417 ATRACE_NAME("underrun");
4418 ALOGW("write blocked for %lld msecs, "
4419 "%d delayed writes, thread %d",
4420 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4421 mNumDelayedWrites, mId);
4422 lastWarning = lastIoEndNs;
4423 }
4424 }
4425 }
4426 // update timing info.
4427 mLastIoBeginNs = lastIoBeginNs;
4428 mLastIoEndNs = lastIoEndNs;
4429 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004430 }
4431 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4432 (mMixerStatus == MIXER_DRAIN_ALL)) {
4433 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004434 }
Andy Hungd3639922022-04-28 18:00:49 -07004435 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004436
4437 if (mThreadThrottle
4438 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004439 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004440 // Limit MixerThread data processing to no more than twice the
4441 // expected processing rate.
4442 //
4443 // This helps prevent underruns with NuPlayer and other applications
4444 // which may set up buffers that are close to the minimum size, or use
4445 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4446 //
4447 // The throttle smooths out sudden large data drains from the device,
4448 // e.g. when it comes out of standby, which often causes problems with
4449 // (1) mixer threads without a fast mixer (which has its own warm-up)
4450 // (2) minimum buffer sized tracks (even if the track is full,
4451 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004452 //
4453 // Total time spent in last processing cycle equals time spent in
4454 // 1. threadLoop_write, as well as time spent in
4455 // 2. threadLoop_mix (significant for heavy mixing, especially
4456 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004457
Andy Hung446f4df2019-02-21 12:26:41 -08004458 // it's OK if deltaMs is an overestimate.
4459
4460 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004461
Ivan Lozanoea04d392017-11-07 14:37:07 -08004462 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004463 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004464 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004465
Andy Hung08fb1742015-05-31 23:22:10 -07004466 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004467 // notify of throttle start on verbose log
4468 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4469 "mixer(%p) throttle begin:"
4470 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004471 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004472 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004473 // Throttle must be attributed to the previous mixer loop's write time
4474 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004475 // This also ensures proper timing statistics.
4476 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004477 } else {
4478 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4479 if (diff > 0) {
4480 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004481 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004482 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004483 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004484 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004485 outDeviceTypes_l(),
4486 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004487 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004488 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4489 }
Andy Hung08fb1742015-05-31 23:22:10 -07004490 }
4491 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004492 }
Eric Laurent81784c32012-11-19 14:55:58 -08004493
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004495 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004496 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004497 // suspended requires accurate metering of sleep time.
4498 if (isSuspended()) {
4499 // advance by expected sleepTime
4500 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4501 const nsecs_t nowNs = systemTime();
4502
4503 // compute expected next time vs current time.
4504 // (negative deltas are treated as delays).
4505 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4506 if (deltaNs < -kMaxNextBufferDelayNs) {
4507 // Delays longer than the max allowed trigger a reset.
4508 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4509 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4510 timeLoopNextNs = nowNs + deltaNs;
4511 } else if (deltaNs < 0) {
4512 // Delays within the max delay allowed: zero the delta/sleepTime
4513 // to help the system catch up in the next iteration(s)
4514 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4515 deltaNs = 0;
4516 }
4517 // update sleep time (which is >= 0)
4518 mSleepTimeUs = deltaNs / 1000;
4519 }
Eric Laurente93cc032016-05-05 10:15:10 -07004520 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004521 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004522 }
Glenn Kastene7754022014-10-31 12:11:26 -07004523 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004524 }
Eric Laurent81784c32012-11-19 14:55:58 -08004525 }
4526
4527 // Finally let go of removed track(s), without the lock held
4528 // since we can't guarantee the destructors won't acquire that
4529 // same lock. This will also mutate and push a new fast mixer state.
4530 threadLoop_removeTracks(tracksToRemove);
4531 tracksToRemove.clear();
4532
4533 // FIXME I don't understand the need for this here;
4534 // it was in the original code but maybe the
4535 // assignment in saveOutputTracks() makes this unnecessary?
4536 clearOutputTracks();
4537
4538 // Effect chains will be actually deleted here if they were removed from
4539 // mEffectChains list during mixing or effects processing
4540 effectChains.clear();
4541
4542 // FIXME Note that the above .clear() is no longer necessary since effectChains
4543 // is now local to this block, but will keep it for now (at least until merge done).
4544 }
4545
Eric Laurentbfb1b832013-01-07 09:53:42 -08004546 threadLoop_exit();
4547
Eric Laurentcf817a22014-08-04 20:36:31 -07004548 if (!mStandby) {
4549 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004550 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004551 }
4552
4553 releaseWakeLock();
4554
4555 ALOGV("Thread %p type %d exiting", this, mType);
4556 return false;
4557}
4558
Andy Hungee58e4a2023-07-07 13:47:37 -07004559void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004560{
Dean Wheatley12473e92021-03-18 23:00:55 +11004561 if (mStandby) {
4562 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4563 return;
4564 } else if (mHwPaused) {
4565 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4566 return;
4567 }
4568
4569 // Gather the framesReleased counters for all active tracks,
4570 // and associate with the sink frames written out. We need
4571 // this to convert the sink timestamp to the track timestamp.
4572 bool kernelLocationUpdate = false;
4573 ExtendedTimestamp timestamp; // use private copy to fetch
4574
4575 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4576 // HAL may be draining some small duration buffered data for fade out.
4577 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4578 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4579 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4580 mSampleRate);
4581
Andy Hungab65b182023-09-06 19:41:47 -07004582 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004583 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4584 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4585 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4586 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4587 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4588 = correctedTimestamp.mFrames;
4589 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4590 = correctedTimestamp.mTimeNs;
4591 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4592 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4593 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4594
4595 // Note: Downstream latency only added if timestamp correction enabled.
4596 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4597 const int64_t newPosition =
4598 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4599 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4600 // prevent retrograde
4601 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4602 newPosition,
4603 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4604 - mSuspendedFrames));
4605 }
4606 }
4607
4608 // We always fetch the timestamp here because often the downstream
4609 // sink will block while writing.
4610
4611 // We keep track of the last valid kernel position in case we are in underrun
4612 // and the normal mixer period is the same as the fast mixer period, or there
4613 // is some error from the HAL.
4614 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4615 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4616 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4617 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4618 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4619
4620 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4621 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4622 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4623 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4624 }
4625
4626 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4627 kernelLocationUpdate = true;
4628 } else {
4629 ALOGVV("getTimestamp error - no valid kernel position");
4630 }
4631
4632 // copy over kernel info
4633 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4634 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4635 + mSuspendedFrames; // add frames discarded when suspended
4636 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4637 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4638 } else {
4639 mTimestampVerifier.error();
4640 }
4641
4642 // mFramesWritten for non-offloaded tracks are contiguous
4643 // even after standby() is called. This is useful for the track frame
4644 // to sink frame mapping.
4645 bool serverLocationUpdate = false;
4646 if (mFramesWritten != mLastFramesWritten) {
4647 serverLocationUpdate = true;
4648 mLastFramesWritten = mFramesWritten;
4649 }
4650 // Only update timestamps if there is a meaningful change.
4651 // Either the kernel timestamp must be valid or we have written something.
4652 if (kernelLocationUpdate || serverLocationUpdate) {
4653 if (serverLocationUpdate) {
4654 // use the time before we called the HAL write - it is a bit more accurate
4655 // to when the server last read data than the current time here.
4656 //
4657 // If we haven't written anything, mLastIoBeginNs will be -1
4658 // and we use systemTime().
4659 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4660 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4661 ? systemTime() : mLastIoBeginNs;
4662 }
4663
Andy Hung8d31fd22023-06-26 19:20:57 -07004664 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004665 if (!t->isFastTrack()) {
4666 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004667 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004668 mFramesWritten,
4669 mSampleRate,
4670 mTimestamp);
4671 }
4672 }
4673 }
4674
4675 if (audio_has_proportional_frames(mFormat)) {
4676 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4677 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4678 mLatencyMs.add(latencyMs);
4679 }
4680 }
4681#if 0
4682 // logFormat example
4683 if (z % 100 == 0) {
4684 timespec ts;
4685 clock_gettime(CLOCK_MONOTONIC, &ts);
4686 LOGT("This is an integer %d, this is a float %f, this is my "
4687 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4688 LOGT("A deceptive null-terminated string %\0");
4689 }
4690 ++z;
4691#endif
4692}
4693
Andy Hungc5007f82023-08-29 14:26:09 -07004694// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004695void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004696NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004697{
Andy Hungfe726a62018-09-27 15:17:25 -07004698 for (const auto& track : tracksToRemove) {
4699 mActiveTracks.remove(track);
4700 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004701 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004702 if (chain != 0) {
4703 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4704 __func__, track->id(), chain.get(), track->sessionId());
4705 chain->decActiveTrackCnt();
4706 }
4707 // If an external client track, inform APM we're no longer active, and remove if needed.
4708 // We do this under lock so that the state is consistent if the Track is destroyed.
4709 if (track->isExternalTrack()) {
4710 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004711 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004712 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004713 }
4714 }
Andy Hungfe726a62018-09-27 15:17:25 -07004715 if (track->isTerminated()) {
4716 // remove from our tracks vector
4717 removeTrack_l(track);
4718 }
jiabineb3bda02020-06-30 14:07:03 -07004719 if (mHapticChannelCount > 0 &&
4720 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4721 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004722 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004723 // Unlock due to VibratorService will lock for this call and will
4724 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004725 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004726 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004727
4728 // When the track is stop, set the haptic intensity as MUTE
4729 // for the HapticGenerator effect.
4730 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004731 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004732 }
jiabin245cdd92018-12-07 17:55:15 -08004733 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735}
Eric Laurent81784c32012-11-19 14:55:58 -08004736
Andy Hungee58e4a2023-07-07 13:47:37 -07004737status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004738{
4739 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004740 ExtendedTimestamp ets;
4741 status_t status = mNormalSink->getTimestamp(ets);
4742 if (status == NO_ERROR) {
4743 status = ets.getBestTimestamp(&timestamp);
4744 }
4745 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004746 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004747 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004748 collectTimestamps_l();
4749 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4750 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004751 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004752 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4753 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4754 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4755 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4756 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004757 }
4758 return INVALID_OPERATION;
4759}
Eric Laurent1c333e22014-05-20 10:48:17 -07004760
Eric Laurenteab90452019-06-24 15:17:46 -07004761// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4762// still applied by the mixer.
4763// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4764// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4765// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004766status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004767{
4768 status_t result = NO_ERROR;
4769 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4770 if (*volume != mLeftVolFloat) {
4771 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004772 // HAL can return INVALID_OPERATION if operation is not supported.
4773 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004774 "Error when setting output stream volume: %d", result);
4775 if (result == NO_ERROR) {
4776 mLeftVolFloat = *volume;
4777 }
4778 }
4779 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4780 // remove stream volume contribution from software volume.
4781 if (mLeftVolFloat == *volume) {
4782 *volume = 1.0f;
4783 }
4784 }
4785 return result;
4786}
4787
Andy Hungee58e4a2023-07-07 13:47:37 -07004788status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004789 audio_patch_handle_t *handle)
4790{
Andy Hungf60abce2016-08-26 11:37:54 -07004791 status_t status;
4792 if (property_get_bool("af.patch_park", false /* default_value */)) {
4793 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4794 // or if HAL does not properly lock against access.
4795 AutoPark<FastMixer> park(mFastMixer);
4796 status = PlaybackThread::createAudioPatch_l(patch, handle);
4797 } else {
4798 status = PlaybackThread::createAudioPatch_l(patch, handle);
4799 }
Eric Laurentb0463942022-12-20 16:31:10 +01004800
4801 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004802 return status;
4803}
4804
Andy Hungee58e4a2023-07-07 13:47:37 -07004805status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004806 audio_patch_handle_t *handle)
4807{
4808 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004809
4810 // store new device and send to effects
4811 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004812 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004813 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004814 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4815 && !mOutput->audioHwDev->supportsAudioPatches(),
4816 "Enumerated device type(%#x) must not be used "
4817 "as it does not support audio patches",
4818 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004819 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004820 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4821 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004822 }
4823
François Gaffie0c280aa2018-07-25 10:02:15 +02004824 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004825#ifdef ADD_BATTERY_DATA
4826 // when changing the audio output device, call addBatteryData to notify
4827 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004828 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004829 uint32_t params = 0;
4830 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004831 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004832 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004833 }
4834
Eric Laurent054d9d32015-04-24 08:48:48 -07004835 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004836 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004837 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4838 }
4839
4840 if (params != 0) {
4841 addBatteryData(params);
4842 }
4843 }
4844#endif
4845
4846 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004847 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004848 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004849
jiabinc52b1ff2019-10-31 17:20:42 -07004850 // mPatch.num_sinks is not set when the thread is created so that
4851 // the first patch creation triggers an ioConfigChanged callback
4852 bool configChanged = (mPatch.num_sinks == 0) ||
4853 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004854 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004855 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004856 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004857
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004858 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004859 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4860 status = hwDevice->createAudioPatch(patch->num_sources,
4861 patch->sources,
4862 patch->num_sinks,
4863 patch->sinks,
4864 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004865 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004866 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004867 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004868 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004869 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004870
4871 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004872 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004873 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004874 // also dispatch to active AudioTracks for MediaMetrics
4875 for (const auto &track : mActiveTracks) {
4876 track->logEndInterval();
4877 track->logBeginInterval(patchSinksAsString);
4878 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004879
Eric Laurente8726fe2015-06-26 09:39:24 -07004880 if (configChanged) {
4881 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4882 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004883 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004884 mActiveTracks.setHasChanged();
4885
Eric Laurent1c333e22014-05-20 10:48:17 -07004886 return status;
4887}
4888
Andy Hungee58e4a2023-07-07 13:47:37 -07004889status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004890{
Andy Hungf60abce2016-08-26 11:37:54 -07004891 status_t status;
4892 if (property_get_bool("af.patch_park", false /* default_value */)) {
4893 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4894 // or if HAL does not properly lock against access.
4895 AutoPark<FastMixer> park(mFastMixer);
4896 status = PlaybackThread::releaseAudioPatch_l(handle);
4897 } else {
4898 status = PlaybackThread::releaseAudioPatch_l(handle);
4899 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004900 return status;
4901}
4902
Andy Hungee58e4a2023-07-07 13:47:37 -07004903status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004904{
4905 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004906
jiabinc52b1ff2019-10-31 17:20:42 -07004907 mPatch = audio_patch{};
4908 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004909
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004910 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004911 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4912 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004913 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004914 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004915 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004916 // Force meteadata update after a route change
4917 mActiveTracks.setHasChanged();
4918
Eric Laurent1c333e22014-05-20 10:48:17 -07004919 return status;
4920}
4921
Andy Hungee58e4a2023-07-07 13:47:37 -07004922void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004923{
Andy Hung972bec12023-08-31 16:13:39 -07004924 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004925 mTracks.add(track);
4926}
4927
Andy Hungee58e4a2023-07-07 13:47:37 -07004928void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004929{
Andy Hung972bec12023-08-31 16:13:39 -07004930 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004931 destroyTrack_l(track);
4932}
4933
Andy Hungee58e4a2023-07-07 13:47:37 -07004934void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004935{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004936 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004937 config->role = AUDIO_PORT_ROLE_SOURCE;
4938 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4939 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004940 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4941 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4942 config->flags.output = mOutput->flags;
4943 }
Eric Laurent83b88082014-06-20 18:31:16 -07004944}
4945
Eric Laurent81784c32012-11-19 14:55:58 -08004946// ----------------------------------------------------------------------------
4947
Andy Hungee58e4a2023-07-07 13:47:37 -07004948/* static */
4949sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07004950 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07004951 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07004952 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07004953}
4954
Andy Hung583043b2023-07-17 17:05:00 -07004955MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004956 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07004957 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004958 // mAudioMixer below
4959 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004960 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004961 mFastMixerFutex(0),
4962 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004963 // mOutputSink below
4964 // mPipeSink below
4965 // mNormalSink below
4966{
Andy Hung583043b2023-07-17 17:05:00 -07004967 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004968 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004969 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004970 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004971 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4972 mNormalFrameCount);
4973 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4974
Andy Hungfbfc3952015-01-15 13:33:51 -08004975 if (type == DUPLICATING) {
4976 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4977 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4978 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4979 return;
4980 }
Eric Laurent81784c32012-11-19 14:55:58 -08004981 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004982 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004983 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004984 const NBAIO_Format offers[1] = {Format_from_SR_C(
4985 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004986#if !LOG_NDEBUG
4987 ssize_t index =
4988#else
4989 (void)
4990#endif
4991 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004992 ALOG_ASSERT(index == 0);
4993
4994 // initialize fast mixer depending on configuration
4995 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004996 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004997 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004998 } else {
4999 switch (kUseFastMixer) {
5000 case FastMixer_Never:
5001 initFastMixer = false;
5002 break;
5003 case FastMixer_Always:
5004 initFastMixer = true;
5005 break;
5006 case FastMixer_Static:
5007 case FastMixer_Dynamic:
5008 initFastMixer = mFrameCount < mNormalFrameCount;
5009 break;
5010 }
5011 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5012 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5013 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005014 }
5015 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005016 audio_format_t fastMixerFormat;
5017 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5018 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5019 } else {
5020 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5021 }
5022 if (mFormat != fastMixerFormat) {
5023 // change our Sink format to accept our intermediate precision
5024 mFormat = fastMixerFormat;
5025 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005026 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005027 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5028 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5029 }
Eric Laurent81784c32012-11-19 14:55:58 -08005030
5031 // create a MonoPipe to connect our submix to FastMixer
5032 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005033
Andy Hung1258c1a2014-05-23 21:22:17 -07005034 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005035 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005036 format.mFormat = fastMixerFormat;
5037 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5038
Eric Laurent81784c32012-11-19 14:55:58 -08005039 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5040 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5041 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5042 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005043 const NBAIO_Format offersFast[1] = {format};
5044 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005045#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005046 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005047#else
5048 (void)
5049#endif
Andy Hung920f6572022-10-06 12:09:49 -07005050 monoPipe->negotiate(offersFast, std::size(offersFast),
5051 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005052 ALOG_ASSERT(index == 0);
5053 monoPipe->setAvgFrames((mScreenState & 1) ?
5054 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5055 mPipeSink = monoPipe;
5056
Eric Laurent81784c32012-11-19 14:55:58 -08005057 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005058 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005059 FastMixerStateQueue *sq = mFastMixer->sq();
5060#ifdef STATE_QUEUE_DUMP
5061 sq->setObserverDump(&mStateQueueObserverDump);
5062 sq->setMutatorDump(&mStateQueueMutatorDump);
5063#endif
5064 FastMixerState *state = sq->begin();
5065 FastTrack *fastTrack = &state->mFastTracks[0];
5066 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5067 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5068 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005069 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5070 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5071 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005072 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005073 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005074 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005075 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005076 fastTrack->mGeneration++;
5077 state->mFastTracksGen++;
5078 state->mTrackMask = 1;
5079 // fast mixer will use the HAL output sink
5080 state->mOutputSink = mOutputSink.get();
5081 state->mOutputSinkGen++;
5082 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005083 // specify sink channel mask when haptic channel mask present as it can not
5084 // be calculated directly from channel count
5085 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005086 ? AUDIO_CHANNEL_NONE
5087 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005088 state->mCommand = FastMixerState::COLD_IDLE;
5089 // already done in constructor initialization list
5090 //mFastMixerFutex = 0;
5091 state->mColdFutexAddr = &mFastMixerFutex;
5092 state->mColdGen++;
5093 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005094 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005095 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005096 sq->end();
5097 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5098
Eric Tan0513b5d2018-09-17 10:32:48 -07005099 NBLog::thread_info_t info;
5100 info.id = mId;
5101 info.type = NBLog::FASTMIXER;
5102 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5103
Eric Laurent81784c32012-11-19 14:55:58 -08005104 // start the fast mixer
5105 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5106 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005107 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005108 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005109
5110#ifdef AUDIO_WATCHDOG
5111 // create and start the watchdog
5112 mAudioWatchdog = new AudioWatchdog();
5113 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5114 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5115 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005116 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005117#endif
Andy Hung8946a282018-04-19 20:04:56 -07005118 } else {
5119#ifdef TEE_SINK
5120 // Only use the MixerThread tee if there is no FastMixer.
5121 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5122 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5123#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005124 }
5125
5126 switch (kUseFastMixer) {
5127 case FastMixer_Never:
5128 case FastMixer_Dynamic:
5129 mNormalSink = mOutputSink;
5130 break;
5131 case FastMixer_Always:
5132 mNormalSink = mPipeSink;
5133 break;
5134 case FastMixer_Static:
5135 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5136 break;
5137 }
5138}
5139
Andy Hungee58e4a2023-07-07 13:47:37 -07005140MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005141{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005142 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005143 FastMixerStateQueue *sq = mFastMixer->sq();
5144 FastMixerState *state = sq->begin();
5145 if (state->mCommand == FastMixerState::COLD_IDLE) {
5146 int32_t old = android_atomic_inc(&mFastMixerFutex);
5147 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005148 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005149 }
5150 }
5151 state->mCommand = FastMixerState::EXIT;
5152 sq->end();
5153 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5154 mFastMixer->join();
5155 // Though the fast mixer thread has exited, it's state queue is still valid.
5156 // We'll use that extract the final state which contains one remaining fast track
5157 // corresponding to our sub-mix.
5158 state = sq->begin();
5159 ALOG_ASSERT(state->mTrackMask == 1);
5160 FastTrack *fastTrack = &state->mFastTracks[0];
5161 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5162 delete fastTrack->mBufferProvider;
5163 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005164 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005165#ifdef AUDIO_WATCHDOG
5166 if (mAudioWatchdog != 0) {
5167 mAudioWatchdog->requestExit();
5168 mAudioWatchdog->requestExitAndWait();
5169 mAudioWatchdog.clear();
5170 }
5171#endif
5172 }
Andy Hung583043b2023-07-17 17:05:00 -07005173 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005174 delete mAudioMixer;
5175}
5176
Andy Hungee58e4a2023-07-07 13:47:37 -07005177void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005178 PlaybackThread::onFirstRef();
5179
Andy Hung972bec12023-08-31 16:13:39 -07005180 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005181 if (mOutput != nullptr && mOutput->stream != nullptr) {
5182 status_t status = mOutput->stream->setLatencyModeCallback(this);
5183 if (status != INVALID_OPERATION) {
5184 updateHalSupportedLatencyModes_l();
5185 }
5186 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5187 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5188 mBluetoothLatencyModesEnabled.store(
5189 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5190 }
5191}
Eric Laurent81784c32012-11-19 14:55:58 -08005192
Andy Hungee58e4a2023-07-07 13:47:37 -07005193uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005194{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005195 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005196 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5197 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5198 }
5199 return latency;
5200}
5201
Andy Hungee58e4a2023-07-07 13:47:37 -07005202ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005203{
5204 // FIXME we should only do one push per cycle; confirm this is true
5205 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005206 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005207 FastMixerStateQueue *sq = mFastMixer->sq();
5208 FastMixerState *state = sq->begin();
5209 if (state->mCommand != FastMixerState::MIX_WRITE &&
5210 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5211 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005212
5213 // FIXME workaround for first HAL write being CPU bound on some devices
5214 ATRACE_BEGIN("write");
5215 mOutput->write((char *)mSinkBuffer, 0);
5216 ATRACE_END();
5217
Eric Laurent81784c32012-11-19 14:55:58 -08005218 int32_t old = android_atomic_inc(&mFastMixerFutex);
5219 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005220 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005221 }
5222#ifdef AUDIO_WATCHDOG
5223 if (mAudioWatchdog != 0) {
5224 mAudioWatchdog->resume();
5225 }
5226#endif
5227 }
5228 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005229#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005230 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005231 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005232#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005233 sq->end();
5234 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5235 if (kUseFastMixer == FastMixer_Dynamic) {
5236 mNormalSink = mPipeSink;
5237 }
5238 } else {
5239 sq->end(false /*didModify*/);
5240 }
5241 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005243}
5244
Andy Hungee58e4a2023-07-07 13:47:37 -07005245void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005246{
5247 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005248 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005249 FastMixerStateQueue *sq = mFastMixer->sq();
5250 FastMixerState *state = sq->begin();
5251 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005252 // Report any frames trapped in the Monopipe
5253 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5254 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5255 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5256 "monoPipeWritten:%lld monoPipeLeft:%lld",
5257 (long long)mFramesWritten, (long long)mSuspendedFrames,
5258 (long long)mPipeSink->framesWritten(), pipeFrames);
5259 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5260
Eric Laurent81784c32012-11-19 14:55:58 -08005261 state->mCommand = FastMixerState::COLD_IDLE;
5262 state->mColdFutexAddr = &mFastMixerFutex;
5263 state->mColdGen++;
5264 mFastMixerFutex = 0;
5265 sq->end();
5266 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5267 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5268 if (kUseFastMixer == FastMixer_Dynamic) {
5269 mNormalSink = mOutputSink;
5270 }
5271#ifdef AUDIO_WATCHDOG
5272 if (mAudioWatchdog != 0) {
5273 mAudioWatchdog->pause();
5274 }
5275#endif
5276 } else {
5277 sq->end(false /*didModify*/);
5278 }
5279 }
5280 PlaybackThread::threadLoop_standby();
5281}
5282
Andy Hungee58e4a2023-07-07 13:47:37 -07005283bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005284{
5285 return false;
5286}
5287
Andy Hungee58e4a2023-07-07 13:47:37 -07005288bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005289{
5290 return !mStandby;
5291}
5292
Andy Hungee58e4a2023-07-07 13:47:37 -07005293bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005294{
Andy Hung972bec12023-08-31 16:13:39 -07005295 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005296 return waitingAsyncCallback_l();
5297}
5298
Eric Laurent81784c32012-11-19 14:55:58 -08005299// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005300void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005301{
5302 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005303 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005305 // discard any pending drain or write ack by incrementing sequence
5306 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5307 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005309 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5310 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005312 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005313 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005314}
5315
Andy Hungee58e4a2023-07-07 13:47:37 -07005316void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005317{
5318 ALOGV("signal playback thread");
5319 broadcast_l();
5320}
5321
Andy Hungee58e4a2023-07-07 13:47:37 -07005322void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005323{
5324 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5325 invalidateTracks((audio_stream_type_t)i);
5326 }
5327}
5328
Andy Hungee58e4a2023-07-07 13:47:37 -07005329void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005330{
Eric Laurent81784c32012-11-19 14:55:58 -08005331 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005332 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005333 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005334 // increase sleep time progressively when application underrun condition clears.
5335 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5336 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5337 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005338 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005339 sleepTimeShift--;
5340 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005341 mSleepTimeUs = 0;
5342 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005343 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005344
Eric Laurent81784c32012-11-19 14:55:58 -08005345}
5346
Andy Hungee58e4a2023-07-07 13:47:37 -07005347void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005348{
5349 // If no tracks are ready, sleep once for the duration of an output
5350 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005351 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005352 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005353 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5354 // Using the Monopipe availableToWrite, we estimate the
5355 // sleep time to retry for more data (before we underrun).
5356 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5357 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5358 const size_t pipeFrames = monoPipe->maxFrames();
5359 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5360 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5361 const size_t framesDelay = std::min(
5362 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5363 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5364 pipeFrames, framesLeft, framesDelay);
5365 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5366 } else {
5367 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5368 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5369 mSleepTimeUs = kMinThreadSleepTimeUs;
5370 }
5371 // reduce sleep time in case of consecutive application underruns to avoid
5372 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5373 // duration we would end up writing less data than needed by the audio HAL if
5374 // the condition persists.
5375 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5376 sleepTimeShift++;
5377 }
Eric Laurent81784c32012-11-19 14:55:58 -08005378 }
5379 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005380 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005381 }
5382 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005383 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5384 // before effects processing or output.
5385 if (mMixerBufferValid) {
5386 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005387 if (mType == SPATIALIZER) {
5388 memset(mSinkBuffer, 0, mSinkBufferSize);
5389 }
Andy Hung98ef9782014-03-04 14:46:50 -08005390 } else {
5391 memset(mSinkBuffer, 0, mSinkBufferSize);
5392 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005393 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005394 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5395 "anticipated start");
5396 }
5397 // TODO add standby time extension fct of effect tail
5398}
5399
Andy Hungc5007f82023-08-29 14:26:09 -07005400// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005401PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005402 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005403{
Andy Hungc0691382018-09-12 18:01:57 -07005404 // clean up deleted track ids in AudioMixer before allocating new tracks
5405 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5406 // for each trackId, destroy it in the AudioMixer
5407 if (mAudioMixer->exists(trackId)) {
5408 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005409 }
5410 });
Andy Hungc0691382018-09-12 18:01:57 -07005411 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005412
5413 mixer_state mixerStatus = MIXER_IDLE;
5414 // find out which tracks need to be processed
5415 size_t count = mActiveTracks.size();
5416 size_t mixedTracks = 0;
5417 size_t tracksWithEffect = 0;
5418 // counts only _active_ fast tracks
5419 size_t fastTracks = 0;
5420 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5421
5422 float masterVolume = mMasterVolume;
5423 bool masterMute = mMasterMute;
5424
5425 if (masterMute) {
5426 masterVolume = 0;
5427 }
5428 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005429 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005430 if (chain != 0) {
5431 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5432 chain->setVolume_l(&v, &v);
5433 masterVolume = (float)((v + (1 << 23)) >> 24);
5434 chain.clear();
5435 }
5436
5437 // prepare a new state to push
5438 FastMixerStateQueue *sq = NULL;
5439 FastMixerState *state = NULL;
5440 bool didModify = false;
5441 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005442 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005443 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005444 sq = mFastMixer->sq();
5445 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005446 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005447 }
5448
Andy Hung69aed5f2014-02-25 17:24:40 -08005449 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005450 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005451
Andy Hungbd3b2b02018-05-21 10:53:11 -07005452 // DeferredOperations handles statistics after setting mixerStatus.
5453 class DeferredOperations {
5454 public:
Andy Hungea840382020-05-05 21:50:17 -07005455 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5456 : mMixerStatus(mixerStatus)
5457 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005458
5459 // when leaving scope, tally frames properly.
5460 ~DeferredOperations() {
5461 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5462 // because that is when the underrun occurs.
5463 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005464 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005465 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005466 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005467 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005468 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005469 }
5470 }
Andy Hungea840382020-05-05 21:50:17 -07005471 // send the max underrun frames for this mixer period
5472 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005473 }
5474
5475 // tallyUnderrunFrames() is called to update the track counters
5476 // with the number of underrun frames for a particular mixer period.
5477 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005478 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005479 mUnderrunFrames.emplace_back(track, underrunFrames);
5480 }
5481
5482 private:
5483 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005484 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005485 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005486 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005487 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005488
jiabin245cdd92018-12-07 17:55:15 -08005489 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005490 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005491 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005492
5493 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005494 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005495
5496 // process fast tracks
5497 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005498 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5499 "%s(%d): FastTrack(%d) present without FastMixer",
5500 __func__, id(), track->id());
5501
jiabin245cdd92018-12-07 17:55:15 -08005502 if (track->getHapticPlaybackEnabled()) {
5503 noFastHapticTrack = false;
5504 }
Eric Laurent81784c32012-11-19 14:55:58 -08005505
5506 // It's theoretically possible (though unlikely) for a fast track to be created
5507 // and then removed within the same normal mix cycle. This is not a problem, as
5508 // the track never becomes active so it's fast mixer slot is never touched.
5509 // The converse, of removing an (active) track and then creating a new track
5510 // at the identical fast mixer slot within the same normal mix cycle,
5511 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005512 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005513 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005514 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5515 FastTrack *fastTrack = &state->mFastTracks[j];
5516
5517 // Determine whether the track is currently in underrun condition,
5518 // and whether it had a recent underrun.
5519 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5520 FastTrackUnderruns underruns = ftDump->mUnderruns;
5521 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005522 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005523 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005524 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005525 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005526 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005527 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005528 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005529 // don't count underruns that occur while stopping or pausing
5530 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005531 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005532 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5533 recentUnderruns > 0) {
5534 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005535 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005536 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005537 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005538 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005539
5540 // This is similar to the state machine for normal tracks,
5541 // with a few modifications for fast tracks.
5542 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005543 switch (track->state()) {
5544 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005545 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005546 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005547 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005548 }
5549 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005550 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005551 // ramp down is not yet implemented
5552 track->setPaused();
5553 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005554 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005555 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005556 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005557 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005558 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005559 if (recentFull > 0 || recentPartial > 0) {
5560 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005561 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005562 }
5563 if (recentUnderruns == 0) {
5564 // no recent underruns: stay active
5565 break;
5566 }
5567 // there has recently been an underrun of some kind
5568 if (track->sharedBuffer() == 0) {
5569 // were any of the recent underruns "empty" (no frames available)?
5570 if (recentEmpty == 0) {
5571 // no, then ignore the partial underruns as they are allowed indefinitely
5572 break;
5573 }
5574 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005575 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005576 break;
5577 }
5578 // indicate to client process that the track was disabled because of underrun;
5579 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005580 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005581 // remove from active list, but state remains ACTIVE [confusing but true]
5582 isActive = false;
5583 break;
5584 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005585 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005586 case IAfTrackBase::STOPPING_2:
5587 case IAfTrackBase::PAUSED:
5588 case IAfTrackBase::STOPPED:
5589 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005590 // Check for presentation complete if track is inactive
5591 // We have consumed all the buffers of this track.
5592 // This would be incomplete if we auto-paused on underrun
5593 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005594 uint32_t latency = 0;
5595 status_t result = mOutput->stream->getLatency(&latency);
5596 ALOGE_IF(result != OK,
5597 "Error when retrieving output stream latency: %d", result);
5598 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005599 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005600 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5601 // track stays in active list until presentation is complete
5602 break;
5603 }
5604 }
5605 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005606 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005607 }
5608 if (track->isStopped()) {
5609 // Can't reset directly, as fast mixer is still polling this track
5610 // track->reset();
5611 // So instead mark this track as needing to be reset after push with ack
5612 resetMask |= 1 << i;
5613 }
5614 isActive = false;
5615 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005616 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005617 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005618 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005619 }
5620
5621 if (isActive) {
5622 // was it previously inactive?
5623 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005624 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5625 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005626 fastTrack->mBufferProvider = eabp;
5627 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005628 fastTrack->mChannelMask = track->channelMask();
5629 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005630 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005631 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005632 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005633 fastTrack->mGeneration++;
5634 state->mTrackMask |= 1 << j;
5635 didModify = true;
5636 // no acknowledgement required for newly active tracks
5637 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005638 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005639 float volume;
5640 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5641 volume = 0.f;
5642 } else {
5643 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5644 }
5645
5646 handleVoipVolume_l(&volume);
5647
Eric Laurent81784c32012-11-19 14:55:58 -08005648 // cache the combined master volume and stream type volume for fast mixer; this
5649 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005650 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005651 proxy->framesReleased()).first;
5652 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005653 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005654 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005655 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5656 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5657
Andy Hung583043b2023-07-17 17:05:00 -07005658 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005659 /*muteState=*/{masterVolume == 0.f,
5660 mStreamTypes[track->streamType()].volume == 0.f,
5661 mStreamTypes[track->streamType()].mute,
5662 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005663 vlf == 0.f && vrf == 0.f,
5664 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005665
5666 vlf *= volume;
5667 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005668
jiabin76d94692022-12-15 21:51:21 +00005669 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005670 ++fastTracks;
5671 } else {
5672 // was it previously active?
5673 if (state->mTrackMask & (1 << j)) {
5674 fastTrack->mBufferProvider = NULL;
5675 fastTrack->mGeneration++;
5676 state->mTrackMask &= ~(1 << j);
5677 didModify = true;
5678 // If any fast tracks were removed, we must wait for acknowledgement
5679 // because we're about to decrement the last sp<> on those tracks.
5680 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5681 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005682 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5683 // AudioTrack may start (which may not be with a start() but with a write()
5684 // after underrun) and immediately paused or released. In that case the
5685 // FastTrack state hasn't had time to update.
5686 // TODO Remove the ALOGW when this theory is confirmed.
5687 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005688 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005689 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005690 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005691 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005692 }
5693 tracksToRemove->add(track);
5694 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005695 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005696 }
jiabin245cdd92018-12-07 17:55:15 -08005697 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5698 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5699 didModify = true;
5700 }
Eric Laurent81784c32012-11-19 14:55:58 -08005701 continue;
5702 }
5703
5704 { // local variable scope to avoid goto warning
5705
5706 audio_track_cblk_t* cblk = track->cblk();
5707
5708 // The first time a track is added we wait
5709 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005710 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005711
5712 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005713 // use the trackId as the AudioMixer name.
5714 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005715 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005716 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005717 track->channelMask(),
5718 track->format(),
5719 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005720 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005721 ALOGW("%s(): AudioMixer cannot create track(%d)"
5722 " mask %#x, format %#x, sessionId %d",
5723 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005724 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005725 tracksToRemove->add(track);
5726 track->invalidate(); // consider it dead.
5727 continue;
5728 }
5729 }
5730
Eric Laurent81784c32012-11-19 14:55:58 -08005731 // make sure that we have enough frames to mix one full buffer.
5732 // enforce this condition only once to enable draining the buffer in case the client
5733 // app does not call stop() and relies on underrun to stop:
5734 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5735 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005736 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005737 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5738 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005739
5740 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005741 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005742 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5743 // add frames already consumed but not yet released by the resampler
5744 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005745 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005746
Eric Laurent81784c32012-11-19 14:55:58 -08005747 uint32_t minFrames = 1;
5748 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5749 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005750 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005751 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005752
5753 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005754 if (ATRACE_ENABLED()) {
5755 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005756 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005757 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005758 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005759 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005760 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005761 !track->isPaused() && !track->isTerminated())
5762 {
Andy Hungc0691382018-09-12 18:01:57 -07005763 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005764
5765 mixedTracks++;
5766
Andy Hung69aed5f2014-02-25 17:24:40 -08005767 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5768 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005769 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005770 if (track->mainBuffer() != mSinkBuffer &&
5771 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005772 if (mEffectBufferEnabled) {
5773 mEffectBufferValid = true; // Later can set directly.
5774 }
Eric Laurent81784c32012-11-19 14:55:58 -08005775 chain = getEffectChain_l(track->sessionId());
5776 // Delegate volume control to effect in track effect chain if needed
5777 if (chain != 0) {
5778 tracksWithEffect++;
5779 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005780 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005781 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005782 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005783 }
5784 }
5785
5786
5787 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005788 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005789 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005790 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5791 if (track->state() == IAfTrackBase::RESUMING) {
5792 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005793 // If a new track is paused immediately after start, do not ramp on resume.
5794 if (cblk->mServer != 0) {
5795 param = AudioMixer::RAMP_VOLUME;
5796 }
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
Andy Hungc0691382018-09-12 18:01:57 -07005798 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005799 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005800 // FIXME should not make a decision based on mServer
5801 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005802 // If the track is stopped before the first frame was mixed,
5803 // do not apply ramp
5804 param = AudioMixer::RAMP_VOLUME;
5805 }
5806
5807 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005808 uint32_t vl, vr; // in U8.24 integer format
5809 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005810 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005811 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005812 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005813 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005814 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005815 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005816
Eric Laurenteab90452019-06-24 15:17:46 -07005817 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5818 v = 0;
5819 }
5820
5821 handleVoipVolume_l(&v);
5822
5823 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005824 vl = vr = 0;
5825 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005826 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005827 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005828 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005829 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5830 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005831 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005832 if (vlf > GAIN_FLOAT_UNITY) {
5833 ALOGV("Track left volume out of range: %.3g", vlf);
5834 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005835 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005836 if (vrf > GAIN_FLOAT_UNITY) {
5837 ALOGV("Track right volume out of range: %.3g", vrf);
5838 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005839 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005840
Andy Hung583043b2023-07-17 17:05:00 -07005841 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005842 /*muteState=*/{masterVolume == 0.f,
5843 mStreamTypes[track->streamType()].volume == 0.f,
5844 mStreamTypes[track->streamType()].mute,
5845 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005846 vlf == 0.f && vrf == 0.f,
5847 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005848
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005849 // now apply the master volume and stream type volume and shaper volume
5850 vlf *= v * vh;
5851 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005852 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005853 // then derive vl and vr as U8.24 versions for the effect chain
5854 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5855 vl = (uint32_t) (scaleto8_24 * vlf);
5856 vr = (uint32_t) (scaleto8_24 * vrf);
5857 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005858 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005859 // send level comes from shared memory and so may be corrupt
5860 if (sendLevel > MAX_GAIN_INT) {
5861 ALOGV("Track send level out of range: %04X", sendLevel);
5862 sendLevel = MAX_GAIN_INT;
5863 }
Andy Hung6be49402014-05-30 10:42:03 -07005864 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5865 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005866 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005867
jiabin76d94692022-12-15 21:51:21 +00005868 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005869
Eric Laurent81784c32012-11-19 14:55:58 -08005870 // Delegate volume control to effect in track effect chain if needed
5871 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5872 // Do not ramp volume if volume is controlled by effect
5873 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005874 // Update remaining floating point volume levels
5875 vlf = (float)vl / (1 << 24);
5876 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005877 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005878 } else {
5879 // force no volume ramp when volume controller was just disabled or removed
5880 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005881 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005882 param = AudioMixer::VOLUME;
5883 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005884 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005885 }
5886
Eric Laurent81784c32012-11-19 14:55:58 -08005887 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005888 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005889 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005890
Andy Hungc0691382018-09-12 18:01:57 -07005891 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5892 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5893 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005894 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005895 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005896 AudioMixer::TRACK,
5897 AudioMixer::FORMAT, (void *)track->format());
5898 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005899 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005900 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005901 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005902
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005903 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005904 mAudioMixer->setParameter(
5905 trackId,
5906 AudioMixer::TRACK,
5907 AudioMixer::MIXER_CHANNEL_MASK,
5908 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5909 } else {
5910 mAudioMixer->setParameter(
5911 trackId,
5912 AudioMixer::TRACK,
5913 AudioMixer::MIXER_CHANNEL_MASK,
5914 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5915 }
5916
Glenn Kastene3aa6592012-12-04 12:22:46 -08005917 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005918 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005919 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005920 if (reqSampleRate == 0) {
5921 reqSampleRate = mSampleRate;
5922 } else if (reqSampleRate > maxSampleRate) {
5923 reqSampleRate = maxSampleRate;
5924 }
Eric Laurent81784c32012-11-19 14:55:58 -08005925 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005926 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005927 AudioMixer::RESAMPLE,
5928 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005929 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005930
Andy Hung8edb8dc2015-03-26 19:13:55 -07005931 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005932 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005933 AudioMixer::TIMESTRETCH,
5934 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005935 // cast away constness for this generic API.
5936 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005937
Andy Hung69aed5f2014-02-25 17:24:40 -08005938 /*
5939 * Select the appropriate output buffer for the track.
5940 *
Andy Hung98ef9782014-03-04 14:46:50 -08005941 * Tracks with effects go into their own effects chain buffer
5942 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005943 *
5944 * Other tracks can use mMixerBuffer for higher precision
5945 * channel accumulation. If this buffer is enabled
5946 * (mMixerBufferEnabled true), then selected tracks will accumulate
5947 * into it.
5948 *
5949 */
5950 if (mMixerBufferEnabled
5951 && (track->mainBuffer() == mSinkBuffer
5952 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005953 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005954 mAudioMixer->setParameter(
5955 trackId,
5956 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005957 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005958 mAudioMixer->setParameter(
5959 trackId,
5960 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005961 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005962 } else {
5963 mAudioMixer->setParameter(
5964 trackId,
5965 AudioMixer::TRACK,
5966 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5967 mAudioMixer->setParameter(
5968 trackId,
5969 AudioMixer::TRACK,
5970 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5971 // TODO: override track->mainBuffer()?
5972 mMixerBufferValid = true;
5973 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005974 } else {
5975 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005976 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005977 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005978 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005979 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005980 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005981 AudioMixer::TRACK,
5982 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5983 }
Eric Laurent81784c32012-11-19 14:55:58 -08005984 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005985 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005986 AudioMixer::TRACK,
5987 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005988 mAudioMixer->setParameter(
5989 trackId,
5990 AudioMixer::TRACK,
5991 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005992 mAudioMixer->setParameter(
5993 trackId,
5994 AudioMixer::TRACK,
5995 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07005996 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005997 mAudioMixer->setParameter(
5998 trackId,
5999 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006000 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006001
6002 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006003 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006004
6005 // If one track is ready, set the mixer ready if:
6006 // - the mixer was not ready during previous round OR
6007 // - no other track is not ready
6008 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6009 mixerStatus != MIXER_TRACKS_ENABLED) {
6010 mixerStatus = MIXER_TRACKS_READY;
6011 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006012
6013 // Enable the next few lines to instrument a test for underrun log handling.
6014 // TODO: Remove when we have a better way of testing the underrun log.
6015#if 0
6016 static int i;
6017 if ((++i & 0xf) == 0) {
6018 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6019 }
6020#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006021 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006022 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006023 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006024 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6025 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006026 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006027 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006028 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006029
Eric Laurent81784c32012-11-19 14:55:58 -08006030 // clear effect chain input buffer if an active track underruns to avoid sending
6031 // previous audio buffer again to effects
6032 chain = getEffectChain_l(track->sessionId());
6033 if (chain != 0) {
6034 chain->clearInputBuffer();
6035 }
6036
Andy Hungc0691382018-09-12 18:01:57 -07006037 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006038 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6039 track->isStopped() || track->isPaused()) {
6040 // We have consumed all the buffers of this track.
6041 // Remove it from the list of active tracks.
6042 // TODO: use actual buffer filling status instead of latency when available from
6043 // audio HAL
6044 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006045 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006046 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6047 if (track->isStopped()) {
6048 track->reset();
6049 }
6050 tracksToRemove->add(track);
6051 }
6052 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006053 // No buffers for this track. Give it a few chances to
6054 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006055 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006056 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6057 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006058 tracksToRemove->add(track);
6059 // indicate to client process that the track was disabled because of underrun;
6060 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006061 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006062 // If one track is not ready, mark the mixer also not ready if:
6063 // - the mixer was ready during previous round OR
6064 // - no other track is ready
6065 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6066 mixerStatus != MIXER_TRACKS_READY) {
6067 mixerStatus = MIXER_TRACKS_ENABLED;
6068 }
6069 }
Andy Hungc0691382018-09-12 18:01:57 -07006070 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006071 }
6072
6073 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006074
6075 }
6076
jiabin245cdd92018-12-07 17:55:15 -08006077 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6078 // When there is no fast track playing haptic and FastMixer exists,
6079 // enabling the first FastTrack, which provides mixed data from normal
6080 // tracks, to play haptic data.
6081 FastTrack *fastTrack = &state->mFastTracks[0];
6082 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6083 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6084 didModify = true;
6085 }
6086 }
6087
Eric Laurent81784c32012-11-19 14:55:58 -08006088 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006089 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006090 if (didModify) {
6091 state->mFastTracksGen++;
6092 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6093 if (kUseFastMixer == FastMixer_Dynamic &&
6094 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6095 state->mCommand = FastMixerState::COLD_IDLE;
6096 state->mColdFutexAddr = &mFastMixerFutex;
6097 state->mColdGen++;
6098 mFastMixerFutex = 0;
6099 if (kUseFastMixer == FastMixer_Dynamic) {
6100 mNormalSink = mOutputSink;
6101 }
6102 // If we go into cold idle, need to wait for acknowledgement
6103 // so that fast mixer stops doing I/O.
6104 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6105 pauseAudioWatchdog = true;
6106 }
Eric Laurent81784c32012-11-19 14:55:58 -08006107 }
6108 if (sq != NULL) {
6109 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006110 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6111 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6112 // when bringing the output sink into standby.)
6113 //
6114 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6115 //
6116 // This occurs with BT suspend when we idle the FastMixer with
6117 // active tracks, which may be added or removed.
6118 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006119 }
6120#ifdef AUDIO_WATCHDOG
6121 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6122 mAudioWatchdog->pause();
6123 }
6124#endif
6125
6126 // Now perform the deferred reset on fast tracks that have stopped
6127 while (resetMask != 0) {
6128 size_t i = __builtin_ctz(resetMask);
6129 ALOG_ASSERT(i < count);
6130 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006131 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006132 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6133 track->reset();
6134 }
6135
Andy Hung80d03d22018-04-10 10:32:11 -07006136 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6137 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6138 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6139 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6140 // See also the implementation of destroyTrack_l().
6141 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006142 const int trackId = track->id();
6143 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6144 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006145 }
6146 }
6147
Eric Laurent81784c32012-11-19 14:55:58 -08006148 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006149 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006150
Eric Laurentb3f315a2021-07-13 15:09:05 +02006151 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6152 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006153 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006154 }
6155
6156 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006157 // as long as there are effects we should clear the effects buffer, to avoid
6158 // passing a non-clean buffer to the effect chain
6159 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006160 if (mType == SPATIALIZER) {
6161 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6162 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006163 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006164 // sink or mix buffer must be cleared if all tracks are connected to an
6165 // effect chain as in this case the mixer will not write to the sink or mix buffer
6166 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006167 // always clear sink buffer for spatializer output as the output of the spatializer
6168 // effect will be accumulated into it
6169 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6170 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006171 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006172 if (mMixerBufferValid) {
6173 memset(mMixerBuffer, 0, mMixerBufferSize);
6174 // TODO: In testing, mSinkBuffer below need not be cleared because
6175 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6176 // after mixing.
6177 //
6178 // To enforce this guarantee:
6179 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6180 // (mixedTracks == 0 && fastTracks > 0))
6181 // must imply MIXER_TRACKS_READY.
6182 // Later, we may clear buffers regardless, and skip much of this logic.
6183 }
Andy Hung98ef9782014-03-04 14:46:50 -08006184 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006185 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006186 }
6187
6188 // if any fast tracks, then status is ready
6189 mMixerStatusIgnoringFastTracks = mixerStatus;
6190 if (fastTracks > 0) {
6191 mixerStatus = MIXER_TRACKS_READY;
6192 }
6193 return mixerStatus;
6194}
6195
Andy Hungc5007f82023-08-29 14:26:09 -07006196// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006197uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006198{
6199 uint32_t trackCount = 0;
6200 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006201 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006202 trackCount++;
6203 }
6204 }
6205 return trackCount;
6206}
6207
Andy Hungee58e4a2023-07-07 13:47:37 -07006208bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006209{
Brian Lindahl65e90012022-07-27 18:01:07 +02006210 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6211 // could falsely detect that the frame position has stalled due to underrun because we haven't
6212 // given the Audio HAL enough time to update.
6213 const nsecs_t nowNs = systemTime();
6214 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6215 return mLatchedValue;
6216 }
6217 mPreviousNs = nowNs;
6218 mLatchedValue = false;
6219 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006220 uint64_t position = 0;
6221 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006222 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006223 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006224 if (position != mPreviousPosition) {
6225 mPreviousPosition = position;
6226 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006227 }
6228 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006229 return mLatchedValue;
6230}
6231
Andy Hungee58e4a2023-07-07 13:47:37 -07006232void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006233{
6234 mLatchedValue = true;
6235 mPreviousPosition = 0;
6236 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006237}
6238
Andy Hungc5007f82023-08-29 14:26:09 -07006239// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006240bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006241 audio_channel_mask_t channelMask, audio_format_t format,
6242 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006243{
Andy Hung1bc088a2018-02-09 15:57:31 -08006244 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6245 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006246 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006247 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006248 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006249 ALOGW("%s: invalid format: %#x", __func__, format);
6250 return false;
6251 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006252 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006253 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6254 return false;
6255 }
6256 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006257}
6258
Andy Hungc5007f82023-08-29 14:26:09 -07006259// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006260bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006261 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006262{
Eric Laurent81784c32012-11-19 14:55:58 -08006263 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006264 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006265
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006266 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006267
Eric Laurent10351942014-05-08 18:49:52 -07006268 AudioParameter param = AudioParameter(keyValuePair);
6269 int value;
6270 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6271 reconfig = true;
6272 }
6273 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006274 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006275 status = BAD_VALUE;
6276 } else {
6277 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006278 reconfig = true;
6279 }
Eric Laurent10351942014-05-08 18:49:52 -07006280 }
6281 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006282 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006283 status = BAD_VALUE;
6284 } else {
6285 // no need to save value, since it's constant
6286 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006287 }
Eric Laurent10351942014-05-08 18:49:52 -07006288 }
6289 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6290 // do not accept frame count changes if tracks are open as the track buffer
6291 // size depends on frame count and correct behavior would not be guaranteed
6292 // if frame count is changed after track creation
6293 if (!mTracks.isEmpty()) {
6294 status = INVALID_OPERATION;
6295 } else {
6296 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006297 }
Eric Laurent10351942014-05-08 18:49:52 -07006298 }
6299 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006300 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006301 }
Eric Laurent81784c32012-11-19 14:55:58 -08006302
Eric Laurent10351942014-05-08 18:49:52 -07006303 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006304 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006305 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006306 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6307 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006308 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006309 mThreadMetrics.logEndInterval();
6310 mThreadSnapshot.onEnd();
6311 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006312 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006313 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006314 }
Eric Laurent10351942014-05-08 18:49:52 -07006315 if (status == NO_ERROR && reconfig) {
6316 readOutputParameters_l();
6317 delete mAudioMixer;
6318 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006319 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006320 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006321 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006322 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006323 track->channelMask(),
6324 track->format(),
6325 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006326 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006327 "%s(): AudioMixer cannot create track(%d)"
6328 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006329 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006330 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006331 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006332 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006333 }
Eric Laurent81784c32012-11-19 14:55:58 -08006334 }
6335
Dean Wheatley68918102021-03-19 22:09:19 +11006336 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006337}
6338
6339
Andy Hungee58e4a2023-07-07 13:47:37 -07006340void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006341{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006342 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006343 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006344 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006345 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006346 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6347 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6348 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006349 if (hasFastMixer()) {
6350 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6351
6352 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6353 // while we are dumping it. It may be inconsistent, but it won't mutate!
6354 // This is a large object so we place it on the heap.
6355 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006356 const std::unique_ptr<FastMixerDumpState> copy =
6357 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006358 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006359
6360#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006361 // Similar for state queue
6362 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6363 observerCopy.dump(fd);
6364 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6365 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006366#endif
6367
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006368#ifdef AUDIO_WATCHDOG
6369 if (mAudioWatchdog != 0) {
6370 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6371 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6372 wdCopy.dump(fd);
6373 }
6374#endif
6375
6376 } else {
6377 dprintf(fd, " No FastMixer\n");
6378 }
Eric Laurent90cea102023-05-15 15:08:27 +02006379
6380 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6381 mBluetoothLatencyModesEnabled ? "" : "not ");
6382 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6383 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6384 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006385}
6386
Andy Hungee58e4a2023-07-07 13:47:37 -07006387uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006388{
6389 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6390}
6391
Andy Hungee58e4a2023-07-07 13:47:37 -07006392uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006393{
6394 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6395}
6396
Andy Hungee58e4a2023-07-07 13:47:37 -07006397void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006398{
6399 PlaybackThread::cacheParameters_l();
6400
6401 // FIXME: Relaxed timing because of a certain device that can't meet latency
6402 // Should be reduced to 2x after the vendor fixes the driver issue
6403 // increase threshold again due to low power audio mode. The way this warning
6404 // threshold is calculated and its usefulness should be reconsidered anyway.
6405 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6406}
6407
Andy Hungee58e4a2023-07-07 13:47:37 -07006408void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006409 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006410}
6411
Andy Hungee58e4a2023-07-07 13:47:37 -07006412void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006413 // Only handle latency mode if:
6414 // - mBluetoothLatencyModesEnabled is true
6415 // - the HAL supports latency modes
6416 // - the selected device is Bluetooth LE or A2DP
6417 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6418 return;
6419 }
6420 if (mOutDeviceTypeAddrs.size() != 1
6421 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6422 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6423 return;
6424 }
6425
6426 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6427 if (mSupportedLatencyModes.size() == 1) {
6428 // If the HAL only support one latency mode currently, confirm the choice
6429 latencyMode = mSupportedLatencyModes[0];
6430 } else if (mSupportedLatencyModes.size() > 1) {
6431 // Request low latency if:
6432 // - At least one active track is either:
6433 // - a fast track with gaming usage or
6434 // - a track with acessibility usage
6435 for (const auto& track : mActiveTracks) {
6436 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6437 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6438 latencyMode = AUDIO_LATENCY_MODE_LOW;
6439 break;
6440 }
6441 }
6442 }
6443
6444 if (latencyMode != mSetLatencyMode) {
6445 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6446 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6447 __func__, mId, toString(latencyMode).c_str(), status);
6448 if (status == NO_ERROR) {
6449 mSetLatencyMode = latencyMode;
6450 }
6451 }
6452}
6453
Andy Hungee58e4a2023-07-07 13:47:37 -07006454void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006455
6456 if (mOutput == nullptr || mOutput->stream == nullptr) {
6457 return;
6458 }
6459 std::vector<audio_latency_mode_t> latencyModes;
6460 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6461 if (status != NO_ERROR) {
6462 latencyModes.clear();
6463 }
6464 if (latencyModes != mSupportedLatencyModes) {
6465 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6466 __func__, mId, status, toString(latencyModes).c_str());
6467 mSupportedLatencyModes.swap(latencyModes);
6468 sendHalLatencyModesChangedEvent_l();
6469 }
6470}
6471
Andy Hungee58e4a2023-07-07 13:47:37 -07006472status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006473 std::vector<audio_latency_mode_t>* modes) {
6474 if (modes == nullptr) {
6475 return BAD_VALUE;
6476 }
Andy Hung972bec12023-08-31 16:13:39 -07006477 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006478 *modes = mSupportedLatencyModes;
6479 return NO_ERROR;
6480}
6481
Andy Hungee58e4a2023-07-07 13:47:37 -07006482void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006483 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006484 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006485 if (modes != mSupportedLatencyModes) {
6486 ALOGD("%s: thread(%d) supported latency modes: %s",
6487 __func__, mId, toString(modes).c_str());
6488 mSupportedLatencyModes.swap(modes);
6489 sendHalLatencyModesChangedEvent_l();
6490 }
6491}
6492
Andy Hungee58e4a2023-07-07 13:47:37 -07006493status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006494 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6495 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6496 return INVALID_OPERATION;
6497 }
6498 mBluetoothLatencyModesEnabled.store(enabled);
6499 return NO_ERROR;
6500}
6501
Eric Laurent81784c32012-11-19 14:55:58 -08006502// ----------------------------------------------------------------------------
6503
Andy Hungee58e4a2023-07-07 13:47:37 -07006504/* static */
6505sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006506 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006507 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6508 const audio_offload_info_t& offloadInfo) {
6509 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006510 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006511}
6512
Andy Hung583043b2023-07-17 17:05:00 -07006513DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006514 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6515 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006516 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006517 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006518{
Andy Hung583043b2023-07-17 17:05:00 -07006519 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006520}
6521
Andy Hungee58e4a2023-07-07 13:47:37 -07006522DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006523{
6524}
6525
Andy Hungee58e4a2023-07-07 13:47:37 -07006526void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006527{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006528 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006529 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6530 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6531}
6532
Andy Hungee58e4a2023-07-07 13:47:37 -07006533void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006534{
Andy Hung972bec12023-08-31 16:13:39 -07006535 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006536 if (mMasterBalance != balance) {
6537 mMasterBalance.store(balance);
6538 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6539 broadcast_l();
6540 }
6541}
6542
Andy Hungee58e4a2023-07-07 13:47:37 -07006543void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006544{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006545 float left, right;
6546
Andy Hung333ab962019-05-28 20:23:35 -07006547 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006548 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006549
Andy Hung398ffa22022-12-13 19:19:53 -08006550 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6551 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6552
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006553 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6554 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006555
6556 const int64_t volumeShaperFrames =
6557 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6558 const auto [shaperVolume, shaperActive] =
6559 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006560 mVolumeShaperActive = shaperActive;
6561
Vlad Popae2f5aef2022-07-25 16:00:20 +02006562 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6563 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6564 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6565
6566 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6567
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006568 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006569 left = right = 0;
6570 } else {
6571 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006572 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006573
Glenn Kastenc56f3422014-03-21 17:53:17 -07006574 if (left > GAIN_FLOAT_UNITY) {
6575 left = GAIN_FLOAT_UNITY;
6576 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006577 if (right > GAIN_FLOAT_UNITY) {
6578 right = GAIN_FLOAT_UNITY;
6579 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006580 left *= v;
6581 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006582 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006583 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6584 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6585 right *= mMasterBalanceRight;
6586 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006587 }
6588
Andy Hung583043b2023-07-17 17:05:00 -07006589 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006590 /*muteState=*/{mMasterMute,
6591 mStreamTypes[track->streamType()].volume == 0.f,
6592 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006593 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006594 clientVolumeMute,
6595 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006596
Eric Laurentbfb1b832013-01-07 09:53:42 -08006597 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006598 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006599 if (left != mLeftVolFloat || right != mRightVolFloat) {
6600 mLeftVolFloat = left;
6601 mRightVolFloat = right;
6602
Eric Laurentbfb1b832013-01-07 09:53:42 -08006603 // Delegate volume control to effect in track effect chain if needed
6604 // only one effect chain can be present on DirectOutputThread, so if
6605 // there is one, the track is connected to it
6606 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006607 // if effect chain exists, volume is handled by it.
6608 // Convert volumes from float to 8.24
6609 uint32_t vl = (uint32_t)(left * (1 << 24));
6610 uint32_t vr = (uint32_t)(right * (1 << 24));
6611 // Direct/Offload effect chains set output volume in setVolume_l().
6612 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6613 } else {
6614 // otherwise we directly set the volume.
6615 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006616 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006617 }
6618 }
6619}
6620
Andy Hungee58e4a2023-07-07 13:47:37 -07006621void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006622{
Andy Hung8d31fd22023-06-26 19:20:57 -07006623 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6624 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006625
Eric Laurent0f0631e2015-07-06 18:01:25 -07006626 if (previousTrack != 0 && latestTrack != 0) {
6627 if (mType == DIRECT) {
6628 if (previousTrack.get() != latestTrack.get()) {
6629 mFlushPending = true;
6630 }
6631 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006632 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6633 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006634 mFlushPending = true;
6635 }
6636 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006637 } else if (previousTrack == 0) {
6638 // there could be an old track added back during track transition for direct
6639 // output, so always issues flush to flush data of the previous track if it
6640 // was already destroyed with HAL paused, then flush can resume the playback
6641 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006642 }
6643 PlaybackThread::onAddNewTrack_l();
6644}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006645
Andy Hungee58e4a2023-07-07 13:47:37 -07006646PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006647 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006648)
6649{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006650 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006651 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006652 bool doHwPause = false;
6653 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006654
6655 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006656 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006657 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006658 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006659 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006660 continue;
6661 }
6662
Andy Hung8d31fd22023-06-26 19:20:57 -07006663 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006664#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006665 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006666#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006667 // Only consider last track started for volume and mixer state control.
6668 // In theory an older track could underrun and restart after the new one starts
6669 // but as we only care about the transition phase between two tracks on a
6670 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006671 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006672 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006673
Kuowei Li23666472021-01-20 10:23:25 +08006674 if (track->isPausePending()) {
6675 track->pauseAck();
6676 // It is possible a track might have been flushed or stopped.
6677 // Other operations such as flush pending might occur on the next prepare.
6678 if (track->isPausing()) {
6679 track->setPaused();
6680 }
6681 // Always perform pause, as an immediate flush will change
6682 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006683 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006684 doHwPause = true;
6685 mHwPaused = true;
6686 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006687 } else if (track->isFlushPending()) {
6688 track->flushAck();
6689 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006690 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006691 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006692 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006693 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006694 if (last) {
6695 mLeftVolFloat = mRightVolFloat = -1.0;
6696 if (mHwPaused) {
6697 doHwResume = true;
6698 mHwPaused = false;
6699 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006700 }
6701 }
6702
Eric Laurent81784c32012-11-19 14:55:58 -08006703 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006704 // for all its buffers to be filled before processing it.
6705 // Allow draining the buffer in case the client
6706 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006707 // hence the test on (track->retryCount() > 1).
6708 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006709 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6710 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006711 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006712
6713 // target retry count that we will use is based on the time we wait for retries.
6714 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6715 // the retry threshold is when we accept any size for PCM data. This is slightly
6716 // smaller than the retry count so we can push small bits of data without a glitch.
6717 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006718 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006719 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006720 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006721 minFrames = mNormalFrameCount;
6722 } else {
6723 minFrames = 1;
6724 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006725
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006726 const size_t framesReady = track->framesReady();
6727 const int trackId = track->id();
6728 if (ATRACE_ENABLED()) {
6729 std::string traceName("nRdy");
6730 traceName += std::to_string(trackId);
6731 ATRACE_INT(traceName.c_str(), framesReady);
6732 }
6733 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006734 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006735 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006736 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006737
Andy Hung8d31fd22023-06-26 19:20:57 -07006738 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6739 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006740 if (last) {
6741 // make sure processVolume_l() will apply new volume even if 0
6742 mLeftVolFloat = mRightVolFloat = -1.0;
6743 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006744 if (!mHwSupportsPause) {
6745 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006746 }
6747 }
6748
6749 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006750 processVolume_l(track, last);
6751 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006752 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006753 if (previousTrack != 0) {
6754 if (track != previousTrack.get()) {
6755 // Flush any data still being written from last track
6756 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006757 // Invalidate previous track to force a seek when resuming.
6758 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006759 }
6760 }
6761 mPreviousTrack = track;
6762
Eric Laurentd595b7c2013-04-03 17:27:56 -07006763 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006764 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006765 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006766 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006767 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006768 doHwResume = true;
6769 mHwPaused = false;
6770 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006771 }
Eric Laurent81784c32012-11-19 14:55:58 -08006772 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006773 // clear effect chain input buffer if the last active track started underruns
6774 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006775 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006776 mEffectChains[0]->clearInputBuffer();
6777 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006778 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006779 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006780 if (last && mHwPaused) {
6781 doHwResume = true;
6782 mHwPaused = false;
6783 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006784 }
6785 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6786 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006787 // We have consumed all the buffers of this track.
6788 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006789 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006790 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006791 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006792 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006793 if (presComplete) {
6794 mOutput->presentationComplete();
6795 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006796 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006797 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006798 }
Eric Laurent81784c32012-11-19 14:55:58 -08006799 if (track->isStopped()) {
6800 track->reset();
6801 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006802 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006803 }
6804 } else {
6805 // No buffers for this track. Give it a few chances to
6806 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006807 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006808 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006809 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006810 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006811 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006812 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006813 } else {
6814 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6815 tracksToRemove->add(track);
6816 // indicate to client process that the track was disabled because of
6817 // underrun; it will then automatically call start() when data is available
6818 track->disable();
6819 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6820 // unlike mixerthread, HAL can be paused for direct output
6821 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6822 "minFrames = %u, mFormat = %#x",
6823 framesReady, minFrames, mFormat);
6824 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6825 doHwPause = true;
6826 mHwPaused = true;
6827 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006828 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006829 } else if (last) {
6830 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006831 }
6832 }
6833 }
6834 }
6835
Eric Laurentd1f69b02014-12-15 14:33:13 -08006836 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006837 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006838 for (size_t i = 0; i < mTracks.size(); i++) {
6839 if (mTracks[i]->isFlushPending()) {
6840 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006841 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006842 }
6843 }
6844 }
6845
6846 // make sure the pause/flush/resume sequence is executed in the right order.
6847 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6848 // before flush and then resume HW. This can happen in case of pause/flush/resume
6849 // if resume is received before pause is executed.
6850 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006851 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006852 status_t result = mOutput->stream->pause();
6853 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006854 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006855 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006856 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006857 flushHw_l();
6858 }
6859 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006860 status_t result = mOutput->stream->resume();
6861 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006862 }
Eric Laurent81784c32012-11-19 14:55:58 -08006863 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006864 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006865
6866 return mixerStatus;
6867}
6868
Andy Hungee58e4a2023-07-07 13:47:37 -07006869void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006870{
Eric Laurent81784c32012-11-19 14:55:58 -08006871 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006872 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006873 // output audio to hardware
6874 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006875 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006876 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006877 status_t status = mActiveTrack->getNextBuffer(&buffer);
6878 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006879 // no need to pad with 0 for compressed audio
6880 if (audio_has_proportional_frames(mFormat)) {
6881 memset(curBuf, 0, frameCount * mFrameSize);
6882 }
Eric Laurent81784c32012-11-19 14:55:58 -08006883 break;
6884 }
6885 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6886 frameCount -= buffer.frameCount;
6887 curBuf += buffer.frameCount * mFrameSize;
6888 mActiveTrack->releaseBuffer(&buffer);
6889 }
Andy Hung2098f272014-02-27 14:00:06 -08006890 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006891 mSleepTimeUs = 0;
6892 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006893 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006894}
6895
Andy Hungee58e4a2023-07-07 13:47:37 -07006896void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006897{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006898 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006899 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006900 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006901 return;
6902 }
Andy Hung85ba3332021-04-27 17:40:26 -07006903 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6904 mSleepTimeUs = mActiveSleepTimeUs;
6905 } else {
6906 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006907 }
Andy Hung85ba3332021-04-27 17:40:26 -07006908 // Note: In S or later, we do not write zeroes for
6909 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006910}
6911
Andy Hungee58e4a2023-07-07 13:47:37 -07006912void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006913{
6914 {
Andy Hung972bec12023-08-31 16:13:39 -07006915 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006916 for (size_t i = 0; i < mTracks.size(); i++) {
6917 if (mTracks[i]->isFlushPending()) {
6918 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006919 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006920 }
6921 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006922 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006923 flushHw_l();
6924 }
6925 }
6926 PlaybackThread::threadLoop_exit();
6927}
6928
6929// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07006930bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006931{
6932 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006933 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006934
6935 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6936 // after a timeout and we will enter standby then.
6937 if (mTracks.size() > 0) {
6938 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006939 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07006940 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006941 }
6942
Eric Laurent5cff4032015-05-26 13:49:58 -07006943 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006944}
6945
Andy Hungc5007f82023-08-29 14:26:09 -07006946// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006947bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006948 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006949{
6950 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006951 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006952
Eric Laurent10351942014-05-08 18:49:52 -07006953 AudioParameter param = AudioParameter(keyValuePair);
6954 int value;
6955 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006956 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006957 }
Eric Laurent10351942014-05-08 18:49:52 -07006958 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6959 // do not accept frame count changes if tracks are open as the track buffer
6960 // size depends on frame count and correct behavior would not be garantied
6961 // if frame count is changed after track creation
6962 if (!mTracks.isEmpty()) {
6963 status = INVALID_OPERATION;
6964 } else {
6965 reconfig = true;
6966 }
6967 }
6968 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006969 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006970 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006971 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006972 if (!mStandby) {
6973 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006974 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006975 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006976 }
Eric Laurent10351942014-05-08 18:49:52 -07006977 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006978 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006979 }
6980 if (status == NO_ERROR && reconfig) {
6981 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006982 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006983 }
6984 }
6985
Dean Wheatley68918102021-03-19 22:09:19 +11006986 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006987}
6988
Andy Hungee58e4a2023-07-07 13:47:37 -07006989uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006990{
6991 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006992 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006993 time = PlaybackThread::activeSleepTimeUs();
6994 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006995 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006996 }
6997 return time;
6998}
6999
Andy Hungee58e4a2023-07-07 13:47:37 -07007000uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007001{
7002 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007003 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007004 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7005 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007006 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007007 }
7008 return time;
7009}
7010
Andy Hungee58e4a2023-07-07 13:47:37 -07007011uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007012{
7013 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007014 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007015 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7016 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007017 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007018 }
7019 return time;
7020}
7021
Andy Hungee58e4a2023-07-07 13:47:37 -07007022void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007023{
7024 PlaybackThread::cacheParameters_l();
7025
7026 // use shorter standby delay as on normal output to release
7027 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007028 // no delay on outputs with HW A/V sync
7029 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007030 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007031 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007032 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007033 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007034 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007035 }
Eric Laurent81784c32012-11-19 14:55:58 -08007036}
7037
Andy Hungee58e4a2023-07-07 13:47:37 -07007038void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007039{
ziyangch8f194f12021-12-01 13:48:04 -08007040 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007041 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007042 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007043 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007044 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007045 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007046 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007047}
7048
Andy Hungee58e4a2023-07-07 13:47:37 -07007049int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007050 // If a VolumeShaper is active, we must wake up periodically to update volume.
7051 const int64_t NS_PER_MS = 1000000;
7052 return mVolumeShaperActive ?
7053 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7054}
7055
Eric Laurent81784c32012-11-19 14:55:58 -08007056// ----------------------------------------------------------------------------
7057
Andy Hungee58e4a2023-07-07 13:47:37 -07007058AsyncCallbackThread::AsyncCallbackThread(
7059 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007060 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007061 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007062 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007063 mDrainSequence(0),
7064 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007065{
7066}
7067
Andy Hungee58e4a2023-07-07 13:47:37 -07007068void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007069{
7070 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7071}
7072
Andy Hungee58e4a2023-07-07 13:47:37 -07007073bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007074{
7075 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007076 uint32_t writeAckSequence;
7077 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007078 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079
7080 {
Andy Hungc5007f82023-08-29 14:26:09 -07007081 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007082 while (!((mWriteAckSequence & 1) ||
7083 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007084 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007085 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007086 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007087 }
7088
Eric Laurentbfb1b832013-01-07 09:53:42 -08007089 if (exitPending()) {
7090 break;
7091 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007092 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7093 mWriteAckSequence, mDrainSequence);
7094 writeAckSequence = mWriteAckSequence;
7095 mWriteAckSequence &= ~1;
7096 drainSequence = mDrainSequence;
7097 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007098 asyncError = mAsyncError;
7099 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007100 }
7101 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007102 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007103 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007104 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007105 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007106 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007107 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007108 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007109 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007110 if (asyncError) {
7111 playbackThread->onAsyncError();
7112 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007113 }
7114 }
7115 }
7116 return false;
7117}
7118
Andy Hungee58e4a2023-07-07 13:47:37 -07007119void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007120{
7121 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007122 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007123 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007124 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007125}
7126
Andy Hungee58e4a2023-07-07 13:47:37 -07007127void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007128{
Andy Hung972bec12023-08-31 16:13:39 -07007129 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007130 // bit 0 is cleared
7131 mWriteAckSequence = sequence << 1;
7132}
7133
Andy Hungee58e4a2023-07-07 13:47:37 -07007134void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007135{
Andy Hung972bec12023-08-31 16:13:39 -07007136 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007137 // ignore unexpected callbacks
7138 if (mWriteAckSequence & 2) {
7139 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007140 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007141 }
7142}
7143
Andy Hungee58e4a2023-07-07 13:47:37 -07007144void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007145{
Andy Hung972bec12023-08-31 16:13:39 -07007146 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007147 // bit 0 is cleared
7148 mDrainSequence = sequence << 1;
7149}
7150
Andy Hungee58e4a2023-07-07 13:47:37 -07007151void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007152{
Andy Hung972bec12023-08-31 16:13:39 -07007153 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007154 // ignore unexpected callbacks
7155 if (mDrainSequence & 2) {
7156 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007157 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007158 }
7159}
7160
Andy Hungee58e4a2023-07-07 13:47:37 -07007161void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007162{
Andy Hung972bec12023-08-31 16:13:39 -07007163 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007164 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007165 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007166}
7167
Eric Laurentbfb1b832013-01-07 09:53:42 -08007168
7169// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007170
7171/* static */
7172sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007173 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007174 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7175 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007176 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007177}
7178
Andy Hung583043b2023-07-17 17:05:00 -07007179OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007180 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7181 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007182 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007183 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007184{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007185 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007186 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007187 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007188}
7189
Andy Hungee58e4a2023-07-07 13:47:37 -07007190void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007191{
7192 if (mFlushPending || mHwPaused) {
7193 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007194 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007195 flushHw_l();
7196 } else {
7197 mMixerStatus = MIXER_DRAIN_ALL;
7198 threadLoop_drain();
7199 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007200 if (mUseAsyncWrite) {
7201 ALOG_ASSERT(mCallbackThread != 0);
7202 mCallbackThread->exit();
7203 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007204 PlaybackThread::threadLoop_exit();
7205}
7206
Andy Hungee58e4a2023-07-07 13:47:37 -07007207PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007208 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007209)
7210{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007211 size_t count = mActiveTracks.size();
7212
7213 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007214 bool doHwPause = false;
7215 bool doHwResume = false;
7216
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007217 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007218
Eric Laurentbfb1b832013-01-07 09:53:42 -08007219 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007220 for (const sp<IAfTrack>& t : mActiveTracks) {
7221 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007222#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007223 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007224#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007225 // Only consider last track started for volume and mixer state control.
7226 // In theory an older track could underrun and restart after the new one starts
7227 // but as we only care about the transition phase between two tracks on a
7228 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007229 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007230 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007231
Haynes Mathew George7844f672014-01-15 12:32:55 -08007232 if (track->isInvalid()) {
7233 ALOGW("An invalidated track shouldn't be in active list");
7234 tracksToRemove->add(track);
7235 continue;
7236 }
7237
Andy Hung8d31fd22023-06-26 19:20:57 -07007238 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007239 ALOGW("An idle track shouldn't be in active list");
7240 continue;
7241 }
7242
Kuowei Li23666472021-01-20 10:23:25 +08007243 if (track->isPausePending()) {
7244 track->pauseAck();
7245 // It is possible a track might have been flushed or stopped.
7246 // Other operations such as flush pending might occur on the next prepare.
7247 if (track->isPausing()) {
7248 track->setPaused();
7249 }
7250 // Always perform pause if last, as an immediate flush will change
7251 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007252 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007253 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007254 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007255 mHwPaused = true;
7256 }
7257 // If we were part way through writing the mixbuffer to
7258 // the HAL we must save this until we resume
7259 // BUG - this will be wrong if a different track is made active,
7260 // in that case we want to discard the pending data in the
7261 // mixbuffer and tell the client to present it again when the
7262 // track is resumed
7263 mPausedWriteLength = mCurrentWriteLength;
7264 mPausedBytesRemaining = mBytesRemaining;
7265 mBytesRemaining = 0; // stop writing
7266 }
7267 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007268 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007269 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007270 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007271 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007272 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007273 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007274 track->flushAck();
7275 if (last) {
7276 mFlushPending = true;
7277 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007278 } else if (track->isResumePending()){
7279 track->resumeAck();
7280 if (last) {
7281 if (mPausedBytesRemaining) {
7282 // Need to continue write that was interrupted
7283 mCurrentWriteLength = mPausedWriteLength;
7284 mBytesRemaining = mPausedBytesRemaining;
7285 mPausedBytesRemaining = 0;
7286 }
7287 if (mHwPaused) {
7288 doHwResume = true;
7289 mHwPaused = false;
7290 // threadLoop_mix() will handle the case that we need to
7291 // resume an interrupted write
7292 }
7293 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007294 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007295
Eric Laurent3df841a2016-07-15 15:15:40 -07007296 mLeftVolFloat = mRightVolFloat = -1.0;
7297
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007298 // Do not handle new data in this iteration even if track->framesReady()
7299 mixerStatus = MIXER_TRACKS_ENABLED;
7300 }
7301 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007302 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007303 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007304 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7305 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007306 if (last) {
7307 // make sure processVolume_l() will apply new volume even if 0
7308 mLeftVolFloat = mRightVolFloat = -1.0;
7309 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007310 }
7311
7312 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007313 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007314 if (previousTrack != 0) {
7315 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007316 // Flush any data still being written from last track
7317 mBytesRemaining = 0;
7318 if (mPausedBytesRemaining) {
7319 // Last track was paused so we also need to flush saved
7320 // mixbuffer state and invalidate track so that it will
7321 // re-submit that unwritten data when it is next resumed
7322 mPausedBytesRemaining = 0;
7323 // Invalidate is a bit drastic - would be more efficient
7324 // to have a flag to tell client that some of the
7325 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007326 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007327 }
7328 // flush data already sent to the DSP if changing audio session as audio
7329 // comes from a different source. Also invalidate previous track to force a
7330 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007331 if (previousTrack->sessionId() != track->sessionId()) {
7332 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007333 }
7334 }
7335 }
7336 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007337 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007338 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007339 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007340 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007341 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007342 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007343 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007344 mixerStatus = MIXER_TRACKS_READY;
7345 }
7346 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007347 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007349 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007350 // Hardware buffer can hold a large amount of audio so we must
7351 // wait for all current track's data to drain before we say
7352 // that the track is stopped.
7353 if (mBytesRemaining == 0) {
7354 // Only start draining when all data in mixbuffer
7355 // has been written
7356 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007357 track->setState(IAfTrackBase::STOPPING_2);
7358 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007359 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7360 if (last && !mStandby) {
7361 // do not modify drain sequence if we are already draining. This happens
7362 // when resuming from pause after drain.
7363 if ((mDrainSequence & 1) == 0) {
7364 mSleepTimeUs = 0;
7365 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7366 mixerStatus = MIXER_DRAIN_TRACK;
7367 mDrainSequence += 2;
7368 }
7369 if (mHwPaused) {
7370 // It is possible to move from PAUSED to STOPPING_1 without
7371 // a resume so we must ensure hardware is running
7372 doHwResume = true;
7373 mHwPaused = false;
7374 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007375 }
7376 }
Eric Laurente93cc032016-05-05 10:15:10 -07007377 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007378 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007379 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007380 }
7381 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007382 // Drain has completed or we are in standby, signal presentation complete
7383 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007384 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007385 mOutput->presentationComplete();
7386 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007387 track->reset();
7388 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007389 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007390 if (!mUseAsyncWrite) {
7391 // If we don't get explicit drain notification we must
7392 // register discontinuity regardless of whether this is
7393 // the previous (!last) or the upcoming (last) track
7394 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007395 mTimestampVerifier.discontinuity(
7396 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007398 }
7399 } else {
7400 // No buffers for this track. Give it a few chances to
7401 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007402 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007403 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007404 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007405 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007406 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007407 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007408 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7409 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007410 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007411 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007412 // it will then automatically call start() when data is available
7413 track->disable();
7414 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007415 } else if (last){
7416 mixerStatus = MIXER_TRACKS_ENABLED;
7417 }
7418 }
7419 }
7420 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007421 if (track->isReady()) { // check ready to prevent premature start.
7422 processVolume_l(track, last);
7423 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007424 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007425
Eric Laurentea0fade2013-10-04 16:23:48 -07007426 // make sure the pause/flush/resume sequence is executed in the right order.
7427 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7428 // before flush and then resume HW. This can happen in case of pause/flush/resume
7429 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007430 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007431 status_t result = mOutput->stream->pause();
7432 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007433 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007434 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007435 if (mFlushPending) {
7436 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007437 }
Eric Laurentfd477972013-10-25 18:10:40 -07007438 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007439 status_t result = mOutput->stream->resume();
7440 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007441 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007442
Eric Laurentbfb1b832013-01-07 09:53:42 -08007443 // remove all the tracks that need to be...
7444 removeTracks_l(*tracksToRemove);
7445
7446 return mixerStatus;
7447}
7448
Eric Laurentbfb1b832013-01-07 09:53:42 -08007449// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007450bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007451{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007452 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7453 mWriteAckSequence, mDrainSequence);
7454 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007455 return true;
7456 }
7457 return false;
7458}
7459
Andy Hungee58e4a2023-07-07 13:47:37 -07007460bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007461{
Andy Hung972bec12023-08-31 16:13:39 -07007462 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007463 return waitingAsyncCallback_l();
7464}
7465
Andy Hungee58e4a2023-07-07 13:47:37 -07007466void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007467{
Eric Laurente659ef42014-09-29 13:06:46 -07007468 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007469 // Flush anything still waiting in the mixbuffer
7470 mCurrentWriteLength = 0;
7471 mBytesRemaining = 0;
7472 mPausedWriteLength = 0;
7473 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007474 // reset bytes written count to reflect that DSP buffers are empty after flush.
7475 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007476
Eric Laurentbfb1b832013-01-07 09:53:42 -08007477 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007478 // discard any pending drain or write ack by incrementing sequence
7479 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7480 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007481 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007482 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7483 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007484 }
7485}
7486
Andy Hungee58e4a2023-07-07 13:47:37 -07007487void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007488{
Andy Hung972bec12023-08-31 16:13:39 -07007489 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007490 if (PlaybackThread::invalidateTracks_l(streamType)) {
7491 mFlushPending = true;
7492 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007493}
7494
Andy Hungee58e4a2023-07-07 13:47:37 -07007495void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007496 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007497 if (PlaybackThread::invalidateTracks_l(portIds)) {
7498 mFlushPending = true;
7499 }
7500}
7501
Eric Laurentbfb1b832013-01-07 09:53:42 -08007502// ----------------------------------------------------------------------------
7503
Andy Hungee58e4a2023-07-07 13:47:37 -07007504/* static */
7505sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007506 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007507 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007508 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007509}
7510
Andy Hung583043b2023-07-17 17:05:00 -07007511DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007512 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007513 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007514 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007515 mWaitTimeMs(UINT_MAX)
7516{
7517 addOutputTrack(mainThread);
7518}
7519
Andy Hungee58e4a2023-07-07 13:47:37 -07007520DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007521{
7522 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7523 mOutputTracks[i]->destroy();
7524 }
7525}
7526
Andy Hungee58e4a2023-07-07 13:47:37 -07007527void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007528{
7529 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007530 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007531 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007532 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007533 if (mMixerBufferValid) {
7534 memset(mMixerBuffer, 0, mMixerBufferSize);
7535 } else {
7536 memset(mSinkBuffer, 0, mSinkBufferSize);
7537 }
Eric Laurent81784c32012-11-19 14:55:58 -08007538 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007539 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007540 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007541 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007542 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007543}
7544
Andy Hungee58e4a2023-07-07 13:47:37 -07007545void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007546{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007547 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007548 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007549 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007550 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007551 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007552 }
7553 } else if (mBytesWritten != 0) {
7554 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7555 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007556 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007557 } else {
7558 // flush remaining overflow buffers in output tracks
7559 writeFrames = 0;
7560 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007561 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007562 }
7563}
7564
Andy Hungee58e4a2023-07-07 13:47:37 -07007565ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007566{
7567 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007568 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7569
7570 // Consider the first OutputTrack for timestamp and frame counting.
7571
7572 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7573 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7574 // we always claim success.
7575 if (i == 0) {
7576 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7577 ALOGD_IF(correction != 0 && writeFrames != 0,
7578 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7579 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7580 mFramesWritten -= correction;
7581 }
7582
7583 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007584 }
Andy Hungcf10d742020-04-28 15:38:24 -07007585 if (mStandby) {
7586 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007587 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007588 mStandby = false;
7589 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007590 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007591}
7592
Andy Hungee58e4a2023-07-07 13:47:37 -07007593void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007594{
7595 // DuplicatingThread implements standby by stopping all tracks
7596 for (size_t i = 0; i < outputTracks.size(); i++) {
7597 outputTracks[i]->stop();
7598 }
7599}
7600
Andy Hungee58e4a2023-07-07 13:47:37 -07007601void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007602{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007603 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007604
7605 std::stringstream ss;
7606 const size_t numTracks = mOutputTracks.size();
7607 ss << " " << numTracks << " OutputTracks";
7608 if (numTracks > 0) {
7609 ss << ":";
7610 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007611 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007612 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007613 if (thread.get() != nullptr) {
7614 ss << thread.get() << ", " << thread->id();
7615 } else {
7616 ss << "null";
7617 }
7618 ss << ")";
7619 }
7620 }
7621 ss << "\n";
7622 std::string result = ss.str();
7623 write(fd, result.c_str(), result.size());
7624}
7625
Andy Hungee58e4a2023-07-07 13:47:37 -07007626void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007627{
7628 outputTracks = mOutputTracks;
7629}
7630
Andy Hungee58e4a2023-07-07 13:47:37 -07007631void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007632{
7633 outputTracks.clear();
7634}
7635
Andy Hungee58e4a2023-07-07 13:47:37 -07007636void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007637{
Andy Hung972bec12023-08-31 16:13:39 -07007638 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007639 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7640 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7641 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7642 const size_t frameCount =
7643 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7644 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7645 // from different OutputTracks and their associated MixerThreads (e.g. one may
7646 // nearly empty and the other may be dropping data).
7647
Svet Ganov33761132021-05-13 22:51:08 +00007648 // TODO b/182392769: use attribution source util, move to server edge
7649 AttributionSourceState attributionSource = AttributionSourceState();
7650 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007651 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007652 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007653 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007654 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007655 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007656 this,
7657 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007658 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007659 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007660 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007661 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007662 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7663 if (status != NO_ERROR) {
7664 ALOGE("addOutputTrack() initCheck failed %d", status);
7665 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007666 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007667 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7668 mOutputTracks.add(outputTrack);
7669 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7670 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007671}
7672
Andy Hungee58e4a2023-07-07 13:47:37 -07007673void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007674{
Andy Hung972bec12023-08-31 16:13:39 -07007675 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007676 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7677 if (mOutputTracks[i]->thread() == thread) {
7678 mOutputTracks[i]->destroy();
7679 mOutputTracks.removeAt(i);
7680 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007681 if (thread->getOutput() == mOutput) {
7682 mOutput = NULL;
7683 }
Eric Laurent81784c32012-11-19 14:55:58 -08007684 return;
7685 }
7686 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007687 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007688}
7689
Andy Hungc5007f82023-08-29 14:26:09 -07007690// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007691void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007692{
7693 mWaitTimeMs = UINT_MAX;
7694 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007695 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007696 if (strong != 0) {
7697 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7698 if (waitTimeMs < mWaitTimeMs) {
7699 mWaitTimeMs = waitTimeMs;
7700 }
7701 }
7702 }
7703}
7704
Andy Hungee58e4a2023-07-07 13:47:37 -07007705bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007706{
7707 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007708 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007709 if (thread == 0) {
7710 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7711 outputTracks[i].get());
7712 return false;
7713 }
Andy Hung87c693c2023-07-06 20:56:16 -07007714 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007715 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007716 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007717 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7718 thread.get());
7719 return false;
7720 }
7721 }
7722 return true;
7723}
7724
Andy Hungee58e4a2023-07-07 13:47:37 -07007725void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007726 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007727{
Kevin Rocard12381092018-04-11 09:19:59 -07007728 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7729 outputTrack->setMetadatas(metadata.tracks);
7730 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007731}
7732
Andy Hungee58e4a2023-07-07 13:47:37 -07007733uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007734{
7735 return (mWaitTimeMs * 1000) / 2;
7736}
7737
Andy Hungee58e4a2023-07-07 13:47:37 -07007738void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007739{
7740 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7741 updateWaitTime_l();
7742
7743 MixerThread::cacheParameters_l();
7744}
7745
Eric Laurentb3f315a2021-07-13 15:09:05 +02007746// ----------------------------------------------------------------------------
7747
Andy Hungee58e4a2023-07-07 13:47:37 -07007748/* static */
7749sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007750 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007751 AudioStreamOut* output,
7752 audio_io_handle_t id,
7753 bool systemReady,
7754 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007755 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007756}
7757
Andy Hung583043b2023-07-17 17:05:00 -07007758SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007759 AudioStreamOut* output,
7760 audio_io_handle_t id,
7761 bool systemReady,
7762 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007763 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007764{
7765}
7766
Andy Hungee58e4a2023-07-07 13:47:37 -07007767void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007768 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007769
Andy Hung41ccf7f2022-12-14 14:25:49 -08007770 const pid_t tid = getTid();
7771 if (tid == -1) {
7772 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7773 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7774 } else {
7775 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7776 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007777 stream()->setHalThreadPriority(priorityBoost);
7778 }
7779 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007780}
7781
Andy Hungee58e4a2023-07-07 13:47:37 -07007782void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007783 // if mSupportedLatencyModes is empty, the HAL stream does not support
7784 // latency mode control and we can exit.
7785 if (mSupportedLatencyModes.empty()) {
7786 return;
7787 }
7788 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7789 if (mSupportedLatencyModes.size() == 1) {
7790 // If the HAL only support one latency mode currently, confirm the choice
7791 latencyMode = mSupportedLatencyModes[0];
7792 } else if (mSupportedLatencyModes.size() > 1) {
7793 // Request low latency if:
7794 // - The low latency mode is requested by the spatializer controller
7795 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7796 // AND
7797 // - At least one active track is spatialized
7798 bool hasSpatializedActiveTrack = false;
7799 for (const auto& track : mActiveTracks) {
7800 if (track->isSpatialized()) {
7801 hasSpatializedActiveTrack = true;
7802 break;
7803 }
7804 }
7805 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7806 latencyMode = AUDIO_LATENCY_MODE_LOW;
7807 }
7808 }
7809
7810 if (latencyMode != mSetLatencyMode) {
7811 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007812 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7813 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007814 if (status == NO_ERROR) {
7815 mSetLatencyMode = latencyMode;
7816 }
7817 }
7818}
7819
Andy Hungee58e4a2023-07-07 13:47:37 -07007820status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007821 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7822 return BAD_VALUE;
7823 }
Andy Hung972bec12023-08-31 16:13:39 -07007824 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007825 mRequestedLatencyMode = mode;
7826 return NO_ERROR;
7827}
7828
Andy Hungee58e4a2023-07-07 13:47:37 -07007829void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007830NO_THREAD_SAFETY_ANALYSIS
7831// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007832{
7833 bool hasVirtualizer = false;
7834 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007835 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007836 {
Andy Hung972bec12023-08-31 16:13:39 -07007837 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007838 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007839 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007840 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007841 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7842 }
7843
7844 finalDownMixer = mFinalDownMixer;
7845 mFinalDownMixer.clear();
7846 }
7847
7848 if (hasVirtualizer) {
7849 if (finalDownMixer != nullptr) {
7850 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007851 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007852 }
7853 finalDownMixer.clear();
7854 } else if (!hasDownMixer) {
7855 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007856 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007857 EFFECT_UIID_DOWNMIX, &descriptors);
7858 if (status != NO_ERROR) {
7859 return;
7860 }
7861 ALOG_ASSERT(!descriptors.empty(),
7862 "%s getDescriptors() returned no error but empty list", __func__);
7863
7864 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7865 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007866 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007867
7868 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7869 ALOGW("%s error creating downmixer %d", __func__, status);
7870 finalDownMixer.clear();
7871 } else {
7872 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007873 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007874 }
7875 }
7876
7877 {
Andy Hung972bec12023-08-31 16:13:39 -07007878 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007879 mFinalDownMixer = finalDownMixer;
7880 }
7881}
7882
Eric Laurent81784c32012-11-19 14:55:58 -08007883// ----------------------------------------------------------------------------
7884// Record
7885// ----------------------------------------------------------------------------
7886
Andy Hung583043b2023-07-17 17:05:00 -07007887sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007888 AudioStreamIn* input,
7889 audio_io_handle_t id,
7890 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007891 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007892}
7893
Andy Hung583043b2023-07-17 17:05:00 -07007894RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007895 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007896 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007897 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007898 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007899 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007900 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007901 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007902 mActiveTracks(&this->mLocalLog),
7903 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007904 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007905 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007906 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7907 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007908 // mFastCapture below
7909 , mFastCaptureFutex(0)
7910 // mInputSource
7911 // mPipeSink
7912 // mPipeSource
7913 , mPipeFramesP2(0)
7914 // mPipeMemory
7915 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007916 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007917 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007918{
Glenn Kastend7dca052015-03-05 16:05:54 -08007919 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07007920 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007921
George Burgess IVa8f90c12020-05-14 11:27:19 -07007922 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007923 mIsMsdDevice = strcmp(
7924 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7925 }
7926
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007927 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007928
Andy Hungc8fddf32018-08-08 18:32:37 -07007929 // TODO: We may also match on address as well as device type for
7930 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007931 // TODO: This property should be ensure that only contains one single device type.
7932 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7933 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007934 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7935 : AUDIO_DEVICE_NONE));
7936
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007937 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007938 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007939 size_t numCounterOffers = 0;
7940 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007941#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007942 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007943#else
7944 (void)
7945#endif
7946 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007947 ALOG_ASSERT(index == 0);
7948
7949 // initialize fast capture depending on configuration
7950 bool initFastCapture;
7951 switch (kUseFastCapture) {
7952 case FastCapture_Never:
7953 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007954 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007955 break;
7956 case FastCapture_Always:
7957 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007958 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007959 break;
7960 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007961 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7962 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7963 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7964 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7965 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007966 break;
7967 // case FastCapture_Dynamic:
7968 }
7969
7970 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007971 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007972 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007973 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7974 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007975 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007976 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007977 const sp<MemoryDealer> roHeap(readOnlyHeap());
7978 sp<IMemory> pipeMemory;
7979 if ((roHeap == 0) ||
7980 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007981 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007982 ALOGE("not enough memory for pipe buffer size=%zu; "
7983 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7984 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7985 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007986 goto failed;
7987 }
7988 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7989 memset(pipeBuffer, 0, pipeSize);
7990 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007991 const NBAIO_Format offersFast[1] = {format};
7992 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007993 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007994 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007995 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007996 mPipeSink = pipe;
7997 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007998 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007999 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008000 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008001 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008002 mPipeSource = pipeReader;
8003 mPipeFramesP2 = pipeFramesP2;
8004 mPipeMemory = pipeMemory;
8005
8006 // create fast capture
8007 mFastCapture = new FastCapture();
8008 FastCaptureStateQueue *sq = mFastCapture->sq();
8009#ifdef STATE_QUEUE_DUMP
8010 // FIXME
8011#endif
8012 FastCaptureState *state = sq->begin();
8013 state->mCblk = NULL;
8014 state->mInputSource = mInputSource.get();
8015 state->mInputSourceGen++;
8016 state->mPipeSink = pipe;
8017 state->mPipeSinkGen++;
8018 state->mFrameCount = mFrameCount;
8019 state->mCommand = FastCaptureState::COLD_IDLE;
8020 // already done in constructor initialization list
8021 //mFastCaptureFutex = 0;
8022 state->mColdFutexAddr = &mFastCaptureFutex;
8023 state->mColdGen++;
8024 state->mDumpState = &mFastCaptureDumpState;
8025#ifdef TEE_SINK
8026 // FIXME
8027#endif
Andy Hung583043b2023-07-17 17:05:00 -07008028 mFastCaptureNBLogWriter =
8029 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008030 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8031 sq->end();
8032 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8033
8034 // start the fast capture
8035 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8036 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008037 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008038 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008039#ifdef AUDIO_WATCHDOG
8040 // FIXME
8041#endif
8042
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008043 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008044 }
Andy Hung8946a282018-04-19 20:04:56 -07008045#ifdef TEE_SINK
8046 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8047 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8048#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008049failed: ;
8050
8051 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008052}
8053
Andy Hungee58e4a2023-07-07 13:47:37 -07008054RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008055{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008056 if (mFastCapture != 0) {
8057 FastCaptureStateQueue *sq = mFastCapture->sq();
8058 FastCaptureState *state = sq->begin();
8059 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8060 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8061 if (old == -1) {
8062 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8063 }
8064 }
8065 state->mCommand = FastCaptureState::EXIT;
8066 sq->end();
8067 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8068 mFastCapture->join();
8069 mFastCapture.clear();
8070 }
Andy Hung583043b2023-07-17 17:05:00 -07008071 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8072 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008073 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008074}
8075
Andy Hungee58e4a2023-07-07 13:47:37 -07008076void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008077{
Glenn Kastend7dca052015-03-05 16:05:54 -08008078 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008079}
8080
Andy Hungee58e4a2023-07-07 13:47:37 -07008081void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008082{
8083 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008084 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008085 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008086 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008087 track->invalidate();
8088 }
8089 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008090 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008091}
8092
Andy Hungee58e4a2023-07-07 13:47:37 -07008093bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008094{
Eric Laurent81784c32012-11-19 14:55:58 -08008095 nsecs_t lastWarning = 0;
8096
8097 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008098
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008099reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008100 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008101 {
Andy Hung972bec12023-08-31 16:13:39 -07008102 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008103 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008104 }
8105
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008106 // used to request a deferred sleep, to be executed later while mutex is unlocked
8107 uint32_t sleepUs = 0;
8108
Andy Hung446f4df2019-02-21 12:26:41 -08008109 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8110
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008111 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008112 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008113 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008114
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008115 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008116 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008117
Glenn Kasten735f45f2014-08-18 15:51:59 -07008118 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008119 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008120
Glenn Kasten735f45f2014-08-18 15:51:59 -07008121 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008122 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008123
Eric Laurent33403f02020-05-29 18:35:06 -07008124 bool silenceFastCapture = false;
8125
Andy Hungc5007f82023-08-29 14:26:09 -07008126 { // scope for mutex()
8127 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008128
Eric Laurent021cf962014-05-13 10:18:14 -07008129 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008130
Eric Laurent000a4192014-01-29 15:17:32 -08008131 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008132 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008133 if (exitPending()) {
8134 break;
8135 }
8136
Eric Laurent5c25d562016-07-13 17:17:45 -07008137 // sleep with mutex unlocked
8138 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008139 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008140 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008141 ATRACE_END();
8142 sleepUs = 0;
8143 continue;
8144 }
8145
Glenn Kasten2b806402013-11-20 16:37:38 -08008146 // if no active track(s), then standby and release wakelock
8147 size_t size = mActiveTracks.size();
8148 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008149 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008150 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008151 releaseWakeLock_l();
8152 ALOGV("RecordThread: loop stopping");
8153 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008154 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008155 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008156 goto reacquire_wakelock;
8157 }
8158
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008159 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008160 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008161 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008162
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008163 activeTrack = mActiveTracks[i];
8164 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008165 if (activeTrack->isFastTrack()) {
8166 ALOG_ASSERT(fastTrackToRemove == 0);
8167 fastTrackToRemove = activeTrack;
8168 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008169 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008170 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008171 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008172 continue;
8173 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008174
Andy Hung8d31fd22023-06-26 19:20:57 -07008175 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008176 switch (activeTrackState) {
8177
Andy Hung8d31fd22023-06-26 19:20:57 -07008178 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008179 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008180 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008181 doBroadcast = true;
8182 size--;
8183 continue;
8184
Andy Hung8d31fd22023-06-26 19:20:57 -07008185 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008186 sleepUs = 10000;
8187 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008188 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008189 continue;
8190
Andy Hung8d31fd22023-06-26 19:20:57 -07008191 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008192 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008193 if (mStandby) {
8194 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008195 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008196 mStandby = false;
8197 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008198 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008199 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008200 break;
8201
Andy Hung8d31fd22023-06-26 19:20:57 -07008202 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008203 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008204 break;
8205
Andy Hung8d31fd22023-06-26 19:20:57 -07008206 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8207 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8208 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008209 default:
Andy Hungce685402018-10-05 17:23:27 -07008210 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8211 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008212 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008213
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008214 if (activeTrack->isFastTrack()) {
8215 ALOG_ASSERT(!mFastTrackAvail);
8216 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008217 // if the active fast track is silenced either:
8218 // 1) silence the whole capture from fast capture buffer if this is
8219 // the only active track
8220 // 2) invalidate this track: this will cause the client to reconnect and possibly
8221 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008222 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008223 if (activeTrack->isSilenced()) {
8224 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008225 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008226 } else {
8227 silenceFastCapture = true;
8228 }
8229 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008230 // Invalidate fast tracks if access to audio history is required as this is not
8231 // possible with fast tracks. Once the fast track has been invalidated, no new
8232 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8233 if (mMaxSharedAudioHistoryMs != 0) {
8234 invalidate = true;
8235 }
8236 if (invalidate) {
8237 activeTrack->invalidate();
8238 ALOG_ASSERT(fastTrackToRemove == 0);
8239 fastTrackToRemove = activeTrack;
8240 removeTrack_l(activeTrack);
8241 mActiveTracks.remove(activeTrack);
8242 size--;
8243 continue;
8244 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008245 fastTrack = activeTrack;
8246 }
Eric Laurent33403f02020-05-29 18:35:06 -07008247
8248 activeTracks.add(activeTrack);
8249 i++;
8250
Glenn Kasten9e982352013-08-14 14:39:50 -07008251 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008252
Andy Hungab65b182023-09-06 19:41:47 -07008253 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008254
Kevin Rocard069c2712018-03-29 19:09:14 -07008255 updateMetadata_l();
8256
Eric Laurent5c25d562016-07-13 17:17:45 -07008257 if (allStopped) {
8258 standbyIfNotAlreadyInStandby();
8259 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008260 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008261 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008262 }
8263
8264 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008265 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008266 if (sleepUs == 0) {
8267 sleepUs = kRecordThreadSleepUs;
8268 }
8269 continue;
8270 }
8271 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008272
Eric Laurent81784c32012-11-19 14:55:58 -08008273 lockEffectChains_l(effectChains);
8274 }
8275
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008276 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008277
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008278 size_t size = effectChains.size();
8279 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008280 // thread mutex is not locked, but effect chain is locked
8281 effectChains[i]->process_l();
8282 }
8283
Glenn Kasten735f45f2014-08-18 15:51:59 -07008284 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008285 if (mFastCapture != 0) {
8286 FastCaptureStateQueue *sq = mFastCapture->sq();
8287 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008288 bool didModify = false;
8289 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008290 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8291 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8292 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8293 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8294 if (old == -1) {
8295 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8296 }
8297 }
8298 state->mCommand = FastCaptureState::READ_WRITE;
8299#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008300 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008301 FastThreadDumpState::kSamplingNforLowRamDevice :
8302 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008303#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008304 didModify = true;
8305 }
8306 audio_track_cblk_t *cblkOld = state->mCblk;
8307 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8308 if (cblkNew != cblkOld) {
8309 state->mCblk = cblkNew;
8310 // block until acked if removing a fast track
8311 if (cblkOld != NULL) {
8312 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8313 }
8314 didModify = true;
8315 }
jiabin01c8f562018-07-19 17:47:28 -07008316 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8317 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8318 if (state->mFastPatchRecordBufferProvider != abp) {
8319 state->mFastPatchRecordBufferProvider = abp;
8320 state->mFastPatchRecordFormat = fastTrack == 0 ?
8321 AUDIO_FORMAT_INVALID : fastTrack->format();
8322 didModify = true;
8323 }
Eric Laurent33403f02020-05-29 18:35:06 -07008324 if (state->mSilenceCapture != silenceFastCapture) {
8325 state->mSilenceCapture = silenceFastCapture;
8326 didModify = true;
8327 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008328 sq->end(didModify);
8329 if (didModify) {
8330 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008331#if 0
8332 if (kUseFastCapture == FastCapture_Dynamic) {
8333 mNormalSource = mPipeSource;
8334 }
8335#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008336 }
8337 }
8338
Glenn Kasten735f45f2014-08-18 15:51:59 -07008339 // now run the fast track destructor with thread mutex unlocked
8340 fastTrackToRemove.clear();
8341
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008342 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8343 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8344 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8345 // If destination is non-contiguous, first read past the nominal end of buffer, then
8346 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008347
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008348 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008349 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008350 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008351
8352 // If an NBAIO source is present, use it to read the normal capture's data
8353 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008354 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008355
8356 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8357 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8358 // we immediately retry the read() to get data and prevent another overflow.
8359 for (int retries = 0; retries <= 2; ++retries) {
8360 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8361 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8362 framesToRead);
8363 if (framesRead != OVERRUN) break;
8364 }
8365
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008366 const ssize_t availableToRead = mPipeSource->availableToRead();
8367 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008368 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008369 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008370 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8371 "more frames to read than fifo size, %zd > %zu",
8372 availableToRead, mPipeFramesP2);
8373 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8374 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8375 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8376 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008377 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8378 }
8379 if (framesRead < 0) {
8380 status_t status = (status_t) framesRead;
8381 switch (status) {
8382 case OVERRUN:
8383 ALOGW("overrun on read from pipe");
8384 framesRead = 0;
8385 break;
8386 case NEGOTIATE:
8387 ALOGE("re-negotiation is needed");
8388 framesRead = -1; // Will cause an attempt to recover.
8389 break;
8390 default:
8391 ALOGE("unknown error %d on read from pipe", status);
8392 break;
8393 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008394 }
8395 // otherwise use the HAL / AudioStreamIn directly
8396 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008397 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008398 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008399 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008400 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008401 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008402 if (result < 0) {
8403 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008404 } else {
8405 framesRead = bytesRead / mFrameSize;
8406 }
8407 }
8408
Andy Hung446f4df2019-02-21 12:26:41 -08008409 const int64_t lastIoEndNs = systemTime(); // end IO timing
8410
Andy Hung3f0c9022016-01-15 17:49:46 -08008411 // Update server timestamp with server stats
8412 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008413 if (framesRead >= 0) {
8414 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8415 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8416 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008417
8418 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008419 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008420 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008421 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008422 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8423 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8424 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008425 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008426 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8427
8428 mTimestampVerifier.add(position, time, mSampleRate);
8429
8430 // Correct timestamps
Andy Hungab65b182023-09-06 19:41:47 -07008431 bool timestampCorrectionEnabled = false;
8432 {
8433 audio_utils::lock_guard l(mutex());
8434 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
8435 }
8436 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008437 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008438 id(), (long long)time, (long long)position);
8439 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8440 position = correctedTimestamp.mFrames;
8441 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008442 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008443 id(), (long long)time, (long long)position);
8444 }
8445
Andy Hung3f0c9022016-01-15 17:49:46 -08008446 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8447 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8448 // Note: In general record buffers should tend to be empty in
8449 // a properly running pipeline.
8450 //
8451 // Also, it is not advantageous to call get_presentation_position during the read
8452 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008453 } else {
8454 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008455 }
8456 }
Andy Hunge6c37112019-02-26 17:38:10 -08008457
8458 // From the timestamp, input read latency is negative output write latency.
8459 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008460 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008461 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8462 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8463 mLatencyMs.add(latencyMs);
8464 }
8465
Andy Hung3f0c9022016-01-15 17:49:46 -08008466 // Use this to track timestamp information
8467 // ALOGD("%s", mTimestamp.toString().c_str());
8468
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008469 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008470 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471 // Force input into standby so that it tries to recover at next read attempt
8472 inputStandBy();
8473 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008474 }
8475 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008476 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008477 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008478 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008479 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008480
Andy Hung8946a282018-04-19 20:04:56 -07008481#ifdef TEE_SINK
8482 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8483#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008484 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008485 {
8486 size_t part1 = mRsmpInFramesP2 - rear;
8487 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008488 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008489 (framesRead - part1) * mFrameSize);
8490 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008491 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008492 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008493
8494 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008495
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008496 // loop over each active track
8497 for (size_t i = 0; i < size; i++) {
8498 activeTrack = activeTracks[i];
8499
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008500 // skip fast tracks, as those are handled directly by FastCapture
8501 if (activeTrack->isFastTrack()) {
8502 continue;
8503 }
8504
Andy Hung73c02e42015-03-29 01:13:58 -07008505 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008506 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8507
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008508 enum {
8509 OVERRUN_UNKNOWN,
8510 OVERRUN_TRUE,
8511 OVERRUN_FALSE
8512 } overrun = OVERRUN_UNKNOWN;
8513
8514 // loop over getNextBuffer to handle circular sink
8515 for (;;) {
8516
Andy Hung8d31fd22023-06-26 19:20:57 -07008517 activeTrack->sinkBuffer().frameCount = ~0;
8518 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8519 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008520 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8521
Andy Hung73c02e42015-03-29 01:13:58 -07008522 // check available frames and handle overrun conditions
8523 // if the record track isn't draining fast enough.
8524 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008525 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008526 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008527 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008528 overrun = OVERRUN_TRUE;
8529 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008530 if (framesOut == 0 || framesIn == 0) {
8531 break;
8532 }
8533
Andy Hung6770c6f2015-04-07 13:43:36 -07008534 // Don't allow framesOut to be larger than what is possible with resampling
8535 // from framesIn.
8536 // This isn't strictly necessary but helps limit buffer resizing in
8537 // RecordBufferConverter. TODO: remove when no longer needed.
8538 framesOut = min(framesOut,
8539 destinationFramesPossible(
Andy Hung8d31fd22023-06-26 19:20:57 -07008540 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008541
8542 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008543 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008544 // straight from RecordThread buffer to RecordTrack buffer.
8545 AudioBufferProvider::Buffer buffer;
8546 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008547 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008548 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008549 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008550 ALOGV_IF(buffer.frameCount != framesOut,
8551 "%s() read less than expected (%zu vs %zu)",
8552 __func__, buffer.frameCount, framesOut);
8553 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008554 memcpy(activeTrack->sinkBuffer().raw,
8555 buffer.raw, buffer.frameCount * mFrameSize);
8556 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008557 } else {
8558 framesOut = 0;
8559 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008560 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008561 }
8562 } else {
8563 // process frames from the RecordThread buffer provider to the RecordTrack
8564 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008565 framesOut = activeTrack->recordBufferConverter()->convert(
8566 activeTrack->sinkBuffer().raw,
8567 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008568 framesOut);
8569 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008570
8571 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8572 overrun = OVERRUN_FALSE;
8573 }
8574
Andy Hung93bb5732023-05-04 21:16:34 -07008575 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8576 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008577 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008578 if (framesToDrop == 0) {
8579 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008580 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008581 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008582 // Sanitize before releasing if the track has no access to the source data
8583 // An idle UID receives silence from non virtual devices until active
8584 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008585 memset(activeTrack->sinkBuffer().raw,
8586 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008587 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008588 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008589 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008590 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008591 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008592 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008593 }
8594 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008595
8596 switch (overrun) {
8597 case OVERRUN_TRUE:
8598 // client isn't retrieving buffers fast enough
8599 if (!activeTrack->setOverflow()) {
8600 nsecs_t now = systemTime();
8601 // FIXME should lastWarning per track?
8602 if ((now - lastWarning) > kWarningThrottleNs) {
8603 ALOGW("RecordThread: buffer overflow");
8604 lastWarning = now;
8605 }
8606 }
8607 break;
8608 case OVERRUN_FALSE:
8609 activeTrack->clearOverflow();
8610 break;
8611 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008612 break;
8613 }
8614
Andy Hung3f0c9022016-01-15 17:49:46 -08008615 // update frame information and push timestamp out
8616 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008617 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008618 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8619 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008620 }
8621
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008622unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008623 // enable changes in effect chain
8624 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008625 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008626 if (audio_has_proportional_frames(mFormat)
8627 && loopCount == lastLoopCountRead + 1) {
8628 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8629 const double jitterMs =
8630 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8631 {framesRead, readPeriodNs},
8632 {0, 0} /* lastTimestamp */, mSampleRate);
8633 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8634
Andy Hung972bec12023-08-31 16:13:39 -07008635 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008636 mIoJitterMs.add(jitterMs);
8637 mProcessTimeMs.add(processMs);
8638 }
8639 // update timing info.
8640 mLastIoBeginNs = lastIoBeginNs;
8641 mLastIoEndNs = lastIoEndNs;
8642 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008643 }
8644
Glenn Kasten93e471f2013-08-19 08:40:07 -07008645 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008646
8647 {
Andy Hung972bec12023-08-31 16:13:39 -07008648 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008649 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008650 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008651 track->invalidate();
8652 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008653 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008654 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008655 }
8656
8657 releaseWakeLock();
8658
8659 ALOGV("RecordThread %p exiting", this);
8660 return false;
8661}
8662
Andy Hungee58e4a2023-07-07 13:47:37 -07008663void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008664{
8665 if (!mStandby) {
8666 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008667 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008668 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008669 mStandby = true;
8670 }
8671}
8672
Andy Hungee58e4a2023-07-07 13:47:37 -07008673void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008674{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008675 // Idle the fast capture if it's currently running
8676 if (mFastCapture != 0) {
8677 FastCaptureStateQueue *sq = mFastCapture->sq();
8678 FastCaptureState *state = sq->begin();
8679 if (!(state->mCommand & FastCaptureState::IDLE)) {
8680 state->mCommand = FastCaptureState::COLD_IDLE;
8681 state->mColdFutexAddr = &mFastCaptureFutex;
8682 state->mColdGen++;
8683 mFastCaptureFutex = 0;
8684 sq->end();
8685 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8686 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8687#if 0
8688 if (kUseFastCapture == FastCapture_Dynamic) {
8689 // FIXME
8690 }
8691#endif
8692#ifdef AUDIO_WATCHDOG
8693 // FIXME
8694#endif
8695 } else {
8696 sq->end(false /*didModify*/);
8697 }
8698 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008699 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008700 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008701
8702 // If going into standby, flush the pipe source.
8703 if (mPipeSource.get() != nullptr) {
8704 const ssize_t flushed = mPipeSource->flush();
8705 if (flushed > 0) {
8706 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8707 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8708 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8709 }
8710 }
Eric Laurent81784c32012-11-19 14:55:58 -08008711}
8712
Andy Hungc5007f82023-08-29 14:26:09 -07008713// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008714sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008715 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008716 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008717 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008718 audio_format_t format,
8719 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008720 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008721 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008722 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008723 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008724 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008725 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008726 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008727 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008728 audio_port_handle_t portId,
8729 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008730{
Glenn Kasten74935e42013-12-19 08:56:45 -08008731 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008732 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008733 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008734 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008735 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008736 audio_input_flags_t requestedFlags = *flags;
8737 uint32_t sampleRate;
8738
8739 lStatus = initCheck();
8740 if (lStatus != NO_ERROR) {
8741 ALOGE("createRecordTrack_l() audio driver not initialized");
8742 goto Exit;
8743 }
8744
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008745 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8746 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8747 lStatus = BAD_VALUE;
8748 goto Exit;
8749 }
8750
Eric Laurentec376dc2021-04-08 20:41:22 +02008751 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008752 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008753 lStatus = PERMISSION_DENIED;
8754 goto Exit;
8755 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008756 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008757 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008758 lStatus = BAD_VALUE;
8759 goto Exit;
8760 }
8761 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008762 if (*pSampleRate == 0) {
8763 *pSampleRate = mSampleRate;
8764 }
8765 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008766
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008767 // special case for FAST flag considered OK if fast capture is present and access to
8768 // audio history is not required
8769 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008770 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8771 }
8772
Eric Laurentf14db3c2017-12-08 14:20:36 -08008773 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008774 if ((*flags & inputFlags) != *flags) {
8775 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8776 " input flags (%08x)",
8777 *flags, inputFlags);
8778 *flags = (audio_input_flags_t)(*flags & inputFlags);
8779 }
Eric Laurent81784c32012-11-19 14:55:58 -08008780
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008781 // client expresses a preference for FAST and no access to audio history,
8782 // but we get the final say
8783 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008784 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008785 // we formerly checked for a callback handler (non-0 tid),
8786 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008787 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008788 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008789 // Frame count is not specified (0), or is less than or equal the pipe depth.
8790 // It is OK to provide a higher capacity than requested.
8791 // We will force it to mPipeFramesP2 below.
8792 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008793 // PCM data
8794 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008795 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008796 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008797 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008798 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008799 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008800 hasFastCapture() &&
8801 // there are sufficient fast track slots available
8802 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008803 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008804 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008805 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008806 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008807 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008808 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008809 audio_input_flags_t old = *flags;
8810 chain->checkInputFlagCompatibility(flags);
8811 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008812 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8813 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008814 }
8815 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008816 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008817 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8818 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008819 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008820 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8821 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008822 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008823 this, frameCount, mFrameCount, mPipeFramesP2,
8824 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008825 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008826 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008827 }
8828 }
8829
Eric Laurentf14db3c2017-12-08 14:20:36 -08008830 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8831 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8832 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8833 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8834 lStatus = BAD_TYPE;
8835 goto Exit;
8836 }
8837
Glenn Kasten74105912014-07-03 12:28:53 -07008838 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008839 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008840 // fast track: frame count is exactly the pipe depth
8841 frameCount = mPipeFramesP2;
8842 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008843 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008844 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008845 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8846 // or 20 ms if there is a fast capture
8847 // TODO This could be a roundupRatio inline, and const
8848 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8849 * sampleRate + mSampleRate - 1) / mSampleRate;
8850 // minimum number of notification periods is at least kMinNotifications,
8851 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8852 static const size_t kMinNotifications = 3;
8853 static const uint32_t kMinMs = 30;
8854 // TODO This could be a roundupRatio inline
8855 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8856 // TODO This could be a roundupRatio inline
8857 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8858 maxNotificationFrames;
8859 const size_t minFrameCount = maxNotificationFrames *
8860 max(kMinNotifications, minNotificationsByMs);
8861 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008862 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8863 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008864 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008865 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008866 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008867 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008868
Andy Hungc5007f82023-08-29 14:26:09 -07008869 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07008870 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008871 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008872 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008873 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008874 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008875 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008876 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008877 }
Eric Laurent81784c32012-11-19 14:55:58 -08008878
Andy Hung8d31fd22023-06-26 19:20:57 -07008879 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008880 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008881 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008882 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008883 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008884
Glenn Kasten03003332013-08-06 15:40:54 -07008885 lStatus = track->initCheck();
8886 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008887 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008888 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008889 goto Exit;
8890 }
8891 mTracks.add(track);
8892
Eric Laurent05067782016-06-01 18:27:28 -07008893 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008894 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8895 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8896 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008897 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008898 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008899
8900 if (maxSharedAudioHistoryMs != 0) {
8901 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8902 }
Eric Laurent81784c32012-11-19 14:55:58 -08008903 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008904
Eric Laurent81784c32012-11-19 14:55:58 -08008905 lStatus = NO_ERROR;
8906
8907Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008908 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008909 return track;
8910}
8911
Andy Hungee58e4a2023-07-07 13:47:37 -07008912status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008913 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008914 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008915{
8916 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8917 sp<ThreadBase> strongMe = this;
8918 status_t status = NO_ERROR;
8919
8920 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008921 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008922 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008923 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07008924 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008925 event, triggerSession,
8926 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008927 }
8928
8929 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008930 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07008931 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07008932 if (recordTrack->isInvalid()) {
8933 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008934 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8935 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008936 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008937 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008938 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008939 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8940 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008941 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07008942 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008943 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07008944 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008945 }
8946 return status;
8947 }
8948
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008949 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8950 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8951 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07008952 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008953 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008954 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07008955 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008956 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07008957 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07008958 if (recordTrack->isInvalid()) {
8959 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07008960 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8961 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008962 // STARTING_2 forces destroy to call stopInput.
8963 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008964 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8965 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008966 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008967 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008968 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07008969 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008970 // Someone else has changed state, let them take over,
8971 // leave mState in the new state.
8972 recordTrack->clearSyncStartEvent();
8973 return INVALID_OPERATION;
8974 }
8975 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008976 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008977 ALOGW("%s(%d): startInput failed, status %d",
8978 __func__, recordTrack->id(), status);
8979 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8980 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008981 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008982 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008983 return status;
8984 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008985 sendIoConfigEvent_l(
8986 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008987 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008988
8989 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8990
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008991 // Catch up with current buffer indices if thread is already running.
8992 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8993 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8994 // see previously buffered data before it called start(), but with greater risk of overrun.
8995
Andy Hung8d31fd22023-06-26 19:20:57 -07008996 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008997 if (!recordTrack->isDirect()) {
8998 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07008999 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009000 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009001 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009002 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009003 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009004 return status;
9005 }
Eric Laurent81784c32012-11-19 14:55:58 -08009006}
9007
Andy Hungee58e4a2023-07-07 13:47:37 -07009008void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009009{
Andy Hungee58e4a2023-07-07 13:47:37 -07009010 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009011
9012 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009013 sp<IAfTrackBase> ptr =
9014 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9015 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009016 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009017 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009018 }
Eric Laurent81784c32012-11-19 14:55:58 -08009019 }
9020}
9021
Andy Hungee58e4a2023-07-07 13:47:37 -07009022bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009023 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009024 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009025 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009026 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009027 return false;
9028 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009029 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009030 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009031
Andy Hungabfab202019-03-07 19:45:54 -08009032 // NOTE: Waiting here is important to keep stop synchronous.
9033 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009034 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009035 mWaitWorkCV.notify_all(); // signal thread to stop
9036 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009037 }
Andy Hungce685402018-10-05 17:23:27 -07009038
Andy Hung8d31fd22023-06-26 19:20:57 -07009039 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009040 ALOGV("Record stopped OK");
9041 return true;
9042 }
Andy Hungce685402018-10-05 17:23:27 -07009043
9044 // don't handle anything - we've been invalidated or restarted and in a different state
9045 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009046 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009047 return false;
9048}
9049
Andy Hungee58e4a2023-07-07 13:47:37 -07009050bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009051{
9052 return false;
9053}
9054
Andy Hungee58e4a2023-07-07 13:47:37 -07009055status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009056{
9057#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9058 if (!isValidSyncEvent(event)) {
9059 return BAD_VALUE;
9060 }
9061
Glenn Kastend848eb42016-03-08 13:42:11 -08009062 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009063 status_t ret = NAME_NOT_FOUND;
9064
Andy Hung972bec12023-08-31 16:13:39 -07009065 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009066
9067 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009068 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009069 if (eventSession == track->sessionId()) {
9070 (void) track->setSyncEvent(event);
9071 ret = NO_ERROR;
9072 }
9073 }
9074 return ret;
9075#else
9076 return BAD_VALUE;
9077#endif
9078}
9079
Andy Hungee58e4a2023-07-07 13:47:37 -07009080status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009081 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009082{
9083 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009084 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009085 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009086 return NO_INIT;
9087 }
jiabin9ff780e2018-03-19 18:19:52 -07009088 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9089 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009090}
9091
Andy Hungee58e4a2023-07-07 13:47:37 -07009092status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009093 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009094{
Paul McLean12340082019-03-19 09:35:05 -06009095 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009096 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009097 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009098 return NO_INIT;
9099 }
Paul McLean12340082019-03-19 09:35:05 -06009100 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009101}
9102
Andy Hungee58e4a2023-07-07 13:47:37 -07009103status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009104{
Paul McLean12340082019-03-19 09:35:05 -06009105 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009106 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009107 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009108 return NO_INIT;
9109 }
Paul McLean12340082019-03-19 09:35:05 -06009110 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009111}
9112
Andy Hungee58e4a2023-07-07 13:47:37 -07009113status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009114 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9115 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009116 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009117 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9118}
9119
Andy Hungee58e4a2023-07-07 13:47:37 -07009120status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009121 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9122 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009123
Eric Laurentec376dc2021-04-08 20:41:22 +02009124 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9125 return BAD_VALUE;
9126 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009127
9128 if (sharedAudioStartMs < 0
9129 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009130 return BAD_VALUE;
9131 }
9132
Eric Laurent2407ce32021-04-26 14:56:03 +02009133 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9134 // As we cannot detect more than one wraparound, only accept values up current write position
9135 // after one wraparound
9136 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9137 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009138 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009139 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9140 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009141 // Bring the start frame position within the input buffer to match the documented
9142 // "best effort" behavior of the API.
9143 if (sharedOffset < 0) {
9144 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009145 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009146 sharedAudioStartFrames =
9147 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009148 }
9149
Eric Laurentec376dc2021-04-08 20:41:22 +02009150 mSharedAudioPackageName = sharedAudioPackageName;
9151 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009152 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009153 } else {
9154 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009155 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009156 }
9157 return NO_ERROR;
9158}
9159
Andy Hungee58e4a2023-07-07 13:47:37 -07009160void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009161 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9162 mSharedAudioStartFrames = -1;
9163 mSharedAudioPackageName = "";
9164}
9165
Andy Hungee58e4a2023-07-07 13:47:37 -07009166ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009167{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009168 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009169 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009170 }
9171 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009172 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009173 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009174 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009175 }
9176 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009177 MetadataUpdate change;
9178 change.recordMetadataUpdate = metadata.tracks;
9179 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009180}
9181
Andy Hungc5007f82023-08-29 14:26:09 -07009182// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009183void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009184{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009185 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009186 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009187
Eric Laurent81784c32012-11-19 14:55:58 -08009188 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009189 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009190 removeTrack_l(track);
9191 }
9192}
9193
Andy Hungee58e4a2023-07-07 13:47:37 -07009194void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009195{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009196 String8 result;
9197 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009198 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009199
Eric Laurent81784c32012-11-19 14:55:58 -08009200 mTracks.remove(track);
9201 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009202 if (track->isFastTrack()) {
9203 ALOG_ASSERT(!mFastTrackAvail);
9204 mFastTrackAvail = true;
9205 }
Eric Laurent81784c32012-11-19 14:55:58 -08009206}
9207
Andy Hungee58e4a2023-07-07 13:47:37 -07009208void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009209{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009210 AudioStreamIn *input = mInput;
9211 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9212 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009213 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009214 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009215 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009216 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009217 }
Andy Hungbfa64962017-06-12 14:43:19 -07009218
9219 if (input != nullptr) {
9220 dprintf(fd, " Hal stream dump:\n");
9221 (void)input->stream->dump(fd);
9222 }
9223
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009224 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009225 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009226
Glenn Kasten2f90c512015-12-02 11:40:09 -08009227 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9228 // while we are dumping it. It may be inconsistent, but it won't mutate!
9229 // This is a large object so we place it on the heap.
9230 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009231 const std::unique_ptr<FastCaptureDumpState> copy =
9232 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009233 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009234}
9235
Andy Hungee58e4a2023-07-07 13:47:37 -07009236void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009237{
Eric Laurent81784c32012-11-19 14:55:58 -08009238 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009239 size_t numtracks = mTracks.size();
9240 size_t numactive = mActiveTracks.size();
9241 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009242 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009243 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009244 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009245 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009246 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009247 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009248 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009249 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009250 if (track != 0) {
9251 bool active = mActiveTracks.indexOf(track) >= 0;
9252 if (active) {
9253 numactiveseen++;
9254 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009255 result.append(prefix);
9256 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009257 }
Eric Laurent81784c32012-11-19 14:55:58 -08009258 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009259 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009260 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009261 }
9262
Marco Nelissenb2208842014-02-07 14:00:50 -08009263 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009264 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009265 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009266 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009267 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009268 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009269 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009270 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009271 result.append(prefix);
9272 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009273 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009274 }
Eric Laurent81784c32012-11-19 14:55:58 -08009275
9276 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009277 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009278}
9279
Andy Hungee58e4a2023-07-07 13:47:37 -07009280void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009281{
Andy Hung972bec12023-08-31 16:13:39 -07009282 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009283 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009284 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009285 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009286 track->setSilenced(silenced);
9287 }
9288 }
9289}
Andy Hung73c02e42015-03-29 01:13:58 -07009290
Andy Hung8d31fd22023-06-26 19:20:57 -07009291void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009292{
Andy Hung87c693c2023-07-06 20:56:16 -07009293 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009294 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009295 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009296 const int32_t rear = recordThread->mRsmpInRear;
9297 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009298 if (mRecordTrack->startFrames() >= 0) {
9299 int32_t startFrames = mRecordTrack->startFrames();
9300 // Accept a recent wraparound of mRsmpInRear
9301 if (startFrames <= rear) {
9302 deltaFrames = rear - startFrames;
9303 } else {
9304 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009305 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009306 // start frame cannot be further in the past than start of resampling buffer
9307 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9308 deltaFrames = recordThread->mRsmpInFrames;
9309 }
9310 }
9311 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009312}
9313
Andy Hung8d31fd22023-06-26 19:20:57 -07009314void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009315 size_t *framesAvailable, bool *hasOverrun)
9316{
Andy Hung87c693c2023-07-06 20:56:16 -07009317 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009318 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009319 const int32_t rear = recordThread->mRsmpInRear;
9320 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009321 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009322
9323 size_t framesIn;
9324 bool overrun = false;
9325 if (filled < 0) {
9326 // should not happen, but treat like a massive overrun and re-sync
9327 framesIn = 0;
9328 mRsmpInFront = rear;
9329 overrun = true;
9330 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9331 framesIn = (size_t) filled;
9332 } else {
9333 // client is not keeping up with server, but give it latest data
9334 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009335 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9336 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009337 overrun = true;
9338 }
9339 if (framesAvailable != NULL) {
9340 *framesAvailable = framesIn;
9341 }
9342 if (hasOverrun != NULL) {
9343 *hasOverrun = overrun;
9344 }
9345}
9346
Eric Laurent81784c32012-11-19 14:55:58 -08009347// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009348status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009349 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009350{
Andy Hung87c693c2023-07-06 20:56:16 -07009351 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009352 if (threadBase == 0) {
9353 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009354 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009355 return NOT_ENOUGH_DATA;
9356 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009357 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009358 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009359 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009360 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009361 // FIXME should not be P2 (don't want to increase latency)
9362 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009363 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009364 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009365
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009366 front &= recordThread->mRsmpInFramesP2 - 1;
9367 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009368 if (part1 > (size_t) filled) {
9369 part1 = filled;
9370 }
9371 size_t ask = buffer->frameCount;
9372 ALOG_ASSERT(ask > 0);
9373 if (part1 > ask) {
9374 part1 = ask;
9375 }
9376 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009377 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009378 buffer->raw = NULL;
9379 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009380 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009381 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009382 }
9383
Andy Hung57446612015-04-19 23:56:46 -07009384 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009385 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009386 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009387 return NO_ERROR;
9388}
9389
9390// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009391void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009392 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009393{
Hongwei Wang95e37682019-04-12 11:13:36 -07009394 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009395 if (stepCount == 0) {
9396 return;
9397 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009398 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009399 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009400 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009401 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009402 buffer->frameCount = 0;
9403}
9404
Andy Hungee58e4a2023-07-07 13:47:37 -07009405void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009406{
Andy Hung972bec12023-08-31 16:13:39 -07009407 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009408 checkBtNrec_l();
9409}
9410
Andy Hungee58e4a2023-07-07 13:47:37 -07009411void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009412{
9413 // disable AEC and NS if the device is a BT SCO headset supporting those
9414 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009415 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009416 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009417 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9418 for (size_t i = 0; i < mEffectChains.size(); i++) {
9419 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9420 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9421 }
9422 }
9423}
9424
Andy Hung97a893e2015-03-29 01:03:07 -07009425
Andy Hungee58e4a2023-07-07 13:47:37 -07009426bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009427 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009428{
9429 bool reconfig = false;
9430
Eric Laurent10351942014-05-08 18:49:52 -07009431 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009432
Eric Laurent10351942014-05-08 18:49:52 -07009433 audio_format_t reqFormat = mFormat;
9434 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009435 // 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 +08009436 [[maybe_unused]] audio_channel_mask_t channelMask =
9437 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009438
9439 AudioParameter param = AudioParameter(keyValuePair);
9440 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009441
9442 // scope for AutoPark extends to end of method
9443 AutoPark<FastCapture> park(mFastCapture);
9444
Eric Laurent10351942014-05-08 18:49:52 -07009445 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9446 // channel count change can be requested. Do we mandate the first client defines the
9447 // HAL sampling rate and channel count or do we allow changes on the fly?
9448 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9449 samplingRate = value;
9450 reconfig = true;
9451 }
9452 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009453 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009454 status = BAD_VALUE;
9455 } else {
9456 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009457 reconfig = true;
9458 }
Eric Laurent10351942014-05-08 18:49:52 -07009459 }
9460 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9461 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009462 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009463 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009464 status = BAD_VALUE;
9465 } else {
9466 channelMask = mask;
9467 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009468 }
Eric Laurent10351942014-05-08 18:49:52 -07009469 }
9470 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9471 // do not accept frame count changes if tracks are open as the track buffer
9472 // size depends on frame count and correct behavior would not be guaranteed
9473 // if frame count is changed after track creation
9474 if (mActiveTracks.size() > 0) {
9475 status = INVALID_OPERATION;
9476 } else {
9477 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009478 }
Eric Laurent10351942014-05-08 18:49:52 -07009479 }
9480 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009481 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009482 }
9483 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9484 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009485 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009486 }
Glenn Kastene198c362013-08-13 09:13:36 -07009487
Eric Laurent10351942014-05-08 18:49:52 -07009488 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009489 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009490 if (status == INVALID_OPERATION) {
9491 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009492 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009493 }
9494 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009495 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009496 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9497 if (mInput->stream->getAudioProperties(&config) == OK &&
9498 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9499 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009500 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009501 status = NO_ERROR;
9502 }
Eric Laurent81784c32012-11-19 14:55:58 -08009503 }
Eric Laurent10351942014-05-08 18:49:52 -07009504 if (status == NO_ERROR) {
9505 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009506 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009507 }
9508 }
Eric Laurent81784c32012-11-19 14:55:58 -08009509 }
Eric Laurent10351942014-05-08 18:49:52 -07009510
Eric Laurent81784c32012-11-19 14:55:58 -08009511 return reconfig;
9512}
9513
Andy Hungee58e4a2023-07-07 13:47:37 -07009514String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009515{
Andy Hung972bec12023-08-31 16:13:39 -07009516 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009517 if (initCheck() == NO_ERROR) {
9518 String8 out_s8;
9519 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9520 return out_s8;
9521 }
Eric Laurent81784c32012-11-19 14:55:58 -08009522 }
Andy Hung920f6572022-10-06 12:09:49 -07009523 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009524}
9525
Andy Hungab65b182023-09-06 19:41:47 -07009526void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009527 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009528 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009529 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009530 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009531 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009532 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009533 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9534 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009535 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009536 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009537 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009538 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009539 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009540 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009541 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009542 break;
9543 }
Andy Hungab65b182023-09-06 19:41:47 -07009544 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009545}
9546
Andy Hungee58e4a2023-07-07 13:47:37 -07009547void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009548{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009549 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9550 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009551 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009552 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9553 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009554 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9555 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009556 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009557 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009558 ALOGI("HAL format %#x is not linear pcm", mFormat);
9559 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009560 result = mInput->stream->getFrameSize(&mFrameSize);
9561 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009562 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9563 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009564 result = mInput->stream->getBufferSize(&mBufferSize);
9565 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009566 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009567 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9568 "mBufferSize=%zu, mFrameCount=%zu",
9569 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009570
Eric Laurentec376dc2021-04-08 20:41:22 +02009571 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9572 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009573 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009574
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009575 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9576 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009577
9578 audio_input_flags_t flags = mInput->flags;
9579 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9580 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009581 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009582 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9583 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9584 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9585 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9586 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9587 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009588}
9589
Andy Hungee58e4a2023-07-07 13:47:37 -07009590uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009591{
Andy Hung972bec12023-08-31 16:13:39 -07009592 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009593 uint32_t result;
9594 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9595 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009596 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009597 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009598}
9599
Andy Hungee58e4a2023-07-07 13:47:37 -07009600KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009601{
Glenn Kastend848eb42016-03-08 13:42:11 -08009602 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009603 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009604 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009605 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009606 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009607 if (ids.indexOfKey(sessionId) < 0) {
9608 ids.add(sessionId, true);
9609 }
9610 }
9611 return ids;
9612}
9613
Andy Hungee58e4a2023-07-07 13:47:37 -07009614AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009615{
Andy Hung972bec12023-08-31 16:13:39 -07009616 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009617 AudioStreamIn *input = mInput;
9618 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009619 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009620 return input;
9621}
9622
Andy Hungc5007f82023-08-29 14:26:09 -07009623// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009624sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009625{
9626 if (mInput == NULL) {
9627 return NULL;
9628 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009629 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009630}
9631
Andy Hungee58e4a2023-07-07 13:47:37 -07009632status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009633{
Eric Laurent81784c32012-11-19 14:55:58 -08009634 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009635 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009636 chain->setInBuffer(NULL);
9637 chain->setOutBuffer(NULL);
9638
9639 checkSuspendOnAddEffectChain_l(chain);
9640
Eric Laurent1b928682014-10-02 19:41:47 -07009641 // make sure enabled pre processing effects state is communicated to the HAL as we
9642 // just moved them to a new input stream.
9643 chain->syncHalEffectsState();
9644
Eric Laurent81784c32012-11-19 14:55:58 -08009645 mEffectChains.add(chain);
9646
9647 return NO_ERROR;
9648}
9649
Andy Hungee58e4a2023-07-07 13:47:37 -07009650size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009651{
9652 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009653
9654 for (size_t i = 0; i < mEffectChains.size(); i++) {
9655 if (chain == mEffectChains[i]) {
9656 mEffectChains.removeAt(i);
9657 break;
9658 }
Eric Laurent81784c32012-11-19 14:55:58 -08009659 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009660 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009661}
9662
Andy Hungee58e4a2023-07-07 13:47:37 -07009663status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009664 audio_patch_handle_t *handle)
9665{
9666 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009667
9668 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009669 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009670 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009671 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009672 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009673 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009674 }
9675
Eric Laurentd8365c52017-07-16 15:27:05 -07009676 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009677
9678 // store new source and send to effects
9679 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9680 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009681 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009682 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009683 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009684 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009685
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009686 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009687 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9688 status = hwDevice->createAudioPatch(patch->num_sources,
9689 patch->sources,
9690 patch->num_sinks,
9691 patch->sinks,
9692 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009693 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009694 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9695 patch->sinks[0].ext.mix.usecase.source,
9696 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009697 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009698 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009699
jiabinc52b1ff2019-10-31 17:20:42 -07009700 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009701 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009702 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009703 }
Eric Laurent296fb132015-05-01 11:38:42 -07009704
Andy Hungc2b11cb2020-04-22 09:04:01 -07009705 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009706 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009707 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009708 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009709 // also dispatch to active AudioRecords
9710 for (const auto &track : mActiveTracks) {
9711 track->logEndInterval();
9712 track->logBeginInterval(pathSourcesAsString);
9713 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009714 // Force meteadata update after a route change
9715 mActiveTracks.setHasChanged();
9716
Eric Laurent1c333e22014-05-20 10:48:17 -07009717 return status;
9718}
9719
Andy Hungee58e4a2023-07-07 13:47:37 -07009720status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009721{
9722 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009723
jiabinc52b1ff2019-10-31 17:20:42 -07009724 mPatch = audio_patch{};
9725 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009726
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009727 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009728 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9729 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009730 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009731 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009732 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009733 // Force meteadata update after a route change
9734 mActiveTracks.setHasChanged();
9735
Eric Laurent1c333e22014-05-20 10:48:17 -07009736 return status;
9737}
9738
Andy Hungee58e4a2023-07-07 13:47:37 -07009739void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009740{
Andy Hung972bec12023-08-31 16:13:39 -07009741 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009742 mOutDevices = outDevices;
9743 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9744 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009745 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009746 }
9747}
9748
Andy Hungee58e4a2023-07-07 13:47:37 -07009749int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009750{
9751 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009752 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009753 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009754 int32_t oldestFront = mRsmpInRear;
9755 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009756 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009757 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009758 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009759 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009760 if (filled > maxFilled) {
9761 oldestFront = front;
9762 maxFilled = filled;
9763 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009764 }
Andy Hung920f6572022-10-06 12:09:49 -07009765 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009766 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9767 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009768 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009769}
9770
Andy Hungee58e4a2023-07-07 13:47:37 -07009771void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009772{
9773 if (offset == 0) {
9774 return;
9775 }
9776 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009777 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009778 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009779 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009780 }
9781}
9782
Andy Hungee58e4a2023-07-07 13:47:37 -07009783void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009784{
9785 // This is the formula for calculating the temporary buffer size.
9786 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9787 // 1 full output buffer, regardless of the alignment of the available input.
9788 // The value is somewhat arbitrary, and could probably be even larger.
9789 // A larger value should allow more old data to be read after a track calls start(),
9790 // without increasing latency.
9791 //
9792 // Note this is independent of the maximum downsampling ratio permitted for capture.
9793 size_t minRsmpInFrames = mFrameCount * 7;
9794
9795 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9796 // capture history available to another client using the same session ID:
9797 // dimension the resampler input buffer accordingly.
9798
9799 // Get oldest client read position: getOldestFront_l() must be called before altering
9800 // mRsmpInRear, or mRsmpInFrames
9801 int32_t previousFront = getOldestFront_l();
9802 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9803 int32_t previousRear = mRsmpInRear;
9804 mRsmpInRear = 0;
9805
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009806 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009807 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009808 "resizeInputBuffer_l() called with invalid max shared history %d",
9809 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009810 if (maxSharedAudioHistoryMs != 0) {
9811 // resizeInputBuffer_l should never be called with a non zero shared history if the
9812 // buffer was not already allocated
9813 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9814 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9815 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9816 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009817 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009818 return;
9819 }
9820 mRsmpInFrames = rsmpInFrames;
9821 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009822 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009823 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9824 // initialized
9825 if (mRsmpInFrames < minRsmpInFrames) {
9826 mRsmpInFrames = minRsmpInFrames;
9827 }
9828 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9829
9830 // TODO optimize audio capture buffer sizes ...
9831 // Here we calculate the size of the sliding buffer used as a source
9832 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9833 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9834 // be better to have it derived from the pipe depth in the long term.
9835 // The current value is higher than necessary. However it should not add to latency.
9836
9837 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9838 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9839
9840 void *rsmpInBuffer;
9841 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9842 // if posix_memalign fails, will segv here.
9843 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9844
9845 // Copy audio history if any from old buffer before freeing it
9846 if (previousRear != 0) {
9847 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9848 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9849
9850 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9851 previousFront &= previousRsmpInFramesP2 - 1;
9852 size_t part1 = previousRsmpInFramesP2 - previousFront;
9853 if (part1 > (size_t) unread) {
9854 part1 = unread;
9855 }
9856 if (part1 != 0) {
9857 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9858 part1 * mFrameSize);
9859 mRsmpInRear = part1;
9860 part1 = unread - part1;
9861 if (part1 != 0) {
9862 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9863 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9864 mRsmpInRear += part1;
9865 }
9866 }
9867 // Update front for all clients according to new rear
9868 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9869 } else {
9870 mRsmpInRear = 0;
9871 }
9872 free(mRsmpInBuffer);
9873 mRsmpInBuffer = rsmpInBuffer;
9874}
9875
Andy Hungee58e4a2023-07-07 13:47:37 -07009876void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009877{
Andy Hung972bec12023-08-31 16:13:39 -07009878 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009879 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009880 if (record->getSource()) {
9881 mSource = record->getSource();
9882 }
Eric Laurent83b88082014-06-20 18:31:16 -07009883}
9884
Andy Hungee58e4a2023-07-07 13:47:37 -07009885void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009886{
Andy Hung972bec12023-08-31 16:13:39 -07009887 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009888 if (mSource == record->getSource()) {
9889 mSource = mInput;
9890 }
Eric Laurent83b88082014-06-20 18:31:16 -07009891 destroyTrack_l(record);
9892}
9893
Andy Hungee58e4a2023-07-07 13:47:37 -07009894void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009895{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009896 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009897 config->role = AUDIO_PORT_ROLE_SINK;
9898 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9899 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009900 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9901 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9902 config->flags.input = mInput->flags;
9903 }
Eric Laurent83b88082014-06-20 18:31:16 -07009904}
Eric Laurent1c333e22014-05-20 10:48:17 -07009905
Eric Laurent6acd1d42017-01-04 14:23:29 -08009906// ----------------------------------------------------------------------------
9907// Mmap
9908// ----------------------------------------------------------------------------
9909
Andy Hung7aa7d102023-07-07 15:58:48 -07009910// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9911// MmapPlaybackThread or MmapCaptureThread instance.
9912class MmapThreadHandle : public MmapStreamInterface {
9913public:
9914 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9915 ~MmapThreadHandle() override;
9916
9917 // MmapStreamInterface virtuals
9918 status_t createMmapBuffer(int32_t minSizeFrames,
9919 struct audio_mmap_buffer_info* info) final;
9920 status_t getMmapPosition(struct audio_mmap_position* position) final;
9921 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9922 status_t start(const AudioClient& client,
9923 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9924 status_t stop(audio_port_handle_t handle) final;
9925 status_t standby() final;
9926 status_t reportData(const void* buffer, size_t frameCount) final;
9927private:
9928 const sp<IAfMmapThread> mThread;
9929};
9930
9931/* static */
9932sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9933 const sp<IAfMmapThread>& mmapThread) {
9934 return sp<MmapThreadHandle>::make(mmapThread);
9935}
9936
9937MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009938 : mThread(thread)
9939{
Phil Burk9fabbf82017-08-03 12:02:00 -07009940 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941}
9942
Andy Hung7aa7d102023-07-07 15:58:48 -07009943// MmapStreamInterface could be directly implemented by MmapThread excepting this
9944// special handling on adapter dtor.
9945MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009946{
Phil Burk9fabbf82017-08-03 12:02:00 -07009947 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948}
9949
Andy Hung7aa7d102023-07-07 15:58:48 -07009950status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009951 struct audio_mmap_buffer_info *info)
9952{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953 return mThread->createMmapBuffer(minSizeFrames, info);
9954}
9955
Andy Hung7aa7d102023-07-07 15:58:48 -07009956status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009958 return mThread->getMmapPosition(position);
9959}
9960
Andy Hung7aa7d102023-07-07 15:58:48 -07009961status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009962 int64_t *timeNanos) {
9963 return mThread->getExternalPosition(position, timeNanos);
9964}
9965
Andy Hung7aa7d102023-07-07 15:58:48 -07009966status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009967 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009968{
jiabind1f1cb62020-03-24 11:57:57 -07009969 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009970}
9971
Andy Hung7aa7d102023-07-07 15:58:48 -07009972status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009973{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009974 return mThread->stop(handle);
9975}
9976
Andy Hung7aa7d102023-07-07 15:58:48 -07009977status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009978{
Eric Laurent18b57012017-02-13 16:23:52 -08009979 return mThread->standby();
9980}
9981
Andy Hung7aa7d102023-07-07 15:58:48 -07009982status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9983{
jiabinfc791ee2023-02-15 19:43:40 +00009984 return mThread->reportData(buffer, frameCount);
9985}
9986
Eric Laurent6acd1d42017-01-04 14:23:29 -08009987
Andy Hungee58e4a2023-07-07 13:47:37 -07009988MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -07009989 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009990 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -07009991 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009992 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009993 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009994 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009995 mActiveTracks(&this->mLocalLog),
9996 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9997 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009998{
Eric Laurent18b57012017-02-13 16:23:52 -08009999 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010000 readHalParameters_l();
10001}
10002
Andy Hungee58e4a2023-07-07 13:47:37 -070010003void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010004{
10005 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10006}
10007
Andy Hungee58e4a2023-07-07 13:47:37 -070010008void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010009{
Andy Hung8d31fd22023-06-26 19:20:57 -070010010 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -070010011 {
Andy Hung972bec12023-08-31 16:13:39 -070010012 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010013 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010014 activeTracks.add(t);
10015 }
10016 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010017 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 stop(t->portId());
10019 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010020 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010021 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010022 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010023 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010024 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010025 }
10026}
10027
10028
Andy Hungee58e4a2023-07-07 13:47:37 -070010029void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010030 audio_stream_type_t streamType __unused,
10031 audio_session_t sessionId,
10032 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010033 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010034 audio_port_handle_t portId)
10035{
10036 mAttr = *attr;
10037 mSessionId = sessionId;
10038 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010039 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010040 mPortId = portId;
10041}
10042
Andy Hungee58e4a2023-07-07 13:47:37 -070010043status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010044 struct audio_mmap_buffer_info *info)
10045{
10046 if (mHalStream == 0) {
10047 return NO_INIT;
10048 }
Eric Laurent18b57012017-02-13 16:23:52 -080010049 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050 return mHalStream->createMmapBuffer(minSizeFrames, info);
10051}
10052
Andy Hungee58e4a2023-07-07 13:47:37 -070010053status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010054{
10055 if (mHalStream == 0) {
10056 return NO_INIT;
10057 }
10058 return mHalStream->getMmapPosition(position);
10059}
10060
Andy Hungee58e4a2023-07-07 13:47:37 -070010061status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010062{
Eric Laurentdda206a2022-07-08 17:28:35 +020010063 // The HAL must receive track metadata before starting the stream
10064 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010065 status_t ret = mHalStream->start();
10066 if (ret != NO_ERROR) {
10067 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10068 return ret;
10069 }
Andy Hungcf10d742020-04-28 15:38:24 -070010070 if (mStandby) {
10071 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010072 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010073 mStandby = false;
10074 }
Eric Laurent331679c2018-04-16 17:03:16 -070010075 return NO_ERROR;
10076}
10077
Andy Hungee58e4a2023-07-07 13:47:37 -070010078status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010079 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010080 audio_port_handle_t *handle)
10081{
Eric Laurenta54f1282017-07-01 19:39:32 -070010082 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010083 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010084 if (mHalStream == 0) {
10085 return NO_INIT;
10086 }
10087
10088 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010089
Eric Laurentdda206a2022-07-08 17:28:35 +020010090 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010091 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010092 acquireWakeLock();
10093 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010094 }
10095
10096 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10097
10098 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010099 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010100 client.attributionSource);
10101
Eric Laurenta54f1282017-07-01 19:39:32 -070010102 if (isOutput()) {
10103 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10104 config.sample_rate = mSampleRate;
10105 config.channel_mask = mChannelMask;
10106 config.format = mFormat;
10107 audio_stream_type_t stream = streamType();
10108 audio_output_flags_t flags =
10109 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010110 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010111 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010112 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010113 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010114 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10115 mSessionId,
10116 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010117 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010118 &config,
10119 flags,
10120 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010121 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010122 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010123 &isSpatialized,
10124 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010125 ALOGD_IF(!secondaryOutputs.empty(),
10126 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010127 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010128 audio_config_base_t config;
10129 config.sample_rate = mSampleRate;
10130 config.channel_mask = mChannelMask;
10131 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010132 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010133 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010134 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010135 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010136 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010137 &config,
10138 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10139 &deviceId,
10140 &portId);
10141 }
10142 // APM should not chose a different input or output stream for the same set of attributes
10143 // and audo configuration
10144 if (ret != NO_ERROR || io != mId) {
10145 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10146 __FUNCTION__, ret, io, mId);
10147 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010148 }
10149
10150 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010151 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152 } else {
jiabin09609032022-06-15 19:26:01 +000010153 {
10154 // Add the track record before starting input so that the silent status for the
10155 // client can be cached.
Andy Hung972bec12023-08-31 16:13:39 -070010156 audio_utils::lock_guard _l(mutex());
jiabin09609032022-06-15 19:26:01 +000010157 setClientSilencedState_l(portId, false /*silenced*/);
10158 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010159 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010160 }
10161
Andy Hung972bec12023-08-31 16:13:39 -070010162 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010163 // abort if start is rejected by audio policy manager
10164 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010165 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010166 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010167 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010168 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010169 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010170 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010171 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010172 }
Andy Hungc5007f82023-08-29 14:26:09 -070010173 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010174 } else {
10175 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176 }
jiabin09609032022-06-15 19:26:01 +000010177 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 return PERMISSION_DENIED;
10179 }
10180
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010181 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010182 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10183 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010184 mChannelMask, mSessionId, isOutput(),
10185 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010186 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010187 if (!isOutput()) {
10188 track->setSilenced_l(isClientSilenced_l(portId));
10189 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010190
Eric Laurent4eb58f12018-12-07 16:41:02 -080010191 if (isOutput()) {
10192 // force volume update when a new track is added
10193 mHalVolFloat = -1.0f;
10194 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010195 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010196 if (t->isSilenced_l()
10197 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010198 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010199 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010200 }
10201 }
10202
Eric Laurent6acd1d42017-01-04 14:23:29 -080010203 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010204 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010205 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010206 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207 chain->incTrackCnt();
10208 chain->incActiveTrackCnt();
10209 }
10210
Andy Hungc2b11cb2020-04-22 09:04:01 -070010211 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010212 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010213
10214 if (mActiveTracks.size() == 1) {
10215 ret = exitStandby_l();
10216 }
10217
Eric Laurent6acd1d42017-01-04 14:23:29 -080010218 broadcast_l();
10219
Eric Laurentdda206a2022-07-08 17:28:35 +020010220 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010221
Eric Laurentdda206a2022-07-08 17:28:35 +020010222 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010223}
10224
Andy Hungee58e4a2023-07-07 13:47:37 -070010225status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010226{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010227 ALOGV("%s handle %d", __FUNCTION__, handle);
10228
10229 if (mHalStream == 0) {
10230 return NO_INIT;
10231 }
10232
Eric Laurenta54f1282017-07-01 19:39:32 -070010233 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010234 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010235 return NO_ERROR;
10236 }
10237
Andy Hung972bec12023-08-31 16:13:39 -070010238 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070010239
Andy Hung8d31fd22023-06-26 19:20:57 -070010240 sp<IAfMmapTrack> track;
10241 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242 if (handle == t->portId()) {
10243 track = t;
10244 break;
10245 }
10246 }
10247 if (track == 0) {
10248 return BAD_VALUE;
10249 }
10250
10251 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010252 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010253
Andy Hungc5007f82023-08-29 14:26:09 -070010254 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010255 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010256 AudioSystem::stopOutput(track->portId());
10257 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010259 AudioSystem::stopInput(track->portId());
10260 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261 }
Andy Hungc5007f82023-08-29 14:26:09 -070010262 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263
Andy Hung116bc262023-06-20 18:56:17 -070010264 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265 if (chain != 0) {
10266 chain->decActiveTrackCnt();
10267 chain->decTrackCnt();
10268 }
10269
Eric Laurentdda206a2022-07-08 17:28:35 +020010270 if (mActiveTracks.isEmpty()) {
10271 mHalStream->stop();
10272 }
10273
Eric Laurent6acd1d42017-01-04 14:23:29 -080010274 broadcast_l();
10275
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276 return NO_ERROR;
10277}
10278
Andy Hungee58e4a2023-07-07 13:47:37 -070010279status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010280{
10281 ALOGV("%s", __FUNCTION__);
10282
10283 if (mHalStream == 0) {
10284 return NO_INIT;
10285 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010286 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010287 return INVALID_OPERATION;
10288 }
10289 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010290 if (!mStandby) {
10291 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010292 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010293 mStandby = true;
10294 }
Eric Laurent18b57012017-02-13 16:23:52 -080010295 releaseWakeLock();
10296 return NO_ERROR;
10297}
10298
Andy Hungee58e4a2023-07-07 13:47:37 -070010299status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010300 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10301 return INVALID_OPERATION;
10302}
10303
Andy Hungee58e4a2023-07-07 13:47:37 -070010304void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305{
10306 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10307 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10308 mFormat = mHALFormat;
10309 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10310 result = mHalStream->getFrameSize(&mFrameSize);
10311 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010312 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10313 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 result = mHalStream->getBufferSize(&mBufferSize);
10315 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10316 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010317
Andy Hungcf10d742020-04-28 15:38:24 -070010318 // TODO: make a readHalParameters call?
10319 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010320 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010321 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010322 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10323 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10324 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10325 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10326 /*
10327 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10328 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10329 (int32_t)mHapticChannelMask)
10330 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10331 (int32_t)mHapticChannelCount)
10332 */
10333 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010334 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010335 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10336 (int32_t)mFrameCount) // sic - added HAL
10337 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338}
10339
Andy Hungee58e4a2023-07-07 13:47:37 -070010340bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010341{
Andy Hungab65b182023-09-06 19:41:47 -070010342 {
10343 audio_utils::unique_lock _l(mutex());
10344 checkSilentMode_l();
10345 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346
10347 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10348
10349 while (!exitPending())
10350 {
Andy Hung116bc262023-06-20 18:56:17 -070010351 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352
Andy Hung13850be2019-03-14 11:33:09 -070010353 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010354 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010355
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356 if (mSignalPending) {
10357 // A signal was raised while we were unlocked
10358 mSignalPending = false;
10359 } else {
10360 if (mConfigEvents.isEmpty()) {
10361 // we're about to wait, flush the binder command buffer
10362 IPCThreadState::self()->flushCommands();
10363
10364 if (exitPending()) {
10365 break;
10366 }
10367
Eric Laurent6acd1d42017-01-04 14:23:29 -080010368 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010369 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010370 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010371 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010372
10373 checkSilentMode_l();
10374
10375 continue;
10376 }
10377 }
10378
10379 processConfigEvents_l();
10380
10381 processVolume_l();
10382
10383 checkInvalidTracks_l();
10384
Andy Hungab65b182023-09-06 19:41:47 -070010385 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010386
Kevin Rocard069c2712018-03-29 19:09:14 -070010387 updateMetadata_l();
10388
Eric Laurent6acd1d42017-01-04 14:23:29 -080010389 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010390 } // release Thread lock
10391
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010393 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010394 }
Andy Hung13850be2019-03-14 11:33:09 -070010395
10396 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397 unlockEffectChains(effectChains);
10398 // Effect chains will be actually deleted here if they were removed from
10399 // mEffectChains list during mixing or effects processing
10400 }
10401
10402 threadLoop_exit();
10403
10404 if (!mStandby) {
10405 threadLoop_standby();
10406 mStandby = true;
10407 }
10408
Eric Laurent6acd1d42017-01-04 14:23:29 -080010409 ALOGV("Thread %p type %d exiting", this, mType);
10410 return false;
10411}
10412
Andy Hungc5007f82023-08-29 14:26:09 -070010413// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010414bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010415 status_t& status)
10416{
10417 AudioParameter param = AudioParameter(keyValuePair);
10418 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010419 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010420 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010421 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010423 if (sendToHal) {
10424 status = mHalStream->setParameters(keyValuePair);
10425 } else {
10426 status = NO_ERROR;
10427 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428
10429 return false;
10430}
10431
Andy Hungee58e4a2023-07-07 13:47:37 -070010432String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010433{
Andy Hung972bec12023-08-31 16:13:39 -070010434 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010435 String8 out_s8;
10436 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10437 return out_s8;
10438 }
Andy Hung920f6572022-10-06 12:09:49 -070010439 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010440}
10441
Andy Hungab65b182023-09-06 19:41:47 -070010442void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010443 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010444 sp<AudioIoDescriptor> desc;
10445 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010446 switch (event) {
10447 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010448 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010450 isInput = true;
10451 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010452 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010453 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010454 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010455 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10456 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010458 case AUDIO_INPUT_CLOSED:
10459 case AUDIO_OUTPUT_CLOSED:
10460 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010461 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462 break;
10463 }
Andy Hungab65b182023-09-06 19:41:47 -070010464 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010465}
10466
Andy Hungee58e4a2023-07-07 13:47:37 -070010467status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010469NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470{
10471 status_t status = NO_ERROR;
10472
10473 // store new device and send to effects
10474 audio_devices_t type = AUDIO_DEVICE_NONE;
10475 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010476 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10477 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10478 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010479 if (isOutput()) {
10480 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010481 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10482 && !mAudioHwDev->supportsAudioPatches(),
10483 "Enumerated device type(%#x) must not be used "
10484 "as it does not support audio patches",
10485 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010486 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010487 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10488 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010489 }
10490 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010491 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010492 } else {
10493 type = patch->sources[0].ext.device.type;
10494 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010495 numDevices = mPatch.num_sources;
10496 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010497 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010498 }
10499
10500 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010501 if (isOutput()) {
10502 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10503 } else {
10504 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10505 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010506 }
10507
jiabinc52b1ff2019-10-31 17:20:42 -070010508 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010509 // store new source and send to effects
10510 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10511 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10512 for (size_t i = 0; i < mEffectChains.size(); i++) {
10513 mEffectChains[i]->setAudioSource_l(mAudioSource);
10514 }
10515 }
10516 }
10517
10518 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010519 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10520 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010521 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010522 audio_port_config port;
10523 std::optional<audio_source_t> source;
10524 if (isOutput()) {
10525 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010526 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010527 port = patch->sources[0];
10528 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010529 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010530 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010531 *handle = AUDIO_PATCH_HANDLE_NONE;
10532 }
10533
jiabinc52b1ff2019-10-31 17:20:42 -070010534 if (numDevices == 0 || mDeviceId != deviceId) {
10535 if (isOutput()) {
10536 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10537 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010538 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010539 } else {
10540 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10541 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10542 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010543 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010544 if (mDeviceId != deviceId && callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010545 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010546 callback->onRoutingChanged(deviceId);
Andy Hungc5007f82023-08-29 14:26:09 -070010547 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010548 }
jiabinc52b1ff2019-10-31 17:20:42 -070010549 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010550 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010552 // Force meteadata update after a route change
10553 mActiveTracks.setHasChanged();
10554
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555 return status;
10556}
10557
Andy Hungee58e4a2023-07-07 13:47:37 -070010558status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010559{
10560 status_t status = NO_ERROR;
10561
jiabinc52b1ff2019-10-31 17:20:42 -070010562 mPatch = audio_patch{};
10563 mOutDeviceTypeAddrs.clear();
10564 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565
10566 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10567 supportsAudioPatches : false;
10568
10569 if (supportsAudioPatches) {
10570 status = mHalDevice->releaseAudioPatch(handle);
10571 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010572 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010574 // Force meteadata update after a route change
10575 mActiveTracks.setHasChanged();
10576
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577 return status;
10578}
10579
Andy Hungee58e4a2023-07-07 13:47:37 -070010580void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010582 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010583 if (isOutput()) {
10584 config->role = AUDIO_PORT_ROLE_SOURCE;
10585 config->ext.mix.hw_module = mAudioHwDev->handle();
10586 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10587 } else {
10588 config->role = AUDIO_PORT_ROLE_SINK;
10589 config->ext.mix.hw_module = mAudioHwDev->handle();
10590 config->ext.mix.usecase.source = mAudioSource;
10591 }
10592}
10593
Andy Hungee58e4a2023-07-07 13:47:37 -070010594status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010595{
10596 audio_session_t session = chain->sessionId();
10597
10598 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10599 // Attach all tracks with same session ID to this chain.
10600 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010601 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602 if (session == track->sessionId()) {
10603 chain->incTrackCnt();
10604 chain->incActiveTrackCnt();
10605 }
10606 }
10607
10608 chain->setThread(this);
10609 chain->setInBuffer(nullptr);
10610 chain->setOutBuffer(nullptr);
10611 chain->syncHalEffectsState();
10612
10613 mEffectChains.add(chain);
10614 checkSuspendOnAddEffectChain_l(chain);
10615 return NO_ERROR;
10616}
10617
Andy Hungee58e4a2023-07-07 13:47:37 -070010618size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010619{
10620 audio_session_t session = chain->sessionId();
10621
10622 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10623
10624 for (size_t i = 0; i < mEffectChains.size(); i++) {
10625 if (chain == mEffectChains[i]) {
10626 mEffectChains.removeAt(i);
10627 // detach all active tracks from the chain
10628 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010629 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630 if (session == track->sessionId()) {
10631 chain->decActiveTrackCnt();
10632 chain->decTrackCnt();
10633 }
10634 }
10635 break;
10636 }
10637 }
10638 return mEffectChains.size();
10639}
10640
Andy Hungee58e4a2023-07-07 13:47:37 -070010641void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010642{
10643 mHalStream->standby();
10644}
10645
Andy Hungee58e4a2023-07-07 13:47:37 -070010646void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010647{
Phil Burk7dce7282017-09-27 13:51:41 -070010648 // Do not call callback->onTearDown() because it is redundant for thread exit
10649 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010650}
10651
Andy Hungee58e4a2023-07-07 13:47:37 -070010652status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010653{
10654 return BAD_VALUE;
10655}
10656
Andy Hungee58e4a2023-07-07 13:47:37 -070010657bool MmapThread::isValidSyncEvent(
10658 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010659{
10660 return false;
10661}
10662
Andy Hungee58e4a2023-07-07 13:47:37 -070010663status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010664 const effect_descriptor_t *desc, audio_session_t sessionId)
10665{
10666 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010667 if (audio_is_global_session(sessionId)) {
10668 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669 desc->name, mThreadName);
10670 return BAD_VALUE;
10671 }
10672
10673 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10674 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10675 desc->name);
10676 return BAD_VALUE;
10677 }
10678 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010679 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10680 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010681 return BAD_VALUE;
10682 }
10683
10684 // Only allow effects without processing load or latency
10685 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10686 return BAD_VALUE;
10687 }
10688
Andy Hung116bc262023-06-20 18:56:17 -070010689 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010690 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10691 return BAD_VALUE;
10692 }
10693
Eric Laurent6acd1d42017-01-04 14:23:29 -080010694 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010695}
10696
Andy Hungee58e4a2023-07-07 13:47:37 -070010697void MmapThread::checkInvalidTracks_l()
Andy Hungc5007f82023-08-29 14:26:09 -070010698NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010699{
Eric Laurent039c24a2022-10-07 14:01:59 +020010700 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010701 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010703 callback = mCallback.promote();
10704 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10705 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10706 mNoCallbackWarningCount++;
10707 }
10708 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709 }
10710 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010711 if (callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010712 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010713 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungc5007f82023-08-29 14:26:09 -070010714 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010715 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010716}
10717
Andy Hungee58e4a2023-07-07 13:47:37 -070010718void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010720 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10721 mAttr.content_type, mAttr.usage, mAttr.source);
10722 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010723 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010724 dprintf(fd, " No active clients\n");
10725 }
10726}
10727
Andy Hungee58e4a2023-07-07 13:47:37 -070010728void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010729{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010730 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010731 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010732 dprintf(fd, " %zu Tracks\n", numtracks);
10733 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010734 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010735 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010736 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010737 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010738 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010739 result.append(prefix);
10740 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010741 }
10742 } else {
10743 dprintf(fd, "\n");
10744 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010745 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010746}
10747
Andy Hungee58e4a2023-07-07 13:47:37 -070010748/* static */
10749sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010750 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010751 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010752 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010753}
10754
10755MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010756 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010757 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010758 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010759 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010760 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010761{
10762 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10763 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010764 mMasterVolume = afThreadCallback->masterVolume_l();
10765 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010766
10767 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10768 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10769 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010770 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010771 }
10772 // Audio patch and call assistant volume are always max
10773 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10774 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10775 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10776 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10777
Eric Laurent6acd1d42017-01-04 14:23:29 -080010778 if (mAudioHwDev) {
10779 if (mAudioHwDev->canSetMasterVolume()) {
10780 mMasterVolume = 1.0;
10781 }
10782
10783 if (mAudioHwDev->canSetMasterMute()) {
10784 mMasterMute = false;
10785 }
10786 }
10787}
10788
Andy Hungee58e4a2023-07-07 13:47:37 -070010789void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790 audio_stream_type_t streamType,
10791 audio_session_t sessionId,
10792 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010793 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010794 audio_port_handle_t portId)
10795{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010796 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010797 mStreamType = streamType;
10798}
10799
Andy Hungee58e4a2023-07-07 13:47:37 -070010800AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010801{
Andy Hung972bec12023-08-31 16:13:39 -070010802 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010803 AudioStreamOut *output = mOutput;
10804 mOutput = NULL;
10805 return output;
10806}
10807
Andy Hungee58e4a2023-07-07 13:47:37 -070010808void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010809{
Andy Hung972bec12023-08-31 16:13:39 -070010810 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010811 // Don't apply master volume in SW if our HAL can do it for us.
10812 if (mAudioHwDev &&
10813 mAudioHwDev->canSetMasterVolume()) {
10814 mMasterVolume = 1.0;
10815 } else {
10816 mMasterVolume = value;
10817 }
10818}
10819
Andy Hungee58e4a2023-07-07 13:47:37 -070010820void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010821{
Andy Hung972bec12023-08-31 16:13:39 -070010822 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010823 // Don't apply master mute in SW if our HAL can do it for us.
10824 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10825 mMasterMute = false;
10826 } else {
10827 mMasterMute = muted;
10828 }
10829}
10830
Andy Hungee58e4a2023-07-07 13:47:37 -070010831void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010832{
Andy Hung972bec12023-08-31 16:13:39 -070010833 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010834 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010835 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010836 broadcast_l();
10837 }
10838}
10839
Andy Hungee58e4a2023-07-07 13:47:37 -070010840float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010841{
Andy Hung972bec12023-08-31 16:13:39 -070010842 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010843 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010844}
10845
Andy Hungee58e4a2023-07-07 13:47:37 -070010846void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010847{
Andy Hung972bec12023-08-31 16:13:39 -070010848 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010849 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010850 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010851 broadcast_l();
10852 }
10853}
10854
Andy Hungee58e4a2023-07-07 13:47:37 -070010855void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010856{
Andy Hung972bec12023-08-31 16:13:39 -070010857 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010858 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010859 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010860 track->invalidate();
10861 }
10862 broadcast_l();
10863 }
10864}
10865
Andy Hungee58e4a2023-07-07 13:47:37 -070010866void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010867{
Andy Hung972bec12023-08-31 16:13:39 -070010868 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010869 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010870 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010871 if (portIds.find(track->portId()) != portIds.end()) {
10872 track->invalidate();
10873 trackMatch = true;
10874 portIds.erase(track->portId());
10875 }
10876 if (portIds.empty()) {
10877 break;
10878 }
10879 }
10880 if (trackMatch) {
10881 broadcast_l();
10882 }
10883}
10884
Andy Hungee58e4a2023-07-07 13:47:37 -070010885void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010886NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010887{
10888 float volume;
10889
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010890 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010891 volume = 0;
10892 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010893 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010894 }
10895
10896 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010897 // Convert volumes from float to 8.24
10898 uint32_t vol = (uint32_t)(volume * (1 << 24));
10899
10900 // Delegate volume control to effect in track effect chain if needed
10901 // only one effect chain can be present on DirectOutputThread, so if
10902 // there is one, the track is connected to it
10903 if (!mEffectChains.isEmpty()) {
10904 mEffectChains[0]->setVolume_l(&vol, &vol);
10905 volume = (float)vol / (1 << 24);
10906 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010907 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010908 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10909 mHalVolFloat = volume; // HW volume control worked, so update value.
10910 mNoCallbackWarningCount = 0;
10911 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010912 sp<MmapStreamCallback> callback = mCallback.promote();
10913 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010914 mHalVolFloat = volume; // SW volume control worked, so update value.
10915 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070010916 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010917 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070010918 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010919 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010920 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10921 ALOGW("Could not set MMAP stream volume: no volume callback!");
10922 mNoCallbackWarningCount++;
10923 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010924 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010925 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010926 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010927 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070010928 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010929 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010930 streamVolume_l() == 0.f,
10931 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010932 // TODO(b/241533526): adjust logic to include mute from AppOps
10933 false /*muteFromPlaybackRestricted*/,
10934 false /*muteFromClientVolume*/,
10935 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010936 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937 }
10938}
10939
Andy Hungee58e4a2023-07-07 13:47:37 -070010940ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010941{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010942 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010943 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010944 }
10945 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070010946 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010947 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010948 playback_track_metadata_v7_t trackMetadata;
10949 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010950 .usage = track->attributes().usage,
10951 .content_type = track->attributes().content_type,
10952 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010953 };
10954 trackMetadata.channel_mask = track->channelMask(),
10955 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10956 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010957 }
10958 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010959
10960 MetadataUpdate change;
10961 change.playbackMetadataUpdate = metadata.tracks;
10962 return change;
10963};
Kevin Rocard069c2712018-03-29 19:09:14 -070010964
Andy Hungee58e4a2023-07-07 13:47:37 -070010965void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010966{
10967 if (!mMasterMute) {
10968 char value[PROPERTY_VALUE_MAX];
10969 if (property_get("ro.audio.silent", value, "0") > 0) {
10970 char *endptr;
10971 unsigned long ul = strtoul(value, &endptr, 0);
10972 if (*endptr == '\0' && ul != 0) {
10973 ALOGD("Silence is golden");
10974 // The setprop command will not allow a property to be changed after
10975 // the first time it is set, so we don't have to worry about un-muting.
10976 setMasterMute_l(true);
10977 }
10978 }
10979 }
10980}
10981
Andy Hungee58e4a2023-07-07 13:47:37 -070010982void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010983{
10984 MmapThread::toAudioPortConfig(config);
10985 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10986 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10987 config->flags.output = mOutput->flags;
10988 }
10989}
10990
Andy Hungee58e4a2023-07-07 13:47:37 -070010991status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070010992 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010993{
10994 if (mOutput == nullptr) {
10995 return NO_INIT;
10996 }
10997 struct timespec timestamp;
10998 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10999 if (status == NO_ERROR) {
11000 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11001 }
11002 return status;
11003}
11004
Andy Hungee58e4a2023-07-07 13:47:37 -070011005status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011006 // Send to MelProcessor for sound dose measurement.
11007 auto processor = mMelProcessor.load();
11008 if (processor) {
11009 processor->process(buffer, frameCount * mFrameSize);
11010 }
11011
jiabinfc791ee2023-02-15 19:43:40 +000011012 return NO_ERROR;
11013}
11014
Andy Hungc5007f82023-08-29 14:26:09 -070011015// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011016void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011017 const sp<audio_utils::MelProcessor>& processor)
11018{
11019 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011020 mMelProcessor.store(processor);
11021 if (processor) {
11022 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011023 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011024
11025 // no need to update output format for MMapPlaybackThread since it is
11026 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011027}
11028
Andy Hungc5007f82023-08-29 14:26:09 -070011029// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011030void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011031{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011032 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11033 auto melProcessor = mMelProcessor.load();
11034 if (melProcessor != nullptr) {
11035 melProcessor->pause();
11036 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011037}
11038
Andy Hungee58e4a2023-07-07 13:47:37 -070011039void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011040{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011041 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011042
Glenn Kastend3bb6452016-12-05 18:14:37 -080011043 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011044 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11046}
11047
Andy Hungee58e4a2023-07-07 13:47:37 -070011048/* static */
11049sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011050 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011051 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011052 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011053}
11054
11055MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011056 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011057 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011058 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059 mInput(input)
11060{
11061 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11062 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11063}
11064
Andy Hungee58e4a2023-07-07 13:47:37 -070011065status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011066{
Phil Burkf054fc32018-12-06 09:45:59 -080011067 {
11068 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011069 if (mInput != nullptr && mInput->stream != nullptr) {
11070 mInput->stream->setGain(1.0f);
11071 }
11072 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011073 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011074}
11075
Andy Hungee58e4a2023-07-07 13:47:37 -070011076AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077{
Andy Hung972bec12023-08-31 16:13:39 -070011078 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011079 AudioStreamIn *input = mInput;
11080 mInput = NULL;
11081 return input;
11082}
Kevin Rocard069c2712018-03-29 19:09:14 -070011083
Andy Hungee58e4a2023-07-07 13:47:37 -070011084void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011085{
11086 bool changed = false;
11087 bool silenced = false;
11088
11089 sp<MmapStreamCallback> callback = mCallback.promote();
11090 if (callback == 0) {
11091 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11092 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11093 mNoCallbackWarningCount++;
11094 }
11095 }
11096
11097 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11098 // track is silenced and unmute otherwise
11099 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11100 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11101 changed = true;
11102 silenced = mActiveTracks[i]->isSilenced_l();
11103 }
11104 }
11105
11106 if (changed) {
11107 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11108 }
11109}
11110
Andy Hungee58e4a2023-07-07 13:47:37 -070011111ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011112{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011113 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011114 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011115 }
11116 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011117 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011118 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011119 record_track_metadata_v7_t trackMetadata;
11120 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011121 .source = track->attributes().source,
11122 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011123 };
11124 trackMetadata.channel_mask = track->channelMask(),
11125 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11126 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011127 }
11128 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011129 MetadataUpdate change;
11130 change.recordMetadataUpdate = metadata.tracks;
11131 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011132}
11133
Andy Hungee58e4a2023-07-07 13:47:37 -070011134void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011135{
Andy Hung972bec12023-08-31 16:13:39 -070011136 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011137 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011138 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011139 mActiveTracks[i]->setSilenced_l(silenced);
11140 broadcast_l();
11141 }
11142 }
jiabin09609032022-06-15 19:26:01 +000011143 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011144}
11145
Andy Hungee58e4a2023-07-07 13:47:37 -070011146void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011147{
11148 MmapThread::toAudioPortConfig(config);
11149 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11150 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11151 config->flags.input = mInput->flags;
11152 }
11153}
11154
Andy Hungee58e4a2023-07-07 13:47:37 -070011155status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011156 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011157{
11158 if (mInput == nullptr) {
11159 return NO_INIT;
11160 }
11161 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11162}
11163
jiabinc658e452022-10-21 20:52:21 +000011164// ----------------------------------------------------------------------------
11165
Andy Hungee58e4a2023-07-07 13:47:37 -070011166/* static */
11167sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011168 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011169 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011170 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011171}
11172
Andy Hung583043b2023-07-17 17:05:00 -070011173BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011174 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011175 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011176
Andy Hungee58e4a2023-07-07 13:47:37 -070011177PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011178 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011179 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11180 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011181 float volumeLeft = 1.0f;
11182 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011183 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11184 const int trackId = mActiveTracks[0]->id();
11185 mAudioMixer->setParameter(
11186 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11187 mAudioMixer->setParameter(
11188 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11189 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011190 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011191 mIsBitPerfect = true;
11192 } else {
11193 mIsBitPerfect = false;
11194 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11195 // active.
11196 for (const auto& track : mActiveTracks) {
11197 const int trackId = track->id();
11198 mAudioMixer->setParameter(
11199 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11200 }
11201 }
jiabin76d94692022-12-15 21:51:21 +000011202 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11203 mVolumeLeft = volumeLeft;
11204 mVolumeRight = volumeRight;
11205 setVolumeForOutput_l(volumeLeft, volumeRight);
11206 }
jiabinc658e452022-10-21 20:52:21 +000011207 return result;
11208}
11209
Andy Hungee58e4a2023-07-07 13:47:37 -070011210void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011211 MixerThread::threadLoop_mix();
11212 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11213}
11214
Glenn Kasten63238ef2015-03-02 15:50:29 -080011215} // namespace android