blob: dc90ef5953dad188ad59701c192bed2a994d8de3 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Andy Hung409572b2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
36#ifdef DEBUG_CPU_USAGE
37#include <audio_utils/Statistics.h>
38#include <cpustats/ThreadCpuUsage.h>
39#endif
40#include <audio_utils/channels.h>
41#include <audio_utils/format.h>
42#include <audio_utils/minifloat.h>
43#include <audio_utils/mono_blend.h>
44#include <audio_utils/primitives.h>
45#include <audio_utils/safe_math.h>
46#include <audiomanager/AudioManager.h>
47#include <binder/IPCThreadState.h>
48#include <binder/IServiceManager.h>
49#include <binder/PersistableBundle.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070050#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <cutils/properties.h>
Andy Hung409572b2023-07-19 12:47:35 -070052#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070053#include <media/AudioContainers.h>
54#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070055#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070056#include <media/AudioResamplerPublic.h>
Andy Hung409572b2023-07-19 12:47:35 -070057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080062#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070063#include <media/TypeConverter.h>
Andy Hung409572b2023-07-19 12:47:35 -070064#include <media/audiohal/EffectsFactoryHalInterface.h>
65#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070066#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080067#include <media/nbaio/AudioStreamOutSink.h>
68#include <media/nbaio/MonoPipe.h>
69#include <media/nbaio/MonoPipeReader.h>
70#include <media/nbaio/Pipe.h>
71#include <media/nbaio/PipeReader.h>
72#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080073#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070074#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070075#include <mediautils/SchedulingPolicyService.h>
76#include <mediautils/ServiceUtilities.h>
Andy Hung409572b2023-07-19 12:47:35 -070077#include <powermanager/PowerManager.h>
78#include <private/android_filesystem_config.h>
79#include <private/media/AudioTrackShared.h>
80#include <system/audio_effects/effect_aec.h>
81#include <system/audio_effects/effect_downmix.h>
82#include <system/audio_effects/effect_ns.h>
83#include <system/audio_effects/effect_spatializer.h>
84#include <utils/Log.h>
85#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080086
Andy Hung409572b2023-07-19 12:47:35 -070087#include <fcntl.h>
88#include <linux/futex.h>
89#include <math.h>
90#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080091#include <pthread.h>
Andy Hung409572b2023-07-19 12:47:35 -070092#include <sstream>
93#include <string>
94#include <sys/stat.h>
95#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096
Eric Laurent81784c32012-11-19 14:55:58 -080097// ----------------------------------------------------------------------------
98
99// Note: the following macro is used for extremely verbose logging message. In
100// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
101// 0; but one side effect of this is to turn all LOGV's as well. Some messages
102// are so verbose that we want to suppress them even when we have ALOG_ASSERT
103// turned on. Do not uncomment the #def below unless you really know what you
104// are doing and want to see all of the extremely verbose messages.
105//#define VERY_VERY_VERBOSE_LOGGING
106#ifdef VERY_VERY_VERBOSE_LOGGING
107#define ALOGVV ALOGV
108#else
109#define ALOGVV(a...) do { } while(0)
110#endif
111
Andy Hung6770c6f2015-04-07 13:43:36 -0700112// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700113#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115template <typename T>
116static inline T min(const T& a, const T& b)
117{
118 return a < b ? a : b;
119}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700120
Eric Laurent81784c32012-11-19 14:55:58 -0800121namespace android {
122
Andy Hung4b17e882023-07-07 13:47:37 -0700123using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700124using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000125using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700126
Andy Hung409572b2023-07-19 12:47:35 -0700127// Keep in sync with java definition in media/java/android/media/AudioRecord.java
128static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// retry counts for buffer fill timeout
131// 50 * ~20msecs = 1 second
132static const int8_t kMaxTrackRetries = 50;
133static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// allow less retry attempts on direct output thread.
136// direct outputs can be a scarce resource in audio hardware and should
137// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700138// Notes:
139// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
140// in case the data write is bursty for the AudioTrack. The application
141// should endeavor to write at least once every kMaxTrackRetriesDirectMs
142// to prevent an underrun situation. If the data is bursty, then
143// the application can also throttle the data sent to be even.
144// 2) For compressed audio data, any data present in the AudioTrack buffer
145// will be sent and reset the retry count. This delivers data as
146// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
147// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
148// of data to be available, then any remaining data is delivered.
149// This is required to ensure the last bit of data is delivered before underrun.
150//
151// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
152// or the size of the HAL period for proportional / linear PCM tracks.
153static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800154
155// don't warn about blocked writes or record buffer overflows more often than this
156static const nsecs_t kWarningThrottleNs = seconds(5);
157
158// RecordThread loop sleep time upon application overrun or audio HAL read error
159static const int kRecordThreadSleepUs = 5000;
160
Eric Laurent10351942014-05-08 18:49:52 -0700161// maximum time to wait in sendConfigEvent_l() for a status to be received
162static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// minimum sleep time for the mixer thread loop when tracks are active but in underrun
165static const uint32_t kMinThreadSleepTimeUs = 5000;
166// maximum divider applied to the active sleep time in the mixer thread loop
167static const uint32_t kMaxThreadSleepTimeShift = 2;
168
Andy Hung09a50072014-02-27 14:30:47 -0800169// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700170// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800171static const uint32_t kMinNormalSinkBufferSizeMs = 20;
172// maximum normal sink buffer size
173static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700175// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
176// FIXME This should be based on experimentally observed scheduling jitter
177static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
178
Eric Laurent972a1732013-09-04 09:42:59 -0700179// Offloaded output thread standby delay: allows track transition without going to standby
180static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
181
Eric Laurent51716182016-02-29 18:00:56 -0800182// Direct output thread minimum sleep time in idle or active(underrun) state
183static const nsecs_t kDirectMinSleepTimeUs = 10000;
184
Brian Lindahl65e90012022-07-27 18:01:07 +0200185// Minimum amount of time between checking to see if the timestamp is advancing
186// for underrun detection. If we check too frequently, we may not detect a
187// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800188static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200189
Glenn Kasten1b291842016-07-18 14:55:21 -0700190// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
191// balance between power consumption and latency, and allows threads to be scheduled reliably
192// by the CFS scheduler.
193// FIXME Express other hardcoded references to 20ms with references to this constant and move
194// it appropriately.
195#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800196
Eric Laurent81784c32012-11-19 14:55:58 -0800197// Whether to use fast mixer
198static const enum {
199 FastMixer_Never, // never initialize or use: for debugging only
200 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
201 // normal mixer multiplier is 1
202 FastMixer_Static, // initialize if needed, then use all the time if initialized,
203 // multiplier is calculated based on min & max normal mixer buffer size
204 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 // FIXME for FastMixer_Dynamic:
207 // Supporting this option will require fixing HALs that can't handle large writes.
208 // For example, one HAL implementation returns an error from a large write,
209 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
210 // We could either fix the HAL implementations, or provide a wrapper that breaks
211 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
212} kUseFastMixer = FastMixer_Static;
213
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700214// Whether to use fast capture
215static const enum {
216 FastCapture_Never, // never initialize or use: for debugging only
217 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
218 FastCapture_Static, // initialize if needed, then use all the time if initialized
219} kUseFastCapture = FastCapture_Static;
220
Eric Laurent81784c32012-11-19 14:55:58 -0800221// Priorities for requestPriority
222static const int kPriorityAudioApp = 2;
223static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700224static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800225
Glenn Kastenea38ee72016-04-18 11:08:01 -0700226// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
227// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
228// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700229
230// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800231static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800232
Glenn Kasten03490092014-05-27 12:30:54 -0700233// The minimum and maximum allowed values
234static const int kFastTrackMultiplierMin = 1;
235static const int kFastTrackMultiplierMax = 2;
236
237// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
238static int sFastTrackMultiplier = kFastTrackMultiplier;
239
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700240// See Thread::readOnlyHeap().
241// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
242// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
243// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700244static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700245
Andy Hung409572b2023-07-19 12:47:35 -0700246static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hungd58c4732023-07-20 21:31:38 -0700247
248static nsecs_t getStandbyTimeInNanos() {
249 static nsecs_t standbyTimeInNanos = []() {
250 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
251 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
252 ALOGI("%s: Using %d ms as standby time", __func__, ms);
253 return milliseconds(ms);
254 }();
255 return standbyTimeInNanos;
256}
257
Andy Hungd21a2ab2023-07-20 21:44:14 -0700258// Set kEnableExtendedChannels to true to enable greater than stereo output
259// for the MixerThread and device sink. Number of channels allowed is
260// FCC_2 <= channels <= FCC_LIMIT.
261constexpr bool kEnableExtendedChannels = true;
262
263// Returns true if channel mask is permitted for the PCM sink in the MixerThread
264/* static */
265bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
266 switch (audio_channel_mask_get_representation(channelMask)) {
267 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
268 // Haptic channel mask is only applicable for channel position mask.
269 const uint32_t channelCount = audio_channel_count_from_out_mask(
270 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
271 const uint32_t maxChannelCount = kEnableExtendedChannels
272 ? FCC_LIMIT : FCC_2;
273 if (channelCount < FCC_2 // mono is not supported at this time
274 || channelCount > maxChannelCount) {
275 return false;
276 }
277 // check that channelMask is the "canonical" one we expect for the channelCount.
278 return audio_channel_position_mask_is_out_canonical(channelMask);
279 }
280 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
281 if (kEnableExtendedChannels) {
282 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
283 if (channelCount >= FCC_2 // mono is not supported at this time
284 && channelCount <= FCC_LIMIT) {
285 return true;
286 }
287 }
288 return false;
289 default:
290 return false;
291 }
292}
293
294// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
295constexpr bool kEnableExtendedPrecision = true;
296
297// Returns true if format is permitted for the PCM sink in the MixerThread
298/* static */
299bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
300 switch (format) {
301 case AUDIO_FORMAT_PCM_16_BIT:
302 return true;
303 case AUDIO_FORMAT_PCM_FLOAT:
304 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
305 case AUDIO_FORMAT_PCM_32_BIT:
306 case AUDIO_FORMAT_PCM_8_24_BIT:
307 return kEnableExtendedPrecision;
308 default:
309 return false;
310 }
311}
312
Eric Laurent81784c32012-11-19 14:55:58 -0800313// ----------------------------------------------------------------------------
314
Andy Hung409572b2023-07-19 12:47:35 -0700315// formatToString() needs to be exact for MediaMetrics purposes.
316// Do not use media/TypeConverter.h toString().
317/* static */
318std::string IAfThreadBase::formatToString(audio_format_t format) {
319 std::string result;
320 FormatConverter::toString(format, result);
321 return result;
322}
323
Andy Hungb68f5eb2019-12-03 16:49:17 -0800324// TODO: move all toString helpers to audio.h
325// under #ifdef __cplusplus #endif
326static std::string patchSinksToString(const struct audio_patch *patch)
327{
328 std::stringstream ss;
329 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700330 if (i > 0) {
331 ss << "|";
332 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800333 ss << "(" << toString(patch->sinks[i].ext.device.type)
334 << ", " << patch->sinks[i].ext.device.address << ")";
335 }
336 return ss.str();
337}
338
339static std::string patchSourcesToString(const struct audio_patch *patch)
340{
341 std::stringstream ss;
342 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700343 if (i > 0) {
344 ss << "|";
345 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800346 ss << "(" << toString(patch->sources[i].ext.device.type)
347 << ", " << patch->sources[i].ext.device.address << ")";
348 }
349 return ss.str();
350}
351
Andy Hung4bd53e72022-11-17 17:21:45 -0800352static std::string toString(audio_latency_mode_t mode) {
353 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000354 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
355 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800356}
357
358// Could be made a template, but other toString overloads for std::vector are confused.
359static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
360 std::string s("{ ");
361 for (const auto& e : elements) {
362 s.append(toString(e));
363 s.append(" ");
364 }
365 s.append("}");
366 return s;
367}
368
Glenn Kasten03490092014-05-27 12:30:54 -0700369static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
370
371static void sFastTrackMultiplierInit()
372{
373 char value[PROPERTY_VALUE_MAX];
374 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
375 char *endptr;
376 unsigned long ul = strtoul(value, &endptr, 0);
377 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
378 sFastTrackMultiplier = (int) ul;
379 }
380 }
381}
382
383// ----------------------------------------------------------------------------
384
Eric Laurent81784c32012-11-19 14:55:58 -0800385#ifdef ADD_BATTERY_DATA
386// To collect the amplifier usage
387static void addBatteryData(uint32_t params) {
388 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
389 if (service == NULL) {
390 // it already logged
391 return;
392 }
393
394 service->addBatteryData(params);
395}
396#endif
397
Andy Hung3f0c9022016-01-15 17:49:46 -0800398// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
399struct {
400 // call when you acquire a partial wakelock
401 void acquire(const sp<IBinder> &wakeLockToken) {
402 pthread_mutex_lock(&mLock);
403 if (wakeLockToken.get() == nullptr) {
404 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
405 } else {
406 if (mCount == 0) {
407 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
408 }
409 ++mCount;
410 }
411 pthread_mutex_unlock(&mLock);
412 }
413
414 // call when you release a partial wakelock.
415 void release(const sp<IBinder> &wakeLockToken) {
416 if (wakeLockToken.get() == nullptr) {
417 return;
418 }
419 pthread_mutex_lock(&mLock);
420 if (--mCount < 0) {
421 ALOGE("negative wakelock count");
422 mCount = 0;
423 }
424 pthread_mutex_unlock(&mLock);
425 }
426
427 // retrieves the boottime timebase offset from monotonic.
428 int64_t getBoottimeOffset() {
429 pthread_mutex_lock(&mLock);
430 int64_t boottimeOffset = mBoottimeOffset;
431 pthread_mutex_unlock(&mLock);
432 return boottimeOffset;
433 }
434
435 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
436 // and the selected timebase.
437 // Currently only TIMEBASE_BOOTTIME is allowed.
438 //
439 // This only needs to be called upon acquiring the first partial wakelock
440 // after all other partial wakelocks are released.
441 //
442 // We do an empirical measurement of the offset rather than parsing
443 // /proc/timer_list since the latter is not a formal kernel ABI.
444 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
445 int clockbase;
446 switch (timebase) {
447 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
448 clockbase = SYSTEM_TIME_BOOTTIME;
449 break;
450 default:
451 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
452 break;
453 }
454 // try three times to get the clock offset, choose the one
455 // with the minimum gap in measurements.
456 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700457 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800458 for (int i = 0; i < tries; ++i) {
459 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
460 const nsecs_t tbase = systemTime(clockbase);
461 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
462 const nsecs_t gap = tmono2 - tmono;
463 if (i == 0 || gap < bestGap) {
464 bestGap = gap;
465 measured = tbase - ((tmono + tmono2) >> 1);
466 }
467 }
468
469 // to avoid micro-adjusting, we don't change the timebase
470 // unless it is significantly different.
471 //
472 // Assumption: It probably takes more than toleranceNs to
473 // suspend and resume the device.
474 static int64_t toleranceNs = 10000; // 10 us
475 if (llabs(*offset - measured) > toleranceNs) {
476 ALOGV("Adjusting timebase offset old: %lld new: %lld",
477 (long long)*offset, (long long)measured);
478 *offset = measured;
479 }
480 }
481
482 pthread_mutex_t mLock;
483 int32_t mCount;
484 int64_t mBoottimeOffset;
485} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800486
487// ----------------------------------------------------------------------------
488// CPU Stats
489// ----------------------------------------------------------------------------
490
491class CpuStats {
492public:
493 CpuStats();
494 void sample(const String8 &title);
495#ifdef DEBUG_CPU_USAGE
496private:
497 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700498 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800499
Andy Hung16698b82018-08-01 10:48:38 -0700500 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800501
502 int mCpuNum; // thread's current CPU number
503 int mCpukHz; // frequency of thread's current CPU in kHz
504#endif
505};
506
507CpuStats::CpuStats()
508#ifdef DEBUG_CPU_USAGE
509 : mCpuNum(-1), mCpukHz(-1)
510#endif
511{
512}
513
Glenn Kasten0f11b512014-01-31 16:18:54 -0800514void CpuStats::sample(const String8 &title
515#ifndef DEBUG_CPU_USAGE
516 __unused
517#endif
518 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800519#ifdef DEBUG_CPU_USAGE
520 // get current thread's delta CPU time in wall clock ns
521 double wcNs;
522 bool valid = mCpuUsage.sampleAndEnable(wcNs);
523
524 // record sample for wall clock statistics
525 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700526 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800527 }
528
529 // get the current CPU number
530 int cpuNum = sched_getcpu();
531
532 // get the current CPU frequency in kHz
533 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
534
535 // check if either CPU number or frequency changed
536 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
537 mCpuNum = cpuNum;
538 mCpukHz = cpukHz;
539 // ignore sample for purposes of cycles
540 valid = false;
541 }
542
543 // if no change in CPU number or frequency, then record sample for cycle statistics
544 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700545 const double cycles = wcNs * cpukHz * 0.000001;
546 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800547 }
548
Eric Tan5b13ff82018-07-27 11:20:17 -0700549 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800550 // mCpuUsage.elapsed() is expensive, so don't call it every loop
551 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700552 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800553 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700554 const double perLoop = elapsed / (double) n;
555 const double perLoop100 = perLoop * 0.01;
556 const double perLoop1k = perLoop * 0.001;
557 const double mean = mWcStats.getMean();
558 const double stddev = mWcStats.getStdDev();
559 const double minimum = mWcStats.getMin();
560 const double maximum = mWcStats.getMax();
561 const double meanCycles = mHzStats.getMean();
562 const double stddevCycles = mHzStats.getStdDev();
563 const double minCycles = mHzStats.getMin();
564 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800565 mCpuUsage.resetElapsed();
566 mWcStats.reset();
567 mHzStats.reset();
568 ALOGD("CPU usage for %s over past %.1f secs\n"
569 " (%u mixer loops at %.1f mean ms per loop):\n"
570 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
571 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
572 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000573 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800574 elapsed * .000000001, n, perLoop * .000001,
575 mean * .001,
576 stddev * .001,
577 minimum * .001,
578 maximum * .001,
579 mean / perLoop100,
580 stddev / perLoop100,
581 minimum / perLoop100,
582 maximum / perLoop100,
583 meanCycles / perLoop1k,
584 stddevCycles / perLoop1k,
585 minCycles / perLoop1k,
586 maxCycles / perLoop1k);
587
588 }
589 }
590#endif
591};
592
593// ----------------------------------------------------------------------------
594// ThreadBase
595// ----------------------------------------------------------------------------
596
Glenn Kasten97b7b752014-09-28 13:04:24 -0700597// static
Andy Hung4b17e882023-07-07 13:47:37 -0700598const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700599{
600 switch (type) {
601 case MIXER:
602 return "MIXER";
603 case DIRECT:
604 return "DIRECT";
605 case DUPLICATING:
606 return "DUPLICATING";
607 case RECORD:
608 return "RECORD";
609 case OFFLOAD:
610 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700611 case MMAP_PLAYBACK:
612 return "MMAP_PLAYBACK";
613 case MMAP_CAPTURE:
614 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200615 case SPATIALIZER:
616 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000617 case BIT_PERFECT:
618 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700619 default:
620 return "unknown";
621 }
622}
623
Andy Hung7535ed92023-07-17 17:05:00 -0700624ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700625 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800626 : Thread(false /*canCallJava*/),
627 mType(type),
Andy Hung7535ed92023-07-17 17:05:00 -0700628 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700629 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
630 isOut),
631 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700632 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800633 // are set by PlaybackThread::readOutputParameters_l() or
634 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700635 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700636 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700637 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800638 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700639 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800640 mSystemReady(systemReady),
641 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800642{
Andy Hungcf10d742020-04-28 15:38:24 -0700643 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700644 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800645}
646
Andy Hung4b17e882023-07-07 13:47:37 -0700647ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800648{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700649 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700650 mConfigEvents.clear();
651
Eric Laurent81784c32012-11-19 14:55:58 -0800652 // do not lock the mutex in destructor
653 releaseWakeLock_l();
654 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800655 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800656 binder->unlinkToDeath(mDeathRecipient);
657 }
Andy Hungd0979812019-02-21 15:51:44 -0800658
659 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800660}
661
Andy Hung4b17e882023-07-07 13:47:37 -0700662status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700663{
664 status_t status = initCheck();
665 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800666 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700667 } else {
668 ALOGE("No working audio driver found.");
669 }
670 return status;
671}
672
Andy Hung4b17e882023-07-07 13:47:37 -0700673void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800674{
675 ALOGV("ThreadBase::exit");
676 // do any cleanup required for exit to succeed
677 preExit();
678 {
679 // This lock prevents the following race in thread (uniprocessor for illustration):
680 // if (!exitPending()) {
681 // // context switch from here to exit()
682 // // exit() calls requestExit(), what exitPending() observes
683 // // exit() calls signal(), which is dropped since no waiters
684 // // context switch back from exit() to here
685 // mWaitWorkCV.wait(...);
686 // // now thread is hung
687 // }
Andy Hungb17d24b2023-08-29 14:26:09 -0700688 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800689 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -0700690 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800691 }
692 // When Thread::requestExitAndWait is made virtual and this method is renamed to
693 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
694 requestExitAndWait();
695}
696
Andy Hung4b17e882023-07-07 13:47:37 -0700697status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800698{
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000699 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hungf8635b62023-08-31 16:13:39 -0700700 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800701
Eric Laurent10351942014-05-08 18:49:52 -0700702 return sendSetParameterConfigEvent_l(keyValuePairs);
703}
704
705// sendConfigEvent_l() must be called with ThreadBase::mLock held
706// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung4b17e882023-07-07 13:47:37 -0700707status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700708NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700709{
710 status_t status = NO_ERROR;
711
Eric Laurent72e3f392015-05-20 14:43:50 -0700712 if (event->mRequiresSystemReady && !mSystemReady) {
713 event->mWaitStatus = false;
714 mPendingConfigEvents.add(event);
715 return status;
716 }
Eric Laurent10351942014-05-08 18:49:52 -0700717 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700718 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungb17d24b2023-08-29 14:26:09 -0700719 mWaitWorkCV.notify_one();
720 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700721 {
Andy Hungb17d24b2023-08-29 14:26:09 -0700722 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700723 while (event->mWaitStatus) {
Andy Hung5529c132024-01-25 17:02:30 -0800724 if (event->mCondition.wait_for(
725 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
726 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700727 event->mStatus = TIMED_OUT;
728 event->mWaitStatus = false;
729 }
730 }
731 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800732 }
Andy Hungb17d24b2023-08-29 14:26:09 -0700733 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800734 return status;
735}
736
Andy Hung4b17e882023-07-07 13:47:37 -0700737void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700738 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800739{
Andy Hungf8635b62023-08-31 16:13:39 -0700740 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700741 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800742}
743
Andy Hungb17d24b2023-08-29 14:26:09 -0700744// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700745void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700746 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800747{
Andy Hungd0979812019-02-21 15:51:44 -0800748 // The audio statistics history is exponentially weighted to forget events
749 // about five or more seconds in the past. In order to have
750 // crisper statistics for mediametrics, we reset the statistics on
751 // an IoConfigEvent, to reflect different properties for a new device.
752 mIoJitterMs.reset();
753 mLatencyMs.reset();
754 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000755 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100756 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800757
Eric Laurent09f1ed22019-04-24 17:45:17 -0700758 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700759 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800760}
761
Andy Hung4b17e882023-07-07 13:47:37 -0700762void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700763{
Andy Hungf8635b62023-08-31 16:13:39 -0700764 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800765 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700766}
767
Andy Hungb17d24b2023-08-29 14:26:09 -0700768// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700769void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800770 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800771{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800772 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700773 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800774}
775
Andy Hungb17d24b2023-08-29 14:26:09 -0700776// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700777status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800778{
Andy Hung2ddee192015-12-18 17:34:44 -0800779 sp<ConfigEvent> configEvent;
780 AudioParameter param(keyValuePair);
781 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700782 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800783 setMasterMono_l(value != 0);
784 if (param.size() == 1) {
785 return NO_ERROR; // should be a solo parameter - we don't pass down
786 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700787 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800788 configEvent = new SetParameterConfigEvent(param.toString());
789 } else {
790 configEvent = new SetParameterConfigEvent(keyValuePair);
791 }
Eric Laurent10351942014-05-08 18:49:52 -0700792 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700793}
794
Andy Hung4b17e882023-07-07 13:47:37 -0700795status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700796 const struct audio_patch *patch,
797 audio_patch_handle_t *handle)
798{
Andy Hungf8635b62023-08-31 16:13:39 -0700799 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
801 status_t status = sendConfigEvent_l(configEvent);
802 if (status == NO_ERROR) {
803 CreateAudioPatchConfigEventData *data =
804 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
805 *handle = data->mHandle;
806 }
807 return status;
808}
809
Andy Hung4b17e882023-07-07 13:47:37 -0700810status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700811 const audio_patch_handle_t handle)
812{
Andy Hungf8635b62023-08-31 16:13:39 -0700813 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
815 return sendConfigEvent_l(configEvent);
816}
817
Andy Hung4b17e882023-07-07 13:47:37 -0700818status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700819 const DeviceDescriptorBaseVector& outDevices)
820{
821 if (type() != RECORD) {
822 // The update out device operation is only for record thread.
823 return INVALID_OPERATION;
824 }
Andy Hungf8635b62023-08-31 16:13:39 -0700825 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700826 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
827 return sendConfigEvent_l(configEvent);
828}
829
Andy Hung4b17e882023-07-07 13:47:37 -0700830void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200831{
832 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
833 sp<ConfigEvent> configEvent =
834 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
835 sendConfigEvent_l(configEvent);
836}
Eric Laurent1c333e22014-05-20 10:48:17 -0700837
Andy Hung4b17e882023-07-07 13:47:37 -0700838void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200839{
Andy Hungf8635b62023-08-31 16:13:39 -0700840 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200841 sendCheckOutputStageEffectsEvent_l();
842}
843
Andy Hung4b17e882023-07-07 13:47:37 -0700844void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200845{
846 sp<ConfigEvent> configEvent =
847 (ConfigEvent *)new CheckOutputStageEffectsEvent();
848 sendConfigEvent_l(configEvent);
849}
850
Andy Hung4b17e882023-07-07 13:47:37 -0700851void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200852{
853 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
854 sendConfigEvent_l(configEvent);
855}
856
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700857// post condition: mConfigEvents.isEmpty()
Andy Hung4b17e882023-07-07 13:47:37 -0700858void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700859{
Eric Laurent10351942014-05-08 18:49:52 -0700860 bool configChanged = false;
861
Eric Laurent81784c32012-11-19 14:55:58 -0800862 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700863 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700864 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800865 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700866 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700867 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700868 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
869 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800870 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700871 true /*asynchronous*/);
872 if (err != 0) {
873 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700874 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700875 }
876 } break;
877 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700878 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hung94dfbb42023-09-06 19:41:47 -0700879 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700880 } break;
881 case CFG_EVENT_SET_PARAMETER: {
882 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
883 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
884 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700885 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000886 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700887 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700888 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700889 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700890 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700891 CreateAudioPatchConfigEventData *data =
892 (CreateAudioPatchConfigEventData *)event->mData.get();
893 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700894 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200895 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700896 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
897 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
898 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700899 } break;
900 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700901 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 ReleaseAudioPatchConfigEventData *data =
903 (ReleaseAudioPatchConfigEventData *)event->mData.get();
904 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700905 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200906 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700907 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
908 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
909 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
910 } break;
911 case CFG_EVENT_UPDATE_OUT_DEVICE: {
912 UpdateOutDevicesConfigEventData *data =
913 (UpdateOutDevicesConfigEventData *)event->mData.get();
914 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700915 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200916 case CFG_EVENT_RESIZE_BUFFER: {
917 ResizeBufferConfigEventData *data =
918 (ResizeBufferConfigEventData *)event->mData.get();
919 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
920 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200921
922 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
923 setCheckOutputStageEffects();
924 } break;
925
Eric Laurent68a40a82022-05-03 18:15:04 +0200926 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
927 onHalLatencyModesChanged_l();
928 } break;
929
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700930 default:
Eric Laurent10351942014-05-08 18:49:52 -0700931 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700932 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800933 }
Eric Laurent10351942014-05-08 18:49:52 -0700934 {
Andy Hungf8635b62023-08-31 16:13:39 -0700935 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700936 if (event->mWaitStatus) {
937 event->mWaitStatus = false;
Andy Hungb17d24b2023-08-29 14:26:09 -0700938 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700939 }
940 }
941 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
942 }
943
944 if (configChanged) {
945 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800946 }
Eric Laurent81784c32012-11-19 14:55:58 -0800947}
948
Marco Nelissenb2208842014-02-07 14:00:50 -0800949String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
950 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700951 const audio_channel_representation_t representation =
952 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700953
954 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800955 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700956 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
957 if (output) {
958 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
959 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
960 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700961 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700962 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
963 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
964 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
965 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
966 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
967 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
968 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
969 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
970 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700974 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
978 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
979 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
980 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700981 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700982 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
983 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700984 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
985 } else {
986 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
987 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
988 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
989 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
990 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
991 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
992 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
993 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
994 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
995 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
996 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
997 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700998 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
999 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1000 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001001 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001002 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1003 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001004 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1005 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1006 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1007 }
1008 const int len = s.length();
1009 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001010 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001011 s.unlockBuffer(len - 2); // remove trailing ", "
1012 }
1013 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001014 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001015 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1016 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1017 return s;
1018 default:
1019 s.appendFormat("unknown mask, representation:%d bits:%#x",
1020 representation, audio_channel_mask_get_bits(mask));
1021 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001022 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001023}
1024
Andy Hung4b17e882023-07-07 13:47:37 -07001025void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001026NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001027{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001028 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1029 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1030
Andy Hungb17d24b2023-08-29 14:26:09 -07001031 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001032 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001033 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001034 }
1035
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001036 dumpBase_l(fd, args);
1037 dumpInternals_l(fd, args);
1038 dumpTracks_l(fd, args);
1039 dumpEffectChains_l(fd, args);
1040
1041 if (locked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001042 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001043 }
1044
1045 dprintf(fd, " Local log:\n");
1046 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001047
1048 // --all does the statistics
1049 bool dumpAll = false;
1050 for (const auto &arg : args) {
1051 if (arg == String16("--all")) {
1052 dumpAll = true;
1053 }
1054 }
1055 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001056 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001057 if (!sched.empty()) {
1058 (void)write(fd, sched.c_str(), sched.size());
1059 }
1060 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001061}
1062
Andy Hung4b17e882023-07-07 13:47:37 -07001063void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001064{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001065 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001066 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001067 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001068 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung409572b2023-07-19 12:47:35 -07001069 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1070 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001071 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001072 dprintf(fd, " Channel count: %u\n", mChannelCount);
1073 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001074 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung409572b2023-07-19 12:47:35 -07001075 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1076 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001077 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001078 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001079 size_t numConfig = mConfigEvents.size();
1080 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001081 const size_t SIZE = 256;
1082 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001083 for (size_t i = 0; i < numConfig; i++) {
1084 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001085 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001086 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001087 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001088 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001089 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001090 }
Andy Hung293558a2017-03-21 12:19:20 -07001091 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001092 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001093 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001094 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001095 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001096 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001097
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001098 // Dump timestamp statistics for the Thread types that support it.
1099 if (mType == RECORD
1100 || mType == MIXER
1101 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001102 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001103 || mType == OFFLOAD
1104 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001105 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hung94dfbb42023-09-06 19:41:47 -07001106 dprintf(fd, " Timestamp corrected: %s\n",
1107 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001108 }
1109
Andy Hung446f4df2019-02-21 12:26:41 -08001110 if (mLastIoBeginNs > 0) { // MMAP may not set this
1111 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1112 isOutput() ? "write" : "read",
1113 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1114 }
1115
1116 if (mProcessTimeMs.getN() > 0) {
1117 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1118 }
1119
1120 if (mIoJitterMs.getN() > 0) {
1121 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1122 isOutput() ? "write" : "read",
1123 mIoJitterMs.toString().c_str());
1124 }
1125
Andy Hunge6c37112019-02-26 17:38:10 -08001126 if (mLatencyMs.getN() > 0) {
1127 dprintf(fd, " Threadloop %s latency stats: %s\n",
1128 isOutput() ? "write" : "read",
1129 mLatencyMs.toString().c_str());
1130 }
Robert Wu06db0a32021-08-10 19:05:34 +00001131
1132 if (mMonopipePipeDepthStats.getN() > 0) {
1133 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1134 isOutput() ? "write" : "read",
1135 mMonopipePipeDepthStats.toString().c_str());
1136 }
Eric Laurent81784c32012-11-19 14:55:58 -08001137}
1138
Andy Hung4b17e882023-07-07 13:47:37 -07001139void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001140{
1141 const size_t SIZE = 256;
1142 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001143
Marco Nelissenb2208842014-02-07 14:00:50 -08001144 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001145 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001146 write(fd, buffer, strlen(buffer));
1147
Marco Nelissenb2208842014-02-07 14:00:50 -08001148 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001149 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001150 if (chain != 0) {
1151 chain->dump(fd, args);
1152 }
1153 }
1154}
1155
Andy Hung4b17e882023-07-07 13:47:37 -07001156void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001157{
Andy Hungf8635b62023-08-31 16:13:39 -07001158 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001159 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001160}
1161
Andy Hung4b17e882023-07-07 13:47:37 -07001162String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001163{
1164 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001165 case MIXER:
1166 return String16("AudioMix");
1167 case DIRECT:
1168 return String16("AudioDirectOut");
1169 case DUPLICATING:
1170 return String16("AudioDup");
1171 case RECORD:
1172 return String16("AudioIn");
1173 case OFFLOAD:
1174 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001175 case MMAP_PLAYBACK:
1176 return String16("MmapPlayback");
1177 case MMAP_CAPTURE:
1178 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001179 case SPATIALIZER:
1180 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001181 default:
1182 ALOG_ASSERT(false);
1183 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001184 }
1185}
1186
Andy Hung4b17e882023-07-07 13:47:37 -07001187void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001188{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001189 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001190 if (mPowerManager != 0) {
1191 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001192 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001193 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1194 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001195 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001196 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001197 {} /* workSource */,
1198 {} /* historyTag */);
1199 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001200 mWakeLockToken = binder;
1201 }
Chris Ye6597d732020-02-28 22:38:25 -08001202 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001203 }
Wei Jia3f273d12015-11-24 09:06:49 -08001204
Andy Hung3f0c9022016-01-15 17:49:46 -08001205 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001206 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1207 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001208}
1209
Andy Hung4b17e882023-07-07 13:47:37 -07001210void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001211{
Andy Hungf8635b62023-08-31 16:13:39 -07001212 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001213 releaseWakeLock_l();
1214}
1215
Andy Hung4b17e882023-07-07 13:47:37 -07001216void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001217{
Andy Hung3f0c9022016-01-15 17:49:46 -08001218 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001219 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001220 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001221 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001222 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001223 }
1224 mWakeLockToken.clear();
1225 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001226}
1227
Andy Hung4b17e882023-07-07 13:47:37 -07001228void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001229 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001230 // use checkService() to avoid blocking if power service is not up yet
1231 sp<IBinder> binder =
1232 defaultServiceManager()->checkService(String16("power"));
1233 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001234 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001235 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001236 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001237 binder->linkToDeath(mDeathRecipient);
1238 }
1239 }
1240}
1241
Andy Hung4b17e882023-07-07 13:47:37 -07001242void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001243 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001244
1245#if !LOG_NDEBUG
1246 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001247 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001248 s << uid << " ";
1249 }
1250 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1251#endif
1252
Andy Hung438e7572015-12-14 15:51:17 -08001253 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1254 if (mSystemReady) {
1255 ALOGE("no wake lock to update, but system ready!");
1256 } else {
1257 ALOGW("no wake lock to update, system not ready yet");
1258 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001259 return;
1260 }
1261 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001262 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001263 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1264 mWakeLockToken, uidsAsInt);
1265 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001266 }
1267}
1268
Andy Hung4b17e882023-07-07 13:47:37 -07001269void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001270{
Andy Hungf8635b62023-08-31 16:13:39 -07001271 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001272 releaseWakeLock_l();
1273 mPowerManager.clear();
1274}
1275
Andy Hung4b17e882023-07-07 13:47:37 -07001276void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001277 const DeviceDescriptorBaseVector& outDevices __unused)
1278{
1279 ALOGE("%s should only be called in RecordThread", __func__);
1280}
1281
Andy Hung4b17e882023-07-07 13:47:37 -07001282void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001283{
1284 ALOGE("%s should only be called in RecordThread", __func__);
1285}
1286
Andy Hung4b17e882023-07-07 13:47:37 -07001287void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001288{
1289 sp<ThreadBase> thread = mThread.promote();
1290 if (thread != 0) {
1291 thread->clearPowerManager();
1292 }
1293 ALOGW("power manager service died !!!");
1294}
1295
Andy Hung4b17e882023-07-07 13:47:37 -07001296void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001297 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001298{
Andy Hung116bc262023-06-20 18:56:17 -07001299 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001300 if (chain != 0) {
1301 if (type != NULL) {
1302 chain->setEffectSuspended_l(type, suspend);
1303 } else {
1304 chain->setEffectSuspendedAll_l(suspend);
1305 }
1306 }
1307
1308 updateSuspendedSessions_l(type, suspend, sessionId);
1309}
1310
Andy Hung4b17e882023-07-07 13:47:37 -07001311void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001312{
1313 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1314 if (index < 0) {
1315 return;
1316 }
1317
1318 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1319 mSuspendedSessions.valueAt(index);
1320
1321 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001322 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001323 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001324 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001325 chain->setEffectSuspendedAll_l(true);
1326 } else {
1327 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1328 desc->mType.timeLow);
1329 chain->setEffectSuspended_l(&desc->mType, true);
1330 }
1331 }
1332 }
1333}
1334
Andy Hung4b17e882023-07-07 13:47:37 -07001335void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001336 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001337 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001338{
1339 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1340
1341 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1342
1343 if (suspend) {
1344 if (index >= 0) {
1345 sessionEffects = mSuspendedSessions.valueAt(index);
1346 } else {
1347 mSuspendedSessions.add(sessionId, sessionEffects);
1348 }
1349 } else {
1350 if (index < 0) {
1351 return;
1352 }
1353 sessionEffects = mSuspendedSessions.valueAt(index);
1354 }
1355
1356
Andy Hung116bc262023-06-20 18:56:17 -07001357 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001358 if (type != NULL) {
1359 key = type->timeLow;
1360 }
1361 index = sessionEffects.indexOfKey(key);
1362
1363 sp<SuspendedSessionDesc> desc;
1364 if (suspend) {
1365 if (index >= 0) {
1366 desc = sessionEffects.valueAt(index);
1367 } else {
1368 desc = new SuspendedSessionDesc();
1369 if (type != NULL) {
1370 desc->mType = *type;
1371 }
1372 sessionEffects.add(key, desc);
1373 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1374 }
1375 desc->mRefCount++;
1376 } else {
1377 if (index < 0) {
1378 return;
1379 }
1380 desc = sessionEffects.valueAt(index);
1381 if (--desc->mRefCount == 0) {
1382 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1383 sessionEffects.removeItemsAt(index);
1384 if (sessionEffects.isEmpty()) {
1385 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1386 sessionId);
1387 mSuspendedSessions.removeItem(sessionId);
1388 }
1389 }
1390 }
1391 if (!sessionEffects.isEmpty()) {
1392 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1393 }
1394}
1395
Andy Hung4b17e882023-07-07 13:47:37 -07001396void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001397 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001398 bool threadLocked)
1399NO_THREAD_SAFETY_ANALYSIS // manual locking
1400{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001401 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001402 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001403 }
Eric Laurent81784c32012-11-19 14:55:58 -08001404
Eric Laurent81784c32012-11-19 14:55:58 -08001405 if (mType != RECORD) {
1406 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1407 // another session. This gives the priority to well behaved effect control panels
1408 // and applications not using global effects.
1409 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1410 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001411 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001412 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1413 }
1414 }
1415
Eric Laurent6b446ce2019-12-13 10:56:31 -08001416 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001417 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001418 }
1419}
1420
Andy Hungb17d24b2023-08-29 14:26:09 -07001421// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001422status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001423 const effect_descriptor_t *desc, audio_session_t sessionId)
1424{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001425 // No global output effect sessions on record threads
1426 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1427 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001428 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1429 desc->name, mThreadName);
1430 return BAD_VALUE;
1431 }
1432 // only pre processing effects on record thread
1433 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1434 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1435 desc->name, mThreadName);
1436 return BAD_VALUE;
1437 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001438
1439 // always allow effects without processing load or latency
1440 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1441 return NO_ERROR;
1442 }
1443
Eric Laurent4c415062016-06-17 16:14:16 -07001444 audio_input_flags_t flags = mInput->flags;
1445 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1446 if (flags & AUDIO_INPUT_FLAG_RAW) {
1447 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1448 desc->name, mThreadName);
1449 return BAD_VALUE;
1450 }
1451 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1452 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1453 desc->name, mThreadName);
1454 return BAD_VALUE;
1455 }
1456 }
jiabineb3bda02020-06-30 14:07:03 -07001457
Andy Hung116bc262023-06-20 18:56:17 -07001458 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001459 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1460 return BAD_VALUE;
1461 }
Eric Laurent4c415062016-06-17 16:14:16 -07001462 return NO_ERROR;
1463}
1464
Andy Hungb17d24b2023-08-29 14:26:09 -07001465// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001466status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001467 const effect_descriptor_t *desc, audio_session_t sessionId)
1468{
1469 // no preprocessing on playback threads
1470 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001471 ALOGW("%s: pre processing effect %s created on playback"
1472 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001473 return BAD_VALUE;
1474 }
1475
Eric Laurent3e4de772017-07-16 16:55:08 -07001476 // always allow effects without processing load or latency
1477 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1478 return NO_ERROR;
1479 }
1480
Andy Hung116bc262023-06-20 18:56:17 -07001481 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001482 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1483 __func__);
1484 return BAD_VALUE;
1485 }
1486
Eric Laurentf690c462021-09-17 14:47:03 +02001487 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1488 && mType != SPATIALIZER) {
1489 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1490 __func__, mType);
1491 return BAD_VALUE;
1492 }
1493
Eric Laurent4c415062016-06-17 16:14:16 -07001494 switch (mType) {
1495 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001496 audio_output_flags_t flags = mOutput->flags;
1497 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1498 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1499 // global effects are applied only to non fast tracks if they are SW
1500 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1501 break;
1502 }
1503 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1504 // only post processing on output stage session
1505 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001506 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1507 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001508 return BAD_VALUE;
1509 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001510 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1511 // only post processing on output stage session
1512 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001513 ALOGW("%s: non post processing effect %s not allowed on device session",
1514 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001515 return BAD_VALUE;
1516 }
Eric Laurent4c415062016-06-17 16:14:16 -07001517 } else {
1518 // no restriction on effects applied on non fast tracks
1519 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1520 break;
1521 }
1522 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001523
Eric Laurent4c415062016-06-17 16:14:16 -07001524 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001525 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001526 return BAD_VALUE;
1527 }
1528 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001529 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1530 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001531 return BAD_VALUE;
1532 }
1533 }
1534 } break;
1535 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001536 // nothing actionable on offload threads, if the effect:
1537 // - is offloadable: the effect can be created
1538 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1539 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001540 break;
1541 case DIRECT:
1542 // Reject any effect on Direct output threads for now, since the format of
1543 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001544 ALOGW("%s: effect %s on DIRECT output thread %s",
1545 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001546 return BAD_VALUE;
1547 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001548 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001549 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1550 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001551 return BAD_VALUE;
1552 }
1553 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001554 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1555 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001556 return BAD_VALUE;
1557 }
1558 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001559 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1560 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001561 return BAD_VALUE;
1562 }
1563 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001564 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001565 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1566 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1567 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1568 // are supported and added after the spatializer.
1569 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1570 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1571 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001572 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001573 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1574 // only post processing , downmixer or spatializer effects on output stage session
1575 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1576 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1577 break;
1578 }
1579 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1580 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1581 __func__, desc->name);
1582 return BAD_VALUE;
1583 }
1584 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1585 // only post processing on output stage session
1586 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1587 ALOGW("%s: non post processing effect %s not allowed on device session",
1588 __func__, desc->name);
1589 return BAD_VALUE;
1590 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001591 }
1592 break;
jiabinc658e452022-10-21 20:52:21 +00001593 case BIT_PERFECT:
1594 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1595 // Allow HW accelerated effects of tunnel type
1596 break;
1597 }
1598 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1599 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1600 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1601 // 3) there is any bit-perfect track with the given session id.
1602 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1603 sessionId == AUDIO_SESSION_DEVICE) {
1604 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1605 __func__, desc->name, mThreadName);
1606 return BAD_VALUE;
1607 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1608 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1609 __func__, desc->name, sessionId);
1610 return BAD_VALUE;
1611 }
1612 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001613 default:
1614 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1615 }
1616
1617 return NO_ERROR;
1618}
1619
Andy Hungb17d24b2023-08-29 14:26:09 -07001620// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001621sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001622 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001623 const sp<IEffectClient>& effectClient,
1624 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001625 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001626 effect_descriptor_t *desc,
1627 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001628 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001629 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001630 bool probe,
1631 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001632{
Andy Hung116bc262023-06-20 18:56:17 -07001633 sp<IAfEffectModule> effect;
1634 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001636 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001637 bool chainCreated = false;
1638 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001639 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001640
1641 lStatus = initCheck();
1642 if (lStatus != NO_ERROR) {
1643 ALOGW("createEffect_l() Audio driver not initialized.");
1644 goto Exit;
1645 }
1646
Eric Laurent81784c32012-11-19 14:55:58 -08001647 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1648
Andy Hungb17d24b2023-08-29 14:26:09 -07001649 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07001650 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001651
Eric Laurent4c415062016-06-17 16:14:16 -07001652 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001653 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001654 goto Exit;
1655 }
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // check for existing effect chain with the requested audio session
1658 chain = getEffectChain_l(sessionId);
1659 if (chain == 0) {
1660 // create a new chain for this session
1661 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001662 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001663 addEffectChain_l(chain);
1664 chain->setStrategy(getStrategyForSession_l(sessionId));
1665 chainCreated = true;
1666 } else {
1667 effect = chain->getEffectFromDesc_l(desc);
1668 }
1669
1670 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1671
1672 if (effect == 0) {
Andy Hung7535ed92023-07-17 17:05:00 -07001673 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001675 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001676 if (lStatus != NO_ERROR) {
1677 goto Exit;
1678 }
1679 effectCreated = true;
1680
jiabinc52b1ff2019-10-31 17:20:42 -07001681 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001682 effect->setDevices(outDeviceTypeAddrs());
1683 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001684 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001685 effect->setAudioSource(mAudioSource);
1686 }
jiabin1319f5a2021-03-30 22:21:24 +00001687 if (effect->isHapticGenerator()) {
1688 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1689 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001690 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung7535ed92023-07-17 17:05:00 -07001691 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001692 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001693 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001694 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001695 }
1696 }
Eric Laurent81784c32012-11-19 14:55:58 -08001697 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001698 handle = IAfEffectHandle::create(
1699 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001700 lStatus = handle->initCheck();
1701 if (lStatus == OK) {
1702 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001703 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001704 }
Eric Laurent81784c32012-11-19 14:55:58 -08001705 if (enabled != NULL) {
1706 *enabled = (int)effect->isEnabled();
1707 }
1708 }
1709
1710Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001711 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hungf8635b62023-08-31 16:13:39 -07001712 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001713 if (effectCreated) {
1714 chain->removeEffect_l(effect);
1715 }
Eric Laurent81784c32012-11-19 14:55:58 -08001716 if (chainCreated) {
1717 removeEffectChain_l(chain);
1718 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001719 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001720 }
1721
Glenn Kasten9156ef32013-08-06 15:39:08 -07001722 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001723 return handle;
1724}
1725
Andy Hung4b17e882023-07-07 13:47:37 -07001726void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001727 bool unpinIfLast)
1728{
1729 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001730 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001731 {
Andy Hungf8635b62023-08-31 16:13:39 -07001732 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001733 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001734 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001735 return;
1736 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001737 effect = effectBase->asEffectModule();
1738 if (effect == nullptr) {
1739 return;
1740 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001741 // restore suspended effects if the disconnected handle was enabled and the last one.
1742 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1743 if (remove) {
1744 removeEffect_l(effect, true);
1745 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001746 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 }
1748 if (remove) {
Andy Hung7535ed92023-07-17 17:05:00 -07001749 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001751 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001752 }
1753 }
1754}
1755
Andy Hung4b17e882023-07-07 13:47:37 -07001756void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001757 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001758 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001759 broadcast_l();
1760 }
1761 if (!effect->isOffloadable()) {
1762 if (mType == ThreadBase::OFFLOAD) {
1763 PlaybackThread *t = (PlaybackThread *)this;
1764 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1765 }
1766 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung7535ed92023-07-17 17:05:00 -07001767 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001768 }
1769 }
1770}
1771
Andy Hung4b17e882023-07-07 13:47:37 -07001772void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001773 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001774 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001775 broadcast_l();
1776 }
1777}
1778
Andy Hung4b17e882023-07-07 13:47:37 -07001779sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001780 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001781{
Andy Hungf8635b62023-08-31 16:13:39 -07001782 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001783 return getEffect_l(sessionId, effectId);
1784}
1785
Andy Hung4b17e882023-07-07 13:47:37 -07001786sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001787 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001788{
Andy Hung116bc262023-06-20 18:56:17 -07001789 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001790 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1791}
1792
Andy Hung4b17e882023-07-07 13:47:37 -07001793std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001794{
Andy Hung116bc262023-06-20 18:56:17 -07001795 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001796 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1797}
1798
Andy Hungf8635b62023-08-31 16:13:39 -07001799// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1800// ThreadBase::mutex() held
1801status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001802{
1803 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001804 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001805 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001806 bool chainCreated = false;
1807
Eric Laurent5baf2af2013-09-12 17:37:00 -07001808 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hungf8635b62023-08-31 16:13:39 -07001809 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1810 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001811
Eric Laurent81784c32012-11-19 14:55:58 -08001812 if (chain == 0) {
1813 // create a new chain for this session
Andy Hungf8635b62023-08-31 16:13:39 -07001814 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001815 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001816 addEffectChain_l(chain);
1817 chain->setStrategy(getStrategyForSession_l(sessionId));
1818 chainCreated = true;
1819 }
Andy Hungf8635b62023-08-31 16:13:39 -07001820 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001821
1822 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hungf8635b62023-08-31 16:13:39 -07001823 ALOGW("%s: %p effect %s already present in chain %p",
1824 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001825 return BAD_VALUE;
1826 }
1827
Eric Laurent5baf2af2013-09-12 17:37:00 -07001828 effect->setOffloaded(mType == OFFLOAD, mId);
1829
Eric Laurent81784c32012-11-19 14:55:58 -08001830 status_t status = chain->addEffect_l(effect);
1831 if (status != NO_ERROR) {
1832 if (chainCreated) {
1833 removeEffectChain_l(chain);
1834 }
1835 return status;
1836 }
1837
jiabin8f278ee2019-11-11 12:16:27 -08001838 effect->setDevices(outDeviceTypeAddrs());
1839 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001840 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001841 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001842
Eric Laurent81784c32012-11-19 14:55:58 -08001843 return NO_ERROR;
1844}
1845
Andy Hung4b17e882023-07-07 13:47:37 -07001846void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001847
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001848 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001849 effect_descriptor_t desc = effect->desc();
1850 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1851 detachAuxEffect_l(effect->id());
1852 }
1853
Andy Hung116bc262023-06-20 18:56:17 -07001854 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001855 if (chain != 0) {
1856 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001857 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001858 removeEffectChain_l(chain);
1859 }
1860 } else {
1861 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1862 }
1863}
1864
Andy Hung4b17e882023-07-07 13:47:37 -07001865void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001866 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001867NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001868{
1869 effectChains = mEffectChains;
1870 for (size_t i = 0; i < mEffectChains.size(); i++) {
Andy Hung1f6d4cd2023-08-29 12:19:17 -07001871 mEffectChains[i]->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001872 }
1873}
1874
Andy Hung4b17e882023-07-07 13:47:37 -07001875void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001876 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001877NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001878{
1879 for (size_t i = 0; i < effectChains.size(); i++) {
Andy Hung1f6d4cd2023-08-29 12:19:17 -07001880 effectChains[i]->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001881 }
1882}
1883
Andy Hung4b17e882023-07-07 13:47:37 -07001884sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001885{
Andy Hungf8635b62023-08-31 16:13:39 -07001886 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001887 return getEffectChain_l(sessionId);
1888}
1889
Andy Hung4b17e882023-07-07 13:47:37 -07001890sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001891 const
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
1893 size_t size = mEffectChains.size();
1894 for (size_t i = 0; i < size; i++) {
1895 if (mEffectChains[i]->sessionId() == sessionId) {
1896 return mEffectChains[i];
1897 }
1898 }
1899 return 0;
1900}
1901
Andy Hung4b17e882023-07-07 13:47:37 -07001902void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001903{
Andy Hungf8635b62023-08-31 16:13:39 -07001904 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001905 size_t size = mEffectChains.size();
1906 for (size_t i = 0; i < size; i++) {
1907 mEffectChains[i]->setMode_l(mode);
1908 }
1909}
1910
Andy Hung4b17e882023-07-07 13:47:37 -07001911void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001912{
1913 config->type = AUDIO_PORT_TYPE_MIX;
1914 config->ext.mix.handle = mId;
1915 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001916 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001917 config->channel_mask = mChannelMask;
1918 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1919 AUDIO_PORT_CONFIG_FORMAT;
1920}
1921
Andy Hung4b17e882023-07-07 13:47:37 -07001922void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001923{
Andy Hungf8635b62023-08-31 16:13:39 -07001924 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001925 if (mSystemReady) {
1926 return;
1927 }
1928 mSystemReady = true;
1929
1930 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1931 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1932 }
1933 mPendingConfigEvents.clear();
1934}
1935
Andy Hungdae27702016-10-31 14:01:16 -07001936template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001937ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001938 ssize_t index = mActiveTracks.indexOf(track);
1939 if (index >= 0) {
1940 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1941 return index;
1942 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001943 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001944 mActiveTracksGeneration++;
1945 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001946 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001947 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001948 return mActiveTracks.add(track);
1949}
1950
1951template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001952ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001953 ssize_t index = mActiveTracks.remove(track);
1954 if (index < 0) {
1955 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1956 return index;
1957 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001958 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001959 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001960 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001961 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001962 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001963#ifdef TEE_SINK
1964 track->dumpTee(-1 /* fd */, "_REMOVE");
1965#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001966 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001967 return index;
1968}
1969
1970template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001971void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001972 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001973 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001974 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001975 }
1976 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001977 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001978 mActiveTracks.clear();
1979 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001980}
1981
1982template <typename T>
Andy Hung94dfbb42023-09-06 19:41:47 -07001983void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001984 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001985 // Updates ActiveTracks client uids to the thread wakelock.
1986 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1987 thread->updateWakeLockUids_l(getWakeLockUids());
1988 mLastActiveTracksGeneration = mActiveTracksGeneration;
1989 }
Andy Hungdae27702016-10-31 14:01:16 -07001990}
Eric Laurent83b88082014-06-20 18:31:16 -07001991
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001992template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001993bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001994 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001995 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001996
1997 for (const sp<T> &track : mActiveTracks) {
1998 // Do not short-circuit as all hasChanged states must be reset
1999 // as all the metadata are going to be sent
2000 hasChanged |= track->readAndClearHasChanged();
2001 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002002 return hasChanged;
2003}
2004
2005template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002006void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002007 const char *funcName, const sp<T> &track) const {
2008 if (mLocalLog != nullptr) {
2009 String8 result;
2010 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002011 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002012 }
2013}
2014
Andy Hung4b17e882023-07-07 13:47:37 -07002015void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002016{
2017 // Thread could be blocked waiting for async
2018 // so signal it to handle state changes immediately
2019 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2020 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2021 mSignalPending = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07002022 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002023}
2024
Andy Hungd0979812019-02-21 15:51:44 -08002025// Call only from threadLoop() or when it is idle.
2026// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07002027void ThreadBase::sendStatistics(bool force)
Andy Hung94dfbb42023-09-06 19:41:47 -07002028NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002029{
2030 // Do not log if we have no stats.
2031 // We choose the timestamp verifier because it is the most likely item to be present.
2032 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2033 if (nstats == 0) {
2034 return;
2035 }
2036
2037 // Don't log more frequently than once per 12 hours.
2038 // We use BOOTTIME to include suspend time.
2039 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2040 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2041 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2042 return;
2043 }
2044
2045 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2046 mLastRecordedTimeNs = timeNs;
2047
Ray Essickf27e9872019-12-07 06:28:46 -08002048 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002049
2050#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2051
2052 // thread configuration
2053 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2054 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2055 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2056 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2057 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2058 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2059 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hung94dfbb42023-09-06 19:41:47 -07002060 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2061 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002062
2063 // thread statistics
2064 if (mIoJitterMs.getN() > 0) {
2065 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2066 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2067 }
2068 if (mProcessTimeMs.getN() > 0) {
2069 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2070 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2071 }
2072 const auto tsjitter = mTimestampVerifier.getJitterMs();
2073 if (tsjitter.getN() > 0) {
2074 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2075 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2076 }
2077 if (mLatencyMs.getN() > 0) {
2078 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2079 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2080 }
Robert Wu06db0a32021-08-10 19:05:34 +00002081 if (mMonopipePipeDepthStats.getN() > 0) {
2082 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2083 mMonopipePipeDepthStats.getMean());
2084 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2085 mMonopipePipeDepthStats.getStdDev());
2086 }
Andy Hungd0979812019-02-21 15:51:44 -08002087
2088 item->selfrecord();
2089}
2090
Andy Hung4b17e882023-07-07 13:47:37 -07002091product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002092{
Andy Hung7535ed92023-07-17 17:05:00 -07002093 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002094 return PRODUCT_STRATEGY_NONE;
2095 }
2096 return AudioSystem::getStrategyForStream(stream);
2097}
2098
Andy Hungb17d24b2023-08-29 14:26:09 -07002099// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002100void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002101 const sp<audio_utils::MelProcessor>& /*processor*/)
2102{
2103 // Do nothing
2104 ALOGW("%s: ThreadBase does not support CSD", __func__);
2105}
2106
Andy Hungb17d24b2023-08-29 14:26:09 -07002107// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002108void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002109{
2110 // Do nothing
2111 ALOGW("%s: ThreadBase does not support CSD", __func__);
2112}
2113
Eric Laurent81784c32012-11-19 14:55:58 -08002114// ----------------------------------------------------------------------------
2115// Playback
2116// ----------------------------------------------------------------------------
2117
Andy Hung7535ed92023-07-17 17:05:00 -07002118PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002119 AudioStreamOut* output,
2120 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002121 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002122 bool systemReady,
2123 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002124 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002125 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002126 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002127 mMixerBuffer(NULL),
2128 mMixerBufferSize(0),
2129 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2130 mMixerBufferValid(false),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002131 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002132 mEffectBuffer(NULL),
2133 mEffectBufferSize(0),
2134 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2135 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002136 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002137 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002138 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002139 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002140 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002141 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002142 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002143 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002144 mMixerStatus(MIXER_IDLE),
2145 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hungd58c4732023-07-20 21:31:38 -07002146 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002147 mBytesRemaining(0),
2148 mCurrentWriteLength(0),
2149 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002150 mWriteAckSequence(0),
2151 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002152 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002153 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002154 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002155 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002156 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002157 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002158 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002159{
Glenn Kastend7dca052015-03-05 16:05:54 -08002160 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002161 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002162
Andy Hungb17d24b2023-08-29 14:26:09 -07002163 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002164 // it would be safer to explicitly pass initial masterVolume/masterMute as
2165 // parameter.
2166 //
2167 // If the HAL we are using has support for master volume or master mute,
2168 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2169 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002170 mMasterVolume = afThreadCallback->masterVolume_l();
2171 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002172 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002173 if (mOutput->audioHwDev->canSetMasterVolume()) {
2174 mMasterVolume = 1.0;
2175 }
2176
2177 if (mOutput->audioHwDev->canSetMasterMute()) {
2178 mMasterMute = false;
2179 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002180 mIsMsdDevice = strcmp(
2181 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002182 }
2183
Eric Laurentf1f22e72021-07-13 14:04:14 +02002184 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2185 mMixerChannelMask = mixerConfig->channel_mask;
2186 }
2187
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002188 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002189
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002190 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002191 && mMixerChannelMask != mChannelMask) {
2192 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2193 mChannelMask, mMixerChannelMask);
2194 }
2195
Andy Hungc8fddf32018-08-08 18:32:37 -07002196 // TODO: We may also match on address as well as device type for
2197 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002198 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002199 // TODO: This property should be ensure that only contains one single device type.
2200 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2201 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002202 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2203 : AUDIO_DEVICE_NONE));
2204 }
2205
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002206 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2207 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002208 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002209 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002210 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002211 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002212 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2213 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002214 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2215 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002216}
2217
Andy Hung4b17e882023-07-07 13:47:37 -07002218PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002219{
Andy Hung7535ed92023-07-17 17:05:00 -07002220 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002221 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002222 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002223 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002224 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002225}
2226
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002227// Thread virtuals
2228
Andy Hung4b17e882023-07-07 13:47:37 -07002229void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002230{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002231 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002232 ALOGE("The stream is not open yet"); // This should not happen.
2233 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002234 // Callbacks take strong or weak pointers as a parameter.
2235 // Since PlaybackThread passes itself as a callback handler, it can only
2236 // be done outside of the constructor. Creating weak and especially strong
2237 // pointers to a refcounted object in its own constructor is strongly
2238 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2239 // Even if a function takes a weak pointer, it is possible that it will
2240 // need to convert it to a strong pointer down the line.
2241 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2242 mOutput->stream->setCallback(this) == OK) {
2243 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002244 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002245 }
2246
jiabinf6eb4c32020-02-25 14:06:25 -08002247 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002248 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002249 }
2250 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002251 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002252 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002253}
2254
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002255// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002256void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002257{
2258 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002259 status_t result = mOutput->stream->exit();
2260 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002261}
2262
Andy Hung4b17e882023-07-07 13:47:37 -07002263void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002264{
Eric Laurent81784c32012-11-19 14:55:58 -08002265 String8 result;
2266
Marco Nelissenb2208842014-02-07 14:00:50 -08002267 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002268 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2269 const stream_type_t *st = &mStreamTypes[i];
2270 if (i > 0) {
2271 result.appendFormat(", ");
2272 }
2273 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2274 if (st->mute) {
2275 result.append("M");
2276 }
2277 }
2278 result.append("\n");
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002279 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002280 result.clear();
2281
Eric Laurent81784c32012-11-19 14:55:58 -08002282 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2283 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002284 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002285 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002286
2287 size_t numtracks = mTracks.size();
2288 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002289 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002290 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002291 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002292 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002293 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002294 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002295 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002296 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002297 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002298 if (track != 0) {
2299 bool active = mActiveTracks.indexOf(track) >= 0;
2300 if (active) {
2301 numactiveseen++;
2302 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002303 result.append(prefix);
2304 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002305 }
2306 }
2307 } else {
2308 result.append("\n");
2309 }
2310 if (numactiveseen != numactive) {
2311 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002312 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002313 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002314 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002315 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002316 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002317 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002318 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002319 result.append(prefix);
2320 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002321 }
2322 }
2323 }
2324
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002325 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002326}
2327
Andy Hung4b17e882023-07-07 13:47:37 -07002328void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002329{
Andy Hung04cb8f72020-03-20 13:44:33 -07002330 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002331 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002332 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2333 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002334 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2335 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2336 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2337 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002338 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002339 dprintf(fd, " Total writes: %d\n", mNumWrites);
2340 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2341 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung160664b2023-09-15 18:19:28 -07002342 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002343 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002344 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002345 AudioStreamOut *output = mOutput;
2346 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002347 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002348 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002349 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2350 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2351 if (mPipeSink.get() != nullptr) {
2352 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2353 }
2354 if (output != nullptr) {
2355 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002356 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358}
2359
Andy Hungb17d24b2023-08-29 14:26:09 -07002360// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002361sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002362 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002363 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002364 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002365 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002366 audio_format_t format,
2367 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002368 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002369 size_t *pNotificationFrameCount,
2370 uint32_t notificationsPerBuffer,
2371 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002372 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002373 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002374 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002375 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002376 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002377 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002378 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002379 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002380 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002381 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002382 bool isBitPerfect,
2383 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002384{
Glenn Kasten74935e42013-12-19 08:56:45 -08002385 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002386 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002387 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002388 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002389 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002390 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002391 uint32_t sampleRate;
2392
2393 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2394 lStatus = BAD_VALUE;
2395 goto Exit;
2396 }
Eric Laurent21da6472017-11-09 16:29:26 -08002397
2398 if (*pSampleRate == 0) {
2399 *pSampleRate = mSampleRate;
2400 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002401 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002402
2403 // special case for FAST flag considered OK if fast mixer is present
2404 if (hasFastMixer()) {
2405 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2406 }
2407
2408 // Check if requested flags are compatible with output stream flags
2409 if ((*flags & outputFlags) != *flags) {
2410 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2411 *flags, outputFlags);
2412 *flags = (audio_output_flags_t)(*flags & outputFlags);
2413 }
Eric Laurent81784c32012-11-19 14:55:58 -08002414
jiabinc658e452022-10-21 20:52:21 +00002415 if (isBitPerfect) {
Andy Hung160664b2023-09-15 18:19:28 -07002416 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002417 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002418 if (chain.get() != nullptr) {
2419 // Bit-perfect is required according to the configuration and preferred mixer
2420 // attributes, but it is not in the output flag from the client's request. Explicitly
2421 // adding bit-perfect flag to check the compatibility
2422 audio_output_flags_t flagsToCheck =
2423 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2424 chain->checkOutputFlagCompatibility(&flagsToCheck);
2425 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2426 ALOGE("%s cannot create track as there is data-processing effect attached to "
2427 "given session id(%d)", __func__, sessionId);
2428 lStatus = BAD_VALUE;
2429 goto Exit;
2430 }
2431 *flags = flagsToCheck;
2432 }
2433 }
2434
Eric Laurent81784c32012-11-19 14:55:58 -08002435 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002436 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002437 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002438 // PCM data
2439 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002440 // TODO: extract as a data library function that checks that a computationally
2441 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002442 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002443 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2444 (channelMask == AUDIO_CHANNEL_OUT_MONO
2445 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002446 // hardware sample rate
2447 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // normal mixer has an associated fast mixer
2449 hasFastMixer() &&
2450 // there are sufficient fast track slots available
2451 (mFastTrackAvailMask != 0)
2452 // FIXME test that MixerThread for this fast track has a capable output HAL
2453 // FIXME add a permission test also?
2454 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002455 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2456 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002457 // read the fast track multiplier property the first time it is needed
2458 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2459 if (ok != 0) {
2460 ALOGE("%s pthread_once failed: %d", __func__, ok);
2461 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002462 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002463 }
Eric Laurent4c415062016-06-17 16:14:16 -07002464
2465 // check compatibility with audio effects.
Andy Hungb17d24b2023-08-29 14:26:09 -07002466 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002467 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002468 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002469 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002470 AUDIO_SESSION_OUTPUT_STAGE,
2471 AUDIO_SESSION_OUTPUT_MIX,
2472 sessionId,
2473 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002474 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002475 if (chain.get() != nullptr) {
2476 audio_output_flags_t old = *flags;
2477 chain->checkOutputFlagCompatibility(flags);
2478 if (old != *flags) {
2479 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2480 (int)session, (int)old, (int)*flags);
2481 }
Eric Laurent4c415062016-06-17 16:14:16 -07002482 }
2483 }
2484 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002485 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002486 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2487 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002488 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002489 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002490 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002491 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002492 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002493 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002494 audio_is_linear_pcm(format), channelMask, sampleRate,
2495 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002496 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002497 }
2498 }
Eric Laurent21da6472017-11-09 16:29:26 -08002499
2500 if (!audio_has_proportional_frames(format)) {
2501 if (sharedBuffer != 0) {
2502 // Same comment as below about ignoring frameCount parameter for set()
2503 frameCount = sharedBuffer->size();
2504 } else if (frameCount == 0) {
2505 frameCount = mNormalFrameCount;
2506 }
2507 if (notificationFrameCount != frameCount) {
2508 notificationFrameCount = frameCount;
2509 }
2510 } else if (sharedBuffer != 0) {
2511 // FIXME: Ensure client side memory buffers need
2512 // not have additional alignment beyond sample
2513 // (e.g. 16 bit stereo accessed as 32 bit frame).
2514 size_t alignment = audio_bytes_per_sample(format);
2515 if (alignment & 1) {
2516 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2517 alignment = 1;
2518 }
2519 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2520 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2521 if (channelCount > 1) {
2522 // More than 2 channels does not require stronger alignment than stereo
2523 alignment <<= 1;
2524 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002525 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002526 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002527 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002528 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002529 goto Exit;
2530 }
Eric Laurent21da6472017-11-09 16:29:26 -08002531
2532 // When initializing a shared buffer AudioTrack via constructors,
2533 // there's no frameCount parameter.
2534 // But when initializing a shared buffer AudioTrack via set(),
2535 // there _is_ a frameCount parameter. We silently ignore it.
2536 frameCount = sharedBuffer->size() / frameSize;
2537 } else {
2538 size_t minFrameCount = 0;
2539 // For fast tracks we try to respect the application's request for notifications per buffer.
2540 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2541 if (notificationsPerBuffer > 0) {
2542 // Avoid possible arithmetic overflow during multiplication.
2543 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2544 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2545 notificationsPerBuffer, mFrameCount);
2546 } else {
2547 minFrameCount = mFrameCount * notificationsPerBuffer;
2548 }
2549 }
2550 } else {
2551 // For normal PCM streaming tracks, update minimum frame count.
2552 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2553 // cover audio hardware latency.
2554 // This is probably too conservative, but legacy application code may depend on it.
2555 // If you change this calculation, also review the start threshold which is related.
2556 uint32_t latencyMs = latency_l();
2557 if (latencyMs == 0) {
2558 ALOGE("Error when retrieving output stream latency");
2559 lStatus = UNKNOWN_ERROR;
2560 goto Exit;
2561 }
2562
2563 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2564 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2565
Eric Laurent81784c32012-11-19 14:55:58 -08002566 }
Eric Laurent21da6472017-11-09 16:29:26 -08002567 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002568 frameCount = minFrameCount;
2569 }
Eric Laurent81784c32012-11-19 14:55:58 -08002570 }
Eric Laurent21da6472017-11-09 16:29:26 -08002571
2572 // Make sure that application is notified with sufficient margin before underrun.
2573 // The client can divide the AudioTrack buffer into sub-buffers,
2574 // and expresses its desire to server as the notification frame count.
2575 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2576 size_t maxNotificationFrames;
2577 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2578 // notify every HAL buffer, regardless of the size of the track buffer
2579 maxNotificationFrames = mFrameCount;
2580 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002581 // Triple buffer the notification period for a triple buffered mixer period;
2582 // otherwise, double buffering for the notification period is fine.
2583 //
2584 // TODO: This should be moved to AudioTrack to modify the notification period
2585 // on AudioTrack::setBufferSizeInFrames() changes.
2586 const int nBuffering =
2587 (uint64_t{frameCount} * mSampleRate)
2588 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2589
Eric Laurent21da6472017-11-09 16:29:26 -08002590 maxNotificationFrames = frameCount / nBuffering;
2591 // If client requested a fast track but this was denied, then use the smaller maximum.
2592 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2593 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2594 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2595 maxNotificationFrames = maxNotificationFramesFastDenied;
2596 }
2597 }
2598 }
2599 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2600 if (notificationFrameCount == 0) {
2601 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2602 maxNotificationFrames, frameCount);
2603 } else {
2604 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2605 notificationFrameCount, maxNotificationFrames, frameCount);
2606 }
2607 notificationFrameCount = maxNotificationFrames;
2608 }
2609 }
2610
Glenn Kasten74935e42013-12-19 08:56:45 -08002611 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002612 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002613
Glenn Kastenc3df8382014-03-13 15:05:25 -07002614 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002615 case BIT_PERFECT:
2616 if (isBitPerfect) {
2617 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2618 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2619 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2620 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2621 mChannelMask);
2622 lStatus = BAD_VALUE;
2623 goto Exit;
2624 }
2625 }
2626 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002627
2628 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002629 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002630 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002631 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2632 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002633 sampleRate, format, channelMask, mOutput, mFormat);
2634 lStatus = BAD_VALUE;
2635 goto Exit;
2636 }
2637 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002638 break;
2639
2640 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002642 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2643 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002644 sampleRate, format, channelMask, mOutput, mFormat);
2645 lStatus = BAD_VALUE;
2646 goto Exit;
2647 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002648 break;
2649
2650 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002651 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002652 ALOGE("createTrack_l() Bad parameter: format %#x \""
2653 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 format, mOutput, mFormat);
2655 lStatus = BAD_VALUE;
2656 goto Exit;
2657 }
Andy Hungcd044842014-08-07 11:04:34 -07002658 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002659 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2660 lStatus = BAD_VALUE;
2661 goto Exit;
2662 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002663 break;
2664
Eric Laurent81784c32012-11-19 14:55:58 -08002665 }
2666
2667 lStatus = initCheck();
2668 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002669 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002670 goto Exit;
2671 }
2672
Andy Hungb17d24b2023-08-29 14:26:09 -07002673 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002674 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002675
2676 // all tracks in same audio session must share the same routing strategy otherwise
2677 // conflicts will happen when tracks are moved from one output to another by audio policy
2678 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002679 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002680 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002681 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002682 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002683 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002684 if (sessionId == t->sessionId() && strategy != actual) {
2685 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2686 strategy, actual);
2687 lStatus = BAD_VALUE;
2688 goto Exit;
2689 }
2690 }
2691 }
2692
Deeraj Soman2b515232024-05-14 12:58:24 +05302693 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2694 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002695 // dynamic audio policy.
2696 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302697 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002698 audio_output_flags_t trackFlags = *flags;
2699 if (mType == DIRECT) {
2700 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302701 } else if (mType == OFFLOAD) {
2702 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2703 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002704 }
jiabin94ed47c2023-07-27 23:34:20 +00002705 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002706
Andy Hung11e74242023-06-26 19:20:57 -07002707 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002708 channelMask, frameCount,
2709 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002710 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002711 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002712 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002713
Glenn Kasten03003332013-08-06 15:40:54 -07002714 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2715 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002716 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002717 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002718 goto Exit;
2719 }
2720 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002721 {
Andy Hungf8635b62023-08-31 16:13:39 -07002722 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002723 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002724 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002725 }
2726 }
Eric Laurent81784c32012-11-19 14:55:58 -08002727
Andy Hung116bc262023-06-20 18:56:17 -07002728 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002729 if (chain != 0) {
2730 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2731 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002732 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002733 chain->incTrackCnt();
2734 }
2735
Eric Laurent05067782016-06-01 18:27:28 -07002736 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002737 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2738 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2739 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002740 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002741 }
2742 }
2743
2744 lStatus = NO_ERROR;
2745
2746Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002747 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002748 return track;
2749}
2750
Andy Hung1bc088a2018-02-09 15:57:31 -08002751template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002752ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002753{
Andy Hungc0691382018-09-12 18:01:57 -07002754 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002755 const ssize_t index = mTracks.remove(track);
2756 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002757 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002758 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002759 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002760 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002761 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002762 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002763 }
2764 return index;
2765}
2766
Andy Hung4b17e882023-07-07 13:47:37 -07002767uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002768{
2769 return latency;
2770}
2771
Andy Hung4b17e882023-07-07 13:47:37 -07002772uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002773{
Andy Hungf8635b62023-08-31 16:13:39 -07002774 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002775 return latency_l();
2776}
Andy Hung4b17e882023-07-07 13:47:37 -07002777uint32_t PlaybackThread::latency_l() const
Andy Hung94dfbb42023-09-06 19:41:47 -07002778NO_THREAD_SAFETY_ANALYSIS
2779// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002780{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002781 uint32_t latency;
2782 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2783 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002784 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002785 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002786}
2787
Andy Hung4b17e882023-07-07 13:47:37 -07002788void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002789{
Andy Hungf8635b62023-08-31 16:13:39 -07002790 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002791 // Don't apply master volume in SW if our HAL can do it for us.
2792 if (mOutput && mOutput->audioHwDev &&
2793 mOutput->audioHwDev->canSetMasterVolume()) {
2794 mMasterVolume = 1.0;
2795 } else {
2796 mMasterVolume = value;
2797 }
2798}
2799
Andy Hung4b17e882023-07-07 13:47:37 -07002800void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002801{
2802 mMasterBalance.store(balance);
2803}
2804
Andy Hung4b17e882023-07-07 13:47:37 -07002805void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002806{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002807 if (isDuplicating()) {
2808 return;
2809 }
Andy Hungf8635b62023-08-31 16:13:39 -07002810 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002811 // Don't apply master mute in SW if our HAL can do it for us.
2812 if (mOutput && mOutput->audioHwDev &&
2813 mOutput->audioHwDev->canSetMasterMute()) {
2814 mMasterMute = false;
2815 } else {
2816 mMasterMute = muted;
2817 }
2818}
2819
Andy Hung4b17e882023-07-07 13:47:37 -07002820void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002821{
Andy Hungf8635b62023-08-31 16:13:39 -07002822 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002823 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002824 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002825}
2826
Andy Hung4b17e882023-07-07 13:47:37 -07002827void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002828{
Andy Hungf8635b62023-08-31 16:13:39 -07002829 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002830 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002831 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002832}
2833
Andy Hung4b17e882023-07-07 13:47:37 -07002834float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002835{
Andy Hungf8635b62023-08-31 16:13:39 -07002836 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002837 return mStreamTypes[stream].volume;
2838}
2839
Andy Hung4b17e882023-07-07 13:47:37 -07002840void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002841{
2842 mOutput->stream->setVolume(left, right);
2843}
2844
Andy Hungb17d24b2023-08-29 14:26:09 -07002845// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002846status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002847{
2848 status_t status = ALREADY_EXISTS;
2849
Eric Laurent81784c32012-11-19 14:55:58 -08002850 if (mActiveTracks.indexOf(track) < 0) {
2851 // the track is newly added, make sure it fills up all its
2852 // buffers before playing. This is to ensure the client will
2853 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002854 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002855 IAfTrackBase::track_state state = track->state();
Andy Hunga7187712023-12-05 17:28:17 -08002856 // Because the track is not on the ActiveTracks,
2857 // at this point, only the TrackHandle will be adding the track.
Andy Hungb17d24b2023-08-29 14:26:09 -07002858 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002859 status = AudioSystem::startOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002860 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002861 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002862 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 if (status == NO_ERROR) {
Andy Hungb17d24b2023-08-29 14:26:09 -07002864 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002865 AudioSystem::stopOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002866 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002867 }
2868 return INVALID_OPERATION;
2869 }
2870 // abort if start is rejected by audio policy manager
2871 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002872 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2873 // current playback thread is reopened, which may happen when clients set preferred
2874 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2875 // immediately.
2876 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 }
2878#ifdef ADD_BATTERY_DATA
2879 // to track the speaker usage
2880 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2881#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002882 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 }
2884
Eric Laurent51716182016-02-29 18:00:56 -08002885 // set retry count for buffer fill
2886 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002887 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002888 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002889 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002890 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002891 }
Andy Hung11e74242023-06-26 19:20:57 -07002892 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002893 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002894 track->retryCount() = kMaxTrackStartupRetries;
2895 track->fillingStatus() =
2896 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002897 }
2898
Andy Hung116bc262023-06-20 18:56:17 -07002899 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002900 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2901 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2902 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002903 // Unlock due to VibratorService will lock for this call and will
2904 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungb17d24b2023-08-29 14:26:09 -07002905 mutex().unlock();
Andy Hung76cb9152023-07-20 21:23:42 -07002906 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002907 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002908 std::optional<media::AudioVibratorInfo> vibratorInfo;
2909 {
2910 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2911 // used to play this track.
Andy Hungf8635b62023-08-31 16:13:39 -07002912 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung7535ed92023-07-17 17:05:00 -07002913 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002914 }
Andy Hungb17d24b2023-08-29 14:26:09 -07002915 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002916 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002917 if (vibratorInfo) {
2918 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2919 }
2920
jiabin57303cc2018-12-18 15:45:57 -08002921 // Haptic playback should be enabled by vibrator service.
2922 if (track->getHapticPlaybackEnabled()) {
2923 // Disable haptic playback of all active track to ensure only
2924 // one track playing haptic if current track should play haptic.
2925 for (const auto &t : mActiveTracks) {
2926 t->setHapticPlaybackEnabled(false);
2927 }
jiabin245cdd92018-12-07 17:55:15 -08002928 }
jiabine70bc7f2020-06-30 22:07:55 -07002929
2930 // Set haptic intensity for effect
2931 if (chain != nullptr) {
2932 chain->setHapticIntensity_l(track->id(), intensity);
2933 }
jiabin245cdd92018-12-07 17:55:15 -08002934 }
2935
Andy Hung11e74242023-06-26 19:20:57 -07002936 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002937 track->resetPresentationComplete();
Andy Hunga7187712023-12-05 17:28:17 -08002938
2939 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2940 // all key changes are complete. It is possible that the threadLoop will begin
2941 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002942 mActiveTracks.add(track);
Andy Hunga7187712023-12-05 17:28:17 -08002943
Eric Laurentd0107bc2013-06-11 14:38:48 -07002944 if (chain != 0) {
2945 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2946 track->sessionId());
2947 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002948 }
2949
Andy Hungc2b11cb2020-04-22 09:04:01 -07002950 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002951 status = NO_ERROR;
2952 }
2953
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002954 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002955 return status;
2956}
2957
Andy Hung4b17e882023-07-07 13:47:37 -07002958bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002959{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002961 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002963 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002964 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002965 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002966 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002967 if (track->isPausePending()) {
2968 track->pauseAck();
2969 }
Andy Hung11e74242023-06-26 19:20:57 -07002970 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002971 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002972
2973 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002974}
2975
Andy Hung4b17e882023-07-07 13:47:37 -07002976void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002977{
2978 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002979
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002980 String8 result;
2981 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002982 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002983
Eric Laurent81784c32012-11-19 14:55:58 -08002984 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002985 {
Andy Hungf8635b62023-08-31 16:13:39 -07002986 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002987 mAudioTrackCallbacks.erase(track);
2988 }
Eric Laurent81784c32012-11-19 14:55:58 -08002989 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002990 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002991 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002992 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2993 mFastTrackAvailMask |= 1 << index;
2994 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07002995 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002996 }
Andy Hung116bc262023-06-20 18:56:17 -07002997 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002998 if (chain != 0) {
2999 chain->decTrackCnt();
3000 }
3001}
3002
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003003std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3004{
3005 std::set<int32_t> result;
3006 for (const auto& t : mTracks) {
3007 if (t->isExternalTrack()) {
3008 result.insert(t->portId());
3009 }
3010 }
3011 return result;
3012}
3013
3014std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3015{
3016 audio_utils::lock_guard _l(mutex());
3017 return getTrackPortIds_l();
3018}
3019
Andy Hung4b17e882023-07-07 13:47:37 -07003020String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003021{
Andy Hungf8635b62023-08-31 16:13:39 -07003022 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003023 String8 out_s8;
3024 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3025 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003026 }
Andy Hung920f6572022-10-06 12:09:49 -07003027 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003028}
3029
Andy Hung4b17e882023-07-07 13:47:37 -07003030status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hungf8635b62023-08-31 16:13:39 -07003031 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003032 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003033 return NO_INIT;
3034 }
3035 return mOutput->stream->selectPresentation(presentationId, programId);
3036}
3037
Andy Hung94dfbb42023-09-06 19:41:47 -07003038void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003039 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003040 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003041 sp<AudioIoDescriptor> desc;
3042 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003043 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003044 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003045 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003046 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003047 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3048 mSampleRate, mFormat, mChannelMask,
3049 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3050 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003051 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003052 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003053 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003054 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003055 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003056 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003057 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003058 break;
3059 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003060 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003061}
3062
Andy Hung4b17e882023-07-07 13:47:37 -07003063void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003064{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003065 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066}
3067
Andy Hung4b17e882023-07-07 13:47:37 -07003068void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003069{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003070 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003071}
3072
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003073void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003074{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003075 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003076}
3077
Andy Hung4b17e882023-07-07 13:47:37 -07003078void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003079 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003080{
Andy Hung4b17e882023-07-07 13:47:37 -07003081 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003082 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07003083 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003084 if (playbackThread == nullptr) {
3085 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3086 return;
3087 }
3088
jiabinf6eb4c32020-02-25 14:06:25 -08003089 audio_utils::metadata::Data metadata =
3090 audio_utils::metadata::dataFromByteString(metadataBs);
3091 if (metadata.empty()) {
3092 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3093 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3094 (int)metadataBs.size());
3095 return;
3096 }
3097
3098 audio_utils::metadata::ByteString metaDataStr =
3099 audio_utils::metadata::byteStringFromData(metadata);
3100 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hungf8635b62023-08-31 16:13:39 -07003101 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003102 for (const auto& callbackPair : mAudioTrackCallbacks) {
3103 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003104 }
3105 }).detach();
3106}
3107
Andy Hung4b17e882023-07-07 13:47:37 -07003108void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109{
Andy Hungf8635b62023-08-31 16:13:39 -07003110 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003111 // reject out of sequence requests
3112 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3113 mWriteAckSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003114 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003115 }
3116}
3117
Andy Hung4b17e882023-07-07 13:47:37 -07003118void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119{
Andy Hungf8635b62023-08-31 16:13:39 -07003120 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003121 // reject out of sequence requests
3122 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003123 // Register discontinuity when HW drain is completed because that can cause
3124 // the timestamp frame position to reset to 0 for direct and offload threads.
3125 // (Out of sequence requests are ignored, since the discontinuity would be handled
3126 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003127 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003128 mDrainSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003129 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003130 }
3131}
3132
Andy Hung4b17e882023-07-07 13:47:37 -07003133void PlaybackThread::readOutputParameters_l()
Andy Hungf8635b62023-08-31 16:13:39 -07003134NO_THREAD_SAFETY_ANALYSIS
3135// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003136{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003137 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003138 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3139 mSampleRate = audioConfig.sample_rate;
3140 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003141 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003142 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003143 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003144 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003145 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3146 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003147 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003148
3149 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3150 mMixerChannelMask = mChannelMask;
3151 }
3152
Andy Hunge5412692014-05-16 11:25:07 -07003153 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003154 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003155
Eric Laurentf1f22e72021-07-13 14:04:14 +02003156 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3157
Phil Burkca5e6142015-07-14 09:42:29 -07003158 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003159 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003160 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003161 // Get format from the shim, which will be different than the HAL format
3162 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003163 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003164 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003165 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003166 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003167 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003168 LOG_FATAL("HAL format %#x not supported for mixed output",
3169 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003170 }
Phil Burk062e67a2015-02-11 13:40:50 -08003171 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003172 result = mOutput->stream->getBufferSize(&mBufferSize);
3173 LOG_ALWAYS_FATAL_IF(result != OK,
3174 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003175 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003176 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003177 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003178 mFrameCount);
3179 }
3180
Eric Laurentd1f69b02014-12-15 14:33:13 -08003181 mHwSupportsPause = false;
3182 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003183 bool supportsPause = false, supportsResume = false;
3184 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3185 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003186 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003187 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003188 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003189 } else if (supportsResume) {
3190 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003191 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003192 }
3193 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003194 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3195 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3196 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003197
Andy Hungfbfc3952015-01-15 13:33:51 -08003198 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3199 // For best precision, we use float instead of the associated output
3200 // device format (typically PCM 16 bit).
3201
3202 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3203 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3204 mBufferSize = mFrameSize * mFrameCount;
3205
3206 // TODO: We currently use the associated output device channel mask and sample rate.
3207 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3208 // (if a valid mask) to avoid premature downmix.
3209 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3210 // instead of the output device sample rate to avoid loss of high frequency information.
3211 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3212 }
3213
Andy Hung09a50072014-02-27 14:30:47 -08003214 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003215 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003216 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003217 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3218 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003219 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3220 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003221
Eric Laurent81784c32012-11-19 14:55:58 -08003222 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3223 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3224 maxNormalFrameCount = maxNormalFrameCount & ~15;
3225 if (maxNormalFrameCount < minNormalFrameCount) {
3226 maxNormalFrameCount = minNormalFrameCount;
3227 }
3228 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3229 if (multiplier <= 1.0) {
3230 multiplier = 1.0;
3231 } else if (multiplier <= 2.0) {
3232 if (2 * mFrameCount <= maxNormalFrameCount) {
3233 multiplier = 2.0;
3234 } else {
3235 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3236 }
3237 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003238 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003239 }
3240 }
3241 mNormalFrameCount = multiplier * mFrameCount;
3242 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003243 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003244 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3245 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003246 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3247 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003248
Andy Hung08fb1742015-05-31 23:22:10 -07003249 // Check if we want to throttle the processing to no more than 2x normal rate
3250 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003251 mThreadThrottleTimeMs = 0;
3252 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003253 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3254
Andy Hung010a1a12014-03-13 13:57:33 -07003255 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3256 // Originally this was int16_t[] array, need to remove legacy implications.
3257 free(mSinkBuffer);
3258 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003259
Andy Hung5b10a202014-03-13 13:59:29 -07003260 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3261 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3262 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003263 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003264
Andy Hung69aed5f2014-02-25 17:24:40 -08003265 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3266 // drives the output.
3267 free(mMixerBuffer);
3268 mMixerBuffer = NULL;
3269 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003270 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003271 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003272 * audio_bytes_per_sample(mMixerBufferFormat);
3273 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3274 }
Andy Hung98ef9782014-03-04 14:46:50 -08003275 free(mEffectBuffer);
3276 mEffectBuffer = NULL;
3277 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003278 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003279 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003280 * audio_bytes_per_sample(mEffectBufferFormat);
3281 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3282 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003283
Eric Laurentb62d0362021-10-26 17:40:18 +02003284 if (mType == SPATIALIZER) {
3285 free(mPostSpatializerBuffer);
3286 mPostSpatializerBuffer = nullptr;
3287 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3288 * audio_bytes_per_sample(mEffectBufferFormat);
3289 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3290 }
3291
Mikhail Naganov55773032020-10-01 15:08:13 -07003292 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3293 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003294 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3295 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003296 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003297
Eric Laurent81784c32012-11-19 14:55:58 -08003298 // force reconfiguration of effect chains and engines to take new buffer size and audio
3299 // parameters into account
Andy Hungb17d24b2023-08-29 14:26:09 -07003300 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003301 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3302 // matter.
Andy Hungf8635b62023-08-31 16:13:39 -07003303 // create a copy of mEffectChains as calling moveEffectChain_ll()
3304 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003305 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003306 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hungf8635b62023-08-31 16:13:39 -07003307 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003308 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003309 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003310
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003311 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003312 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003313 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07003314 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003315 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3316 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3317 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3318 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3319 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3320 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3321 (int32_t)mHapticChannelMask)
3322 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3323 (int32_t)mHapticChannelCount)
3324 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -07003325 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003326 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3327 (int32_t)mFrameCount) // sic - added HAL
3328 ;
3329 uint32_t latencyMs;
3330 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3331 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3332 }
3333 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003334}
3335
Andy Hung4b17e882023-07-07 13:47:37 -07003336ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003337{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003338 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003339 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003340 }
3341 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003342 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07003343 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003344 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003345 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003346 }
Kevin Rocard12381092018-04-11 09:19:59 -07003347 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003348 MetadataUpdate change;
3349 change.playbackMetadataUpdate = metadata.tracks;
3350 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003351}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003352
Andy Hung4b17e882023-07-07 13:47:37 -07003353void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003354 const StreamOutHalInterface::SourceMetadata& metadata)
3355{
3356 mOutput->stream->updateSourceMetadata(metadata);
3357};
3358
Andy Hung4b17e882023-07-07 13:47:37 -07003359status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003360 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003361{
3362 if (halFrames == NULL || dspFrames == NULL) {
3363 return BAD_VALUE;
3364 }
Andy Hungf8635b62023-08-31 16:13:39 -07003365 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003366 if (initCheck() != NO_ERROR) {
3367 return INVALID_OPERATION;
3368 }
Andy Hung818e7a32016-02-16 18:08:07 -08003369 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003370 *halFrames = framesWritten;
3371
3372 if (isSuspended()) {
3373 // return an estimation of rendered frames when the output is suspended
3374 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003375 *dspFrames = (uint32_t)
3376 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003377 return NO_ERROR;
3378 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003379 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003380 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003381 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003382 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003383 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003384 }
3385}
3386
Andy Hung4b17e882023-07-07 13:47:37 -07003387product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003388{
3389 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3390 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3391 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003392 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003393 }
3394 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003395 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003396 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003397 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003398 }
3399 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003400 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003401}
3402
3403
Andy Hung4b17e882023-07-07 13:47:37 -07003404AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003405{
Andy Hungf8635b62023-08-31 16:13:39 -07003406 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003407 return mOutput;
3408}
3409
Andy Hung4b17e882023-07-07 13:47:37 -07003410AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003411{
Andy Hungf8635b62023-08-31 16:13:39 -07003412 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003413 AudioStreamOut *output = mOutput;
3414 mOutput = NULL;
3415 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3416 // must push a NULL and wait for ack
3417 mOutputSink.clear();
3418 mPipeSink.clear();
3419 mNormalSink.clear();
3420 return output;
3421}
3422
Andy Hungb17d24b2023-08-29 14:26:09 -07003423// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003424sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003425{
3426 if (mOutput == NULL) {
3427 return NULL;
3428 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003429 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003430}
3431
Andy Hung4b17e882023-07-07 13:47:37 -07003432uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003433{
3434 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3435}
3436
Andy Hung4b17e882023-07-07 13:47:37 -07003437status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003438{
3439 if (!isValidSyncEvent(event)) {
3440 return BAD_VALUE;
3441 }
3442
Andy Hungf8635b62023-08-31 16:13:39 -07003443 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003444
3445 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003446 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003447 if (event->triggerSession() == track->sessionId()) {
3448 (void) track->setSyncEvent(event);
3449 return NO_ERROR;
3450 }
3451 }
3452
3453 return NAME_NOT_FOUND;
3454}
3455
Andy Hung4b17e882023-07-07 13:47:37 -07003456bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003457{
3458 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3459}
3460
Andy Hung4b17e882023-07-07 13:47:37 -07003461void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003462 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003463{
Andy Hungfe726a62018-09-27 15:17:25 -07003464 // Miscellaneous track cleanup when removed from the active list,
3465 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003466#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003467 for (const auto& track : tracksToRemove) {
3468 if (track->isExternalTrack()) {
3469 // to track the speaker usage
3470 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003471 }
3472 }
Andy Hungfe726a62018-09-27 15:17:25 -07003473#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003474}
3475
Andy Hung4b17e882023-07-07 13:47:37 -07003476void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003477{
3478 if (!mMasterMute) {
3479 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003480 if (mOutDeviceTypeAddrs.empty()) {
3481 ALOGD("ro.audio.silent is ignored since no output device is set");
3482 return;
3483 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003484 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003485 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3486 return;
3487 }
Eric Laurent81784c32012-11-19 14:55:58 -08003488 if (property_get("ro.audio.silent", value, "0") > 0) {
3489 char *endptr;
3490 unsigned long ul = strtoul(value, &endptr, 0);
3491 if (*endptr == '\0' && ul != 0) {
3492 ALOGD("Silence is golden");
3493 // The setprop command will not allow a property to be changed after
3494 // the first time it is set, so we don't have to worry about un-muting.
3495 setMasterMute_l(true);
3496 }
3497 }
3498 }
3499}
3500
3501// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003502ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003503{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003504 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003505 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003506 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003507 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003508
3509 // If an NBAIO sink is present, use it to write the normal mixer's submix
3510 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003511
Andy Hung010a1a12014-03-13 13:57:33 -07003512 const size_t count = mBytesRemaining / mFrameSize;
3513
Simon Wilson2d590962012-11-29 15:18:50 -08003514 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003515 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003516 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003517 if (screenState != mScreenState) {
3518 mScreenState = screenState;
3519 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3520 if (pipe != NULL) {
3521 pipe->setAvgFrames((mScreenState & 1) ?
3522 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3523 }
3524 }
Andy Hung010a1a12014-03-13 13:57:33 -07003525 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003526 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003527
Eric Laurent81784c32012-11-19 14:55:58 -08003528 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003529 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003530
Andy Hung8946a282018-04-19 20:04:56 -07003531#ifdef TEE_SINK
3532 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3533#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003534 } else {
3535 bytesWritten = framesWritten;
3536 }
3537 // otherwise use the HAL / AudioStreamOut directly
3538 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003539 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003540
Eric Laurentbfb1b832013-01-07 09:53:42 -08003541 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003542 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3543 mWriteAckSequence += 2;
3544 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003545 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003546 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003547 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003548 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003549 // FIXME We should have an implementation of timestamps for direct output threads.
3550 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003551 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003552 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003553
Eric Laurentbfb1b832013-01-07 09:53:42 -08003554 if (mUseAsyncWrite &&
3555 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3556 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003557 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003559 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003560 }
Eric Laurent81784c32012-11-19 14:55:58 -08003561 }
3562
Eric Laurent81784c32012-11-19 14:55:58 -08003563 mNumWrites++;
3564 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003565 if (mStandby) {
3566 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003567 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003568 mStandby = false;
3569 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003570 return bytesWritten;
3571}
3572
Andy Hungb17d24b2023-08-29 14:26:09 -07003573// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003574void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003575 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003576{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003577 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003578 if (outputSink != nullptr) {
3579 outputSink->startMelComputation(processor);
3580 }
Vlad Popab042ee62022-10-20 18:05:00 +02003581}
3582
Andy Hungb17d24b2023-08-29 14:26:09 -07003583// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003584void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003585{
3586 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003587 if (outputSink != nullptr) {
3588 outputSink->stopMelComputation();
3589 }
Vlad Popab042ee62022-10-20 18:05:00 +02003590}
3591
Andy Hung4b17e882023-07-07 13:47:37 -07003592void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003593{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003594 bool supportsDrain = false;
3595 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003596 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3597 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003598 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3599 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003600 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003601 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003602 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003603 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003604 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003605 }
3606}
3607
Andy Hung4b17e882023-07-07 13:47:37 -07003608void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003609{
Eric Laurent275e8e92014-11-30 15:14:47 -08003610 {
Andy Hungf8635b62023-08-31 16:13:39 -07003611 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003612 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003613 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003614 track->invalidate();
3615 }
Andy Hungdae27702016-10-31 14:01:16 -07003616 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3617 // After we exit there are no more track changes sent to BatteryNotifier
3618 // because that requires an active threadLoop.
3619 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3620 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003621 }
Eric Laurent81784c32012-11-19 14:55:58 -08003622}
3623
3624/*
3625The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003626 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003627 - mActiveSleepTimeUs from activeSleepTimeUs()
3628 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003629 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3630 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003631 - maxPeriod from frame count and sample rate (MIXER only)
3632
3633The parameters that affect these derived values are:
3634 - frame count
3635 - frame size
3636 - sample rate
3637 - device type: A2DP or not
3638 - device latency
3639 - format: PCM or not
3640 - active sleep time
3641 - idle sleep time
3642*/
3643
Andy Hung4b17e882023-07-07 13:47:37 -07003644void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003645{
Andy Hung25c2dac2014-02-27 14:56:00 -08003646 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003647 mActiveSleepTimeUs = activeSleepTimeUs();
3648 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003649
Andy Hungd58c4732023-07-20 21:31:38 -07003650 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003651
Eric Laurent42537be2016-01-08 17:16:42 -08003652 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3653 // truncating audio when going to standby.
Andy Hung94dfbb42023-09-06 19:41:47 -07003654 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003655 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3656 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3657 }
3658 }
Eric Laurent81784c32012-11-19 14:55:58 -08003659}
3660
Andy Hung4b17e882023-07-07 13:47:37 -07003661bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003662{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003663 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003664 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003665 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003666 size_t size = mTracks.size();
3667 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003668 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003669 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003670 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003671 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003672 }
3673 }
Eric Laurent13084622016-05-17 10:51:49 -07003674 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003675}
3676
Andy Hung4b17e882023-07-07 13:47:37 -07003677void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003678{
Andy Hungf8635b62023-08-31 16:13:39 -07003679 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003680 invalidateTracks_l(streamType);
3681}
3682
Andy Hung4b17e882023-07-07 13:47:37 -07003683void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07003684 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003685 invalidateTracks_l(portIds);
3686}
3687
Andy Hung4b17e882023-07-07 13:47:37 -07003688bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003689 bool trackMatch = false;
3690 const size_t size = mTracks.size();
3691 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003692 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003693 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3694 t->invalidate();
3695 portIds.erase(t->portId());
3696 trackMatch = true;
3697 }
3698 if (portIds.empty()) {
3699 break;
3700 }
3701 }
3702 return trackMatch;
3703}
3704
jiabinf042b9b2021-05-07 23:46:28 +00003705// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003706IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003707 audio_port_handle_t trackPortId) {
3708 for (size_t i = 0; i < mTracks.size(); i++) {
3709 if (mTracks[i]->portId() == trackPortId) {
3710 return mTracks[i].get();
3711 }
3712 }
3713 return nullptr;
3714}
3715
Andy Hung4b17e882023-07-07 13:47:37 -07003716status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003717{
Glenn Kastend848eb42016-03-08 13:42:11 -08003718 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003719 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003720 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003721
Andy Hungd3639922022-04-28 18:00:49 -07003722 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003723 if (!audio_is_global_session(session)) {
3724 // player sessions on a spatializer output will use a dedicated input buffer and
3725 // will either output multi channel to mEffectBuffer if the track is spatilaized
3726 // or stereo to mPostSpatializerBuffer if not spatialized.
3727 uint32_t channelMask;
3728 bool isSessionSpatialized =
3729 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3730 if (isSessionSpatialized) {
3731 channelMask = mMixerChannelMask;
3732 } else {
3733 channelMask = mChannelMask;
3734 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003735 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003736 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003737 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003738 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003739 &halInBuffer);
3740 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003741
Andy Hung7535ed92023-07-17 17:05:00 -07003742 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003743 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3744 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3745 &halOutBuffer);
3746 if (result != OK) return result;
3747
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003748 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003749
Mikhail Naganov022b9952017-01-04 16:36:51 -08003750 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3751 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003752 } else {
3753 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3754 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3755 // mPostSpatializerBuffer as output buffer
3756 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003757 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003758 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3759 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003760 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003761 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3762 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003763
Eric Laurentb62d0362021-10-26 17:40:18 +02003764 if (session == AUDIO_SESSION_DEVICE) {
3765 halInBuffer = halOutBuffer;
3766 }
3767 }
3768 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003769 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003770 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3771 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3772 &halInBuffer);
3773 if (result != OK) return result;
3774 halOutBuffer = halInBuffer;
3775 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3776 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003777 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003778 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003779 // Only one effect chain can be present in direct output thread and it uses
3780 // the sink buffer as input
3781 if (mType != DIRECT) {
3782 size_t numSamples = mNormalFrameCount
3783 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3784 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003785 const status_t allocateStatus =
3786 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003787 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003788 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003789 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003790
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003791 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003792 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3793 buffer, session);
3794 }
3795 }
3796 }
3797
3798 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003799 // Attach all tracks with same session ID to this chain.
3800 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003801 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003802 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003803 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3804 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003805 track->setMainBuffer(buffer);
3806 chain->incTrackCnt();
3807 }
3808 }
3809
3810 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003811 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003812 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003813 ALOGV("addEffectChain_l() activating track %p on session %d",
3814 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003815 chain->incActiveTrackCnt();
3816 }
3817 }
3818 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003819
Eric Laurentaaa44472014-09-12 17:41:50 -07003820 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003821 chain->setInBuffer(halInBuffer);
3822 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003823 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3824 // chains list in order to be processed last as it contains output device effects.
3825 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3826 // processing effects specific to an output stream before effects applied to all streams
3827 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003828 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3829 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003830 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003831 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003832 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003833 // Effect chain for other sessions are inserted at beginning of effect
3834 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003835 // sessions is not important.
3836 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003837 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3838 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003839 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003840 size_t size = mEffectChains.size();
3841 size_t i = 0;
3842 for (i = 0; i < size; i++) {
3843 if (mEffectChains[i]->sessionId() < session) {
3844 break;
3845 }
3846 }
3847 mEffectChains.insertAt(chain, i);
3848 checkSuspendOnAddEffectChain_l(chain);
3849
3850 return NO_ERROR;
3851}
3852
Andy Hung4b17e882023-07-07 13:47:37 -07003853size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003854{
Glenn Kastend848eb42016-03-08 13:42:11 -08003855 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003856
3857 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3858
3859 for (size_t i = 0; i < mEffectChains.size(); i++) {
3860 if (chain == mEffectChains[i]) {
3861 mEffectChains.removeAt(i);
3862 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003863 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003864 if (session == track->sessionId()) {
3865 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3866 chain.get(), session);
3867 chain->decActiveTrackCnt();
3868 }
3869 }
3870
3871 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003872 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003873 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003874 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003875 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003876 chain->decTrackCnt();
3877 }
3878 }
3879 break;
3880 }
3881 }
3882 return mEffectChains.size();
3883}
3884
Andy Hung4b17e882023-07-07 13:47:37 -07003885status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003886 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003887{
Andy Hungf8635b62023-08-31 16:13:39 -07003888 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003889 return attachAuxEffect_l(track, EffectId);
3890}
3891
Andy Hung4b17e882023-07-07 13:47:37 -07003892status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003893 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003894{
3895 status_t status = NO_ERROR;
3896
3897 if (EffectId == 0) {
3898 track->setAuxBuffer(0, NULL);
3899 } else {
3900 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003901 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003902 if (effect != 0) {
3903 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3904 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3905 } else {
3906 status = INVALID_OPERATION;
3907 }
3908 } else {
3909 status = BAD_VALUE;
3910 }
3911 }
3912 return status;
3913}
3914
Andy Hung4b17e882023-07-07 13:47:37 -07003915void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003916{
3917 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003918 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003919 if (track->auxEffectId() == effectId) {
3920 attachAuxEffect_l(track, 0);
3921 }
3922 }
3923}
3924
Andy Hung4b17e882023-07-07 13:47:37 -07003925bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003926NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003927{
Andy Hung78d8d952023-05-30 18:10:23 -07003928 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003929
Andy Hung45a38f22023-10-03 10:49:34 -07003930 if (mType == SPATIALIZER) {
3931 const pid_t tid = getTid();
3932 if (tid == -1) { // odd: we are here, we must be a running thread.
3933 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3934 } else {
3935 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3936 if (priorityBoost > 0) {
3937 stream()->setHalThreadPriority(priorityBoost);
3938 }
3939 }
3940 }
3941
Andy Hung11e74242023-06-26 19:20:57 -07003942 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003943
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003944 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003945 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003946
3947 // MIXER
3948 nsecs_t lastWarning = 0;
3949
3950 // DUPLICATING
3951 // FIXME could this be made local to while loop?
3952 writeFrames = 0;
3953
3954 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003955 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003956
Andy Hungd3639922022-04-28 18:00:49 -07003957 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003958 sleepTimeShift = 0;
3959 }
3960
3961 CpuStats cpuStats;
3962 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3963
3964 acquireWakeLock();
3965
Glenn Kasteneef598c2017-04-03 14:41:13 -07003966 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3967 // thread associated with this PlaybackThread.
3968 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3969 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003970 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3971 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003972 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003973 const char *logString = NULL;
3974
rago1bb90822017-05-02 18:31:48 -07003975 // Estimated time for next buffer to be written to hal. This is used only on
3976 // suspended mode (for now) to help schedule the wait time until next iteration.
3977 nsecs_t timeLoopNextNs = 0;
3978
Eric Laurent664539d2013-09-23 18:24:31 -07003979 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003980
Andy Hung2dbffc22018-08-08 18:50:41 -07003981 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003982
Eric Laurentb3f315a2021-07-13 15:09:05 +02003983 sendCheckOutputStageEffectsEvent();
3984
Andy Hung446f4df2019-02-21 12:26:41 -08003985 // loopCount is used for statistics and diagnostics.
3986 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003987 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003988 // Log merge requests are performed during AudioFlinger binder transactions, but
3989 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07003990 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003991
Eric Laurent81784c32012-11-19 14:55:58 -08003992 cpuStats.sample(myName);
3993
Andy Hung116bc262023-06-20 18:56:17 -07003994 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003995 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003996 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07003997 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003998
Andy Hung2dbffc22018-08-08 18:50:41 -07003999 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4000 //
Andy Hungb17d24b2023-08-29 14:26:09 -07004001 // Note: we access outDeviceTypes() outside of mutex().
Andy Hung94dfbb42023-09-06 19:41:47 -07004002 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004003 // Here, we try for the AF lock, but do not block on it as the latency
4004 // is more informational.
Andy Hung85a07452023-08-28 18:36:53 -07004005 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd25fe392023-07-13 16:52:46 -07004006 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004007 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004008 status_t status = INVALID_OPERATION;
4009 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07004010 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07004011 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004012 && swPatches.size() > 0) {
4013 status = swPatches[0].getLatencyMs_l(&latencyMs);
4014 downstreamPatchHandle = swPatches[0].getPatchHandle();
4015 }
4016 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004017 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004018 lastDownstreamPatchHandle = downstreamPatchHandle;
4019 }
4020 if (status == OK) {
4021 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004022 // latency of 5 seconds).
4023 const double minLatency = 0., maxLatency = 5000.;
4024 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004025 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004026 } else {
4027 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004028 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004029 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004030 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004031 }
Andy Hung7535ed92023-07-17 17:05:00 -07004032 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004033 }
4034 } else {
4035 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4036 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004037 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004038 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4039 }
4040 }
4041
Eric Laurentb3f315a2021-07-13 15:09:05 +02004042 if (mCheckOutputStageEffects.exchange(false)) {
4043 checkOutputStageEffects();
4044 }
4045
Vlad Popa7e81cea2023-01-19 16:34:16 +01004046 MetadataUpdate metadataUpdate;
Andy Hungb17d24b2023-08-29 14:26:09 -07004047 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004048
Andy Hungb17d24b2023-08-29 14:26:09 -07004049 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004050
Eric Laurent021cf962014-05-13 10:18:14 -07004051 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004052 if (mCheckOutputStageEffects.load()) {
4053 continue;
4054 }
Eric Laurent10351942014-05-08 18:49:52 -07004055
Andy Hungb17d24b2023-08-29 14:26:09 -07004056 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004057 if (logString != NULL) {
4058 mNBLogWriter->logTimestamp();
4059 mNBLogWriter->log(logString);
4060 logString = NULL;
4061 }
4062
Dean Wheatley12473e92021-03-18 23:00:55 +11004063 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004064
Eric Laurent81784c32012-11-19 14:55:58 -08004065 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004066 if (mSignalPending) {
4067 // A signal was raised while we were unlocked
4068 mSignalPending = false;
4069 } else if (waitingAsyncCallback_l()) {
4070 if (exitPending()) {
4071 break;
4072 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004073 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004074 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004075 releaseWakeLock_l();
4076 released = true;
4077 }
Andy Hung10cbff12017-02-21 17:30:14 -08004078
4079 const int64_t waitNs = computeWaitTimeNs_l();
4080 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungb17d24b2023-08-29 14:26:09 -07004081 std::cv_status cvstatus =
4082 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4083 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004084 mSignalPending = true; // if timeout recheck everything
4085 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004086 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004087 if (released) {
4088 acquireWakeLock_l();
4089 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004090 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4091 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004092
4093 continue;
4094 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004095 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004096 isSuspended()) {
4097 // put audio hardware into standby after short delay
4098 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004099
4100 threadLoop_standby();
4101
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004102 // This is where we go into standby
4103 if (!mStandby) {
4104 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004105 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004106 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004107 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004108 }
Andy Hungd0979812019-02-21 15:51:44 -08004109 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004110 }
4111
Eric Tan39ec8d62018-07-24 09:49:29 -07004112 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004113 // we're about to wait, flush the binder command buffer
4114 IPCThreadState::self()->flushCommands();
4115
4116 clearOutputTracks();
4117
4118 if (exitPending()) {
4119 break;
4120 }
4121
4122 releaseWakeLock_l();
4123 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004124 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -07004125 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004126 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004127 acquireWakeLock_l();
4128
4129 mMixerStatus = MIXER_IDLE;
4130 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4131 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004132 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004133 checkSilentMode_l();
4134
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004135 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4136 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004137 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004138 sleepTimeShift = 0;
4139 }
4140
4141 continue;
4142 }
4143 }
Eric Laurent81784c32012-11-19 14:55:58 -08004144 // mMixerStatusIgnoringFastTracks is also updated internally
4145 mMixerStatus = prepareTracks_l(&tracksToRemove);
4146
Andy Hung94dfbb42023-09-06 19:41:47 -07004147 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004148
Vlad Popa7e81cea2023-01-19 16:34:16 +01004149 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004150
Eric Laurent81784c32012-11-19 14:55:58 -08004151 // prevent any changes in effect chain list and in each effect chain
4152 // during mixing and effect process as the audio buffers could be deleted
4153 // or modified if an effect is created or deleted
4154 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004155
4156 // Determine which session to pick up haptic data.
4157 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004158 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004159 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004160 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004161 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004162 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004163 if (effectChain != nullptr
4164 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004165 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004166 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004167 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004168 break;
4169 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004170 if (activeHapticSessionId == AUDIO_SESSION_NONE
4171 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004172 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004173 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004174 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004175 }
4176 }
4177 }
4178
Andy Hungc1646382019-04-30 16:12:10 -07004179 // Acquire a local copy of active tracks with lock (release w/o lock).
4180 //
4181 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4182 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4183 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4184 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004185
4186 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004187
Jiabin Huangfb476842022-12-06 03:18:10 +00004188 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004189 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004190 }
4191
Eric Laurent19952e12023-04-20 10:08:29 +02004192 // signal actual start of output stream when the render position reported by the kernel
4193 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004194 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4195 && (mKernelPositionOnStandby
4196 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004197 mHalStarted = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07004198 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004199 }
Andy Hungb17d24b2023-08-29 14:26:09 -07004200 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004201
Eric Laurentbfb1b832013-01-07 09:53:42 -08004202 if (mBytesRemaining == 0) {
4203 mCurrentWriteLength = 0;
4204 if (mMixerStatus == MIXER_TRACKS_READY) {
4205 // threadLoop_mix() sets mCurrentWriteLength
4206 threadLoop_mix();
4207 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4208 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004209 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004210 // must be written to HAL
4211 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004212 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004213 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004214
4215 // Tally underrun frames as we are inserting 0s here.
4216 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004217 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004218 && !track->isStopped()
4219 && !track->isPaused()
4220 && !track->isTerminated()) {
4221 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4222 __func__, track->id(), track->getTrackStateAsString(),
4223 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004224 track->audioTrackServerProxy()->tallyUnderrunFrames(
4225 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004226 }
4227 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004228 }
4229 }
Andy Hung98ef9782014-03-04 14:46:50 -08004230 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004231 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004232 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004233 // or mSinkBuffer (if there are no effects and there is no data already copied to
4234 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004235 //
4236 // This is done pre-effects computation; if effects change to
4237 // support higher precision, this needs to move.
4238 //
4239 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004240 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004241 uint32_t mixerChannelCount = mEffectBufferValid ?
4242 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004243 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004244 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4245 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4246
David Li88ee0902022-06-22 10:01:21 +08004247 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4248 // do these processes after effects are applied.
4249 if (!mEffectBufferValid) {
4250 // mono blend occurs for mixer threads only (not direct or offloaded)
4251 // and is handled here if we're going directly to the sink.
4252 if (requireMonoBlend()) {
4253 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4254 mNormalFrameCount, true /*limit*/);
4255 }
Andy Hung2ddee192015-12-18 17:34:44 -08004256
David Li88ee0902022-06-22 10:01:21 +08004257 if (!hasFastMixer()) {
4258 // Balance must take effect after mono conversion.
4259 // We do it here if there is no FastMixer.
4260 // mBalance detects zero balance within the class for speed
4261 // (not needed here).
4262 mBalance.setBalance(mMasterBalance.load());
4263 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4264 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004265 }
4266
Andy Hung98ef9782014-03-04 14:46:50 -08004267 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004268 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004269
4270 // If we're going directly to the sink and there are haptic channels,
4271 // we should adjust channels as the sample data is partially interleaved
4272 // in this case.
4273 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4274 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4275 mChannelCount + mHapticChannelCount,
4276 audio_bytes_per_sample(format),
4277 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4278 }
Andy Hung98ef9782014-03-04 14:46:50 -08004279 }
4280
Eric Laurentbfb1b832013-01-07 09:53:42 -08004281 mBytesRemaining = mCurrentWriteLength;
4282 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004283 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4284 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4285 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4286 mBytesWritten += mBytesRemaining;
4287 mFramesWritten += framesRemaining;
4288 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004289 mBytesRemaining = 0;
4290 }
Eric Laurent81784c32012-11-19 14:55:58 -08004291
Eric Laurentbfb1b832013-01-07 09:53:42 -08004292 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004293 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294 for (size_t i = 0; i < effectChains.size(); i ++) {
4295 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004296 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004297 if (activeHapticSessionId != AUDIO_SESSION_NONE
4298 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004299 // Haptic data is active in this case, copy it directly from
4300 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004301 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4302 audio_channel_count_from_out_mask(mMixerChannelMask) :
4303 mChannelCount;
4304 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4305 hapticSessionChannelCount = mChannelCount;
4306 }
4307
jiabin47affe52019-04-04 18:02:07 -07004308 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004309 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004310 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004311 memcpy_by_audio_format(
4312 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004313 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004314 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004315 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004316 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004317 }
Eric Laurent81784c32012-11-19 14:55:58 -08004318 }
4319 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004320 // Process effect chains for offloaded thread even if no audio
4321 // was read from audio track: process only updates effect state
4322 // and thus does have to be synchronized with audio writes but may have
4323 // to be called while waiting for async write callback
4324 if (mType == OFFLOAD) {
4325 for (size_t i = 0; i < effectChains.size(); i ++) {
4326 effectChains[i]->process_l();
4327 }
4328 }
Eric Laurent81784c32012-11-19 14:55:58 -08004329
Andy Hung98ef9782014-03-04 14:46:50 -08004330 // Only if the Effects buffer is enabled and there is data in the
4331 // Effects buffer (buffer valid), we need to
4332 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004333 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004334 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004335 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004336 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004337 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004338 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004339 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004340 }
4341
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004342 if (!hasFastMixer()) {
4343 // Balance must take effect after mono conversion.
4344 // We do it here if there is no FastMixer.
4345 // mBalance detects zero balance within the class for speed (not needed here).
4346 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004347 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004348 }
4349
Eric Laurentb62d0362021-10-26 17:40:18 +02004350 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4351 // mPostSpatializerBuffer if the haptics track is spatialized.
4352 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4353 // For other thread types, the haptics channels are already in mEffectBuffer.
4354 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4355 const size_t srcBufferSize = mNormalFrameCount *
4356 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4357 mEffectBufferFormat);
4358 const size_t dstBufferSize = mNormalFrameCount
4359 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4360
4361 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4362 mEffectBufferFormat,
4363 (uint8_t*)mEffectBuffer + srcBufferSize,
4364 mEffectBufferFormat,
4365 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004366 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004367 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4368 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4369 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4370 // Clamp PCM float values more than this distance from 0 to insulate
4371 // a HAL which doesn't handle NaN correctly.
4372 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4373 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4374 static_cast<const float*>(effectBuffer),
4375 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4376 } else {
4377 memcpy_by_audio_format(mSinkBuffer, mFormat,
4378 effectBuffer, mEffectBufferFormat, framesToCopy);
4379 }
jiabin245cdd92018-12-07 17:55:15 -08004380 // The sample data is partially interleaved when haptic channels exist,
4381 // we need to adjust channels here.
4382 if (mHapticChannelCount > 0) {
4383 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4384 mChannelCount + mHapticChannelCount,
4385 audio_bytes_per_sample(mFormat),
4386 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4387 }
Andy Hung98ef9782014-03-04 14:46:50 -08004388 }
4389
Eric Laurent81784c32012-11-19 14:55:58 -08004390 // enable changes in effect chain
4391 unlockEffectChains(effectChains);
4392
Vlad Popafce10862023-02-03 10:37:07 +01004393 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004394 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004395 metadataUpdate.playbackMetadataUpdate);
4396 }
4397
Eric Laurentbfb1b832013-01-07 09:53:42 -08004398 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004399 // mSleepTimeUs == 0 means we must write to audio hardware
4400 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004401 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004402 // writePeriodNs is updated >= 0 when ret > 0.
4403 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004405 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004406 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004407 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004408 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004409 if (ret < 0) {
4410 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004411 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004412 mBytesWritten += ret;
4413 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004414 const int64_t frames = ret / mFrameSize;
4415 mFramesWritten += frames;
4416
4417 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4418 // process information relating to write time.
4419 if (audio_has_proportional_frames(mFormat)) {
4420 // we are in a continuous mixing cycle
4421 if (mMixerStatus == MIXER_TRACKS_READY &&
4422 loopCount == lastLoopCountWritten + 1) {
4423
4424 const double jitterMs =
4425 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4426 {frames, writePeriodNs},
4427 {0, 0} /* lastTimestamp */, mSampleRate);
4428 const double processMs =
4429 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4430
Andy Hungf8635b62023-08-31 16:13:39 -07004431 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004432 mIoJitterMs.add(jitterMs);
4433 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004434
4435 if (mPipeSink.get() != nullptr) {
4436 // Using the Monopipe availableToWrite, we estimate the current
4437 // buffer size.
4438 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4439 const ssize_t
4440 availableToWrite = mPipeSink->availableToWrite();
4441 const size_t pipeFrames = monoPipe->maxFrames();
4442 const size_t
4443 remainingFrames = pipeFrames - max(availableToWrite, 0);
4444 mMonopipePipeDepthStats.add(remainingFrames);
4445 }
Andy Hung446f4df2019-02-21 12:26:41 -08004446 }
4447
4448 // write blocked detection
4449 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004450 if ((mType == MIXER || mType == SPATIALIZER)
4451 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004452 mNumDelayedWrites++;
4453 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4454 ATRACE_NAME("underrun");
4455 ALOGW("write blocked for %lld msecs, "
4456 "%d delayed writes, thread %d",
4457 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4458 mNumDelayedWrites, mId);
4459 lastWarning = lastIoEndNs;
4460 }
4461 }
4462 }
4463 // update timing info.
4464 mLastIoBeginNs = lastIoBeginNs;
4465 mLastIoEndNs = lastIoEndNs;
4466 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004467 }
4468 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4469 (mMixerStatus == MIXER_DRAIN_ALL)) {
4470 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004471 }
Andy Hungd3639922022-04-28 18:00:49 -07004472 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004473
4474 if (mThreadThrottle
4475 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004476 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004477 // Limit MixerThread data processing to no more than twice the
4478 // expected processing rate.
4479 //
4480 // This helps prevent underruns with NuPlayer and other applications
4481 // which may set up buffers that are close to the minimum size, or use
4482 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4483 //
4484 // The throttle smooths out sudden large data drains from the device,
4485 // e.g. when it comes out of standby, which often causes problems with
4486 // (1) mixer threads without a fast mixer (which has its own warm-up)
4487 // (2) minimum buffer sized tracks (even if the track is full,
4488 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004489 //
4490 // Total time spent in last processing cycle equals time spent in
4491 // 1. threadLoop_write, as well as time spent in
4492 // 2. threadLoop_mix (significant for heavy mixing, especially
4493 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004494
Andy Hung446f4df2019-02-21 12:26:41 -08004495 // it's OK if deltaMs is an overestimate.
4496
4497 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004498
Ivan Lozanoea04d392017-11-07 14:37:07 -08004499 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004500 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004501 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004502
Andy Hung08fb1742015-05-31 23:22:10 -07004503 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004504 // notify of throttle start on verbose log
4505 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4506 "mixer(%p) throttle begin:"
4507 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004508 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004509 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004510 // Throttle must be attributed to the previous mixer loop's write time
4511 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004512 // This also ensures proper timing statistics.
4513 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004514 } else {
4515 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4516 if (diff > 0) {
4517 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004518 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004519 ALOGD_IF(!isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004520 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004521 !isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004522 outDeviceTypes_l(),
4523 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004524 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004525 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4526 }
Andy Hung08fb1742015-05-31 23:22:10 -07004527 }
4528 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004529 }
Eric Laurent81784c32012-11-19 14:55:58 -08004530
Eric Laurentbfb1b832013-01-07 09:53:42 -08004531 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004532 ATRACE_BEGIN("sleep");
Andy Hungb17d24b2023-08-29 14:26:09 -07004533 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004534 // suspended requires accurate metering of sleep time.
4535 if (isSuspended()) {
4536 // advance by expected sleepTime
4537 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4538 const nsecs_t nowNs = systemTime();
4539
4540 // compute expected next time vs current time.
4541 // (negative deltas are treated as delays).
4542 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4543 if (deltaNs < -kMaxNextBufferDelayNs) {
4544 // Delays longer than the max allowed trigger a reset.
4545 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4546 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4547 timeLoopNextNs = nowNs + deltaNs;
4548 } else if (deltaNs < 0) {
4549 // Delays within the max delay allowed: zero the delta/sleepTime
4550 // to help the system catch up in the next iteration(s)
4551 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4552 deltaNs = 0;
4553 }
4554 // update sleep time (which is >= 0)
4555 mSleepTimeUs = deltaNs / 1000;
4556 }
Eric Laurente93cc032016-05-05 10:15:10 -07004557 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004558 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004559 }
Glenn Kastene7754022014-10-31 12:11:26 -07004560 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004561 }
Eric Laurent81784c32012-11-19 14:55:58 -08004562 }
4563
4564 // Finally let go of removed track(s), without the lock held
4565 // since we can't guarantee the destructors won't acquire that
4566 // same lock. This will also mutate and push a new fast mixer state.
4567 threadLoop_removeTracks(tracksToRemove);
4568 tracksToRemove.clear();
4569
4570 // FIXME I don't understand the need for this here;
4571 // it was in the original code but maybe the
4572 // assignment in saveOutputTracks() makes this unnecessary?
4573 clearOutputTracks();
4574
4575 // Effect chains will be actually deleted here if they were removed from
4576 // mEffectChains list during mixing or effects processing
4577 effectChains.clear();
4578
4579 // FIXME Note that the above .clear() is no longer necessary since effectChains
4580 // is now local to this block, but will keep it for now (at least until merge done).
4581 }
4582
Eric Laurentbfb1b832013-01-07 09:53:42 -08004583 threadLoop_exit();
4584
Eric Laurentcf817a22014-08-04 20:36:31 -07004585 if (!mStandby) {
4586 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004587 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004588 }
4589
4590 releaseWakeLock();
4591
4592 ALOGV("Thread %p type %d exiting", this, mType);
4593 return false;
4594}
4595
Andy Hung4b17e882023-07-07 13:47:37 -07004596void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004597{
Dean Wheatley12473e92021-03-18 23:00:55 +11004598 if (mStandby) {
4599 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4600 return;
4601 } else if (mHwPaused) {
4602 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4603 return;
4604 }
4605
4606 // Gather the framesReleased counters for all active tracks,
4607 // and associate with the sink frames written out. We need
4608 // this to convert the sink timestamp to the track timestamp.
4609 bool kernelLocationUpdate = false;
4610 ExtendedTimestamp timestamp; // use private copy to fetch
4611
4612 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4613 // HAL may be draining some small duration buffered data for fade out.
4614 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4615 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4616 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4617 mSampleRate);
4618
Andy Hung94dfbb42023-09-06 19:41:47 -07004619 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004620 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4621 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4622 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4623 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4624 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4625 = correctedTimestamp.mFrames;
4626 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4627 = correctedTimestamp.mTimeNs;
4628 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4629 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4630 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4631
4632 // Note: Downstream latency only added if timestamp correction enabled.
4633 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4634 const int64_t newPosition =
4635 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4636 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4637 // prevent retrograde
4638 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4639 newPosition,
4640 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4641 - mSuspendedFrames));
4642 }
4643 }
4644
4645 // We always fetch the timestamp here because often the downstream
4646 // sink will block while writing.
4647
4648 // We keep track of the last valid kernel position in case we are in underrun
4649 // and the normal mixer period is the same as the fast mixer period, or there
4650 // is some error from the HAL.
4651 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4652 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4653 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4654 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4655 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4656
4657 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4658 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4659 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4660 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4661 }
4662
4663 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4664 kernelLocationUpdate = true;
4665 } else {
4666 ALOGVV("getTimestamp error - no valid kernel position");
4667 }
4668
4669 // copy over kernel info
4670 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4671 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4672 + mSuspendedFrames; // add frames discarded when suspended
4673 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4674 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4675 } else {
4676 mTimestampVerifier.error();
4677 }
4678
4679 // mFramesWritten for non-offloaded tracks are contiguous
4680 // even after standby() is called. This is useful for the track frame
4681 // to sink frame mapping.
4682 bool serverLocationUpdate = false;
4683 if (mFramesWritten != mLastFramesWritten) {
4684 serverLocationUpdate = true;
4685 mLastFramesWritten = mFramesWritten;
4686 }
4687 // Only update timestamps if there is a meaningful change.
4688 // Either the kernel timestamp must be valid or we have written something.
4689 if (kernelLocationUpdate || serverLocationUpdate) {
4690 if (serverLocationUpdate) {
4691 // use the time before we called the HAL write - it is a bit more accurate
4692 // to when the server last read data than the current time here.
4693 //
4694 // If we haven't written anything, mLastIoBeginNs will be -1
4695 // and we use systemTime().
4696 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4697 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung160664b2023-09-15 18:19:28 -07004698 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004699 }
4700
Andy Hung11e74242023-06-26 19:20:57 -07004701 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004702 if (!t->isFastTrack()) {
4703 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004704 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004705 mFramesWritten,
4706 mSampleRate,
4707 mTimestamp);
4708 }
4709 }
4710 }
4711
4712 if (audio_has_proportional_frames(mFormat)) {
4713 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4714 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4715 mLatencyMs.add(latencyMs);
4716 }
4717 }
4718#if 0
4719 // logFormat example
4720 if (z % 100 == 0) {
4721 timespec ts;
4722 clock_gettime(CLOCK_MONOTONIC, &ts);
4723 LOGT("This is an integer %d, this is a float %f, this is my "
4724 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4725 LOGT("A deceptive null-terminated string %\0");
4726 }
4727 ++z;
4728#endif
4729}
4730
Andy Hungb17d24b2023-08-29 14:26:09 -07004731// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07004732void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungb17d24b2023-08-29 14:26:09 -07004733NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004734{
Andy Hunga7187712023-12-05 17:28:17 -08004735 if (tracksToRemove.empty()) return;
4736
4737 // Block all incoming TrackHandle requests until we are finished with the release.
4738 setThreadBusy_l(true);
4739
Andy Hungfe726a62018-09-27 15:17:25 -07004740 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004741 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004742 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004743 if (chain != 0) {
4744 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4745 __func__, track->id(), chain.get(), track->sessionId());
4746 chain->decActiveTrackCnt();
4747 }
Andy Hunga7187712023-12-05 17:28:17 -08004748
Andy Hungfe726a62018-09-27 15:17:25 -07004749 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hunga7187712023-12-05 17:28:17 -08004750 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004751 if (track->isExternalTrack()) {
Andy Hunga7187712023-12-05 17:28:17 -08004752 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004753 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004754 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004755 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004756 }
Andy Hunga7187712023-12-05 17:28:17 -08004757 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004758 }
jiabineb3bda02020-06-30 14:07:03 -07004759 if (mHapticChannelCount > 0 &&
4760 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4761 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004762 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004763 // Unlock due to VibratorService will lock for this call and will
4764 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004765 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungb17d24b2023-08-29 14:26:09 -07004766 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004767
4768 // When the track is stop, set the haptic intensity as MUTE
4769 // for the HapticGenerator effect.
4770 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004771 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004772 }
jiabin245cdd92018-12-07 17:55:15 -08004773 }
Andy Hunga7187712023-12-05 17:28:17 -08004774
4775 // Under lock, the track is removed from the active tracks list.
4776 //
4777 // Once the track is no longer active, the TrackHandle may directly
4778 // modify it as the threadLoop() is no longer responsible for its maintenance.
4779 // Do not modify the track from threadLoop after the mutex is unlocked
4780 // if it is not active.
4781 mActiveTracks.remove(track);
4782
4783 if (track->isTerminated()) {
4784 // remove from our tracks vector
4785 removeTrack_l(track);
4786 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004787 }
Andy Hunga7187712023-12-05 17:28:17 -08004788
4789 // Allow incoming TrackHandle requests. We still hold the mutex,
4790 // so pending TrackHandle requests will occur after we unlock it.
4791 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004792}
Eric Laurent81784c32012-11-19 14:55:58 -08004793
Andy Hung4b17e882023-07-07 13:47:37 -07004794status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004795{
4796 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004797 ExtendedTimestamp ets;
4798 status_t status = mNormalSink->getTimestamp(ets);
4799 if (status == NO_ERROR) {
4800 status = ets.getBestTimestamp(&timestamp);
4801 }
4802 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004803 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004804 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004805 collectTimestamps_l();
4806 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4807 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004808 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004809 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4810 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4811 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4812 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4813 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004814 }
4815 return INVALID_OPERATION;
4816}
Eric Laurent1c333e22014-05-20 10:48:17 -07004817
Eric Laurenteab90452019-06-24 15:17:46 -07004818// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4819// still applied by the mixer.
4820// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4821// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4822// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004823status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004824{
4825 status_t result = NO_ERROR;
4826 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4827 if (*volume != mLeftVolFloat) {
4828 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004829 // HAL can return INVALID_OPERATION if operation is not supported.
4830 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004831 "Error when setting output stream volume: %d", result);
4832 if (result == NO_ERROR) {
4833 mLeftVolFloat = *volume;
4834 }
4835 }
4836 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4837 // remove stream volume contribution from software volume.
4838 if (mLeftVolFloat == *volume) {
4839 *volume = 1.0f;
4840 }
4841 }
4842 return result;
4843}
4844
Andy Hung4b17e882023-07-07 13:47:37 -07004845status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004846 audio_patch_handle_t *handle)
4847{
Andy Hungf60abce2016-08-26 11:37:54 -07004848 status_t status;
4849 if (property_get_bool("af.patch_park", false /* default_value */)) {
4850 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4851 // or if HAL does not properly lock against access.
4852 AutoPark<FastMixer> park(mFastMixer);
4853 status = PlaybackThread::createAudioPatch_l(patch, handle);
4854 } else {
4855 status = PlaybackThread::createAudioPatch_l(patch, handle);
4856 }
Eric Laurentb0463942022-12-20 16:31:10 +01004857
4858 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004859 return status;
4860}
4861
Andy Hung4b17e882023-07-07 13:47:37 -07004862status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004863 audio_patch_handle_t *handle)
4864{
4865 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004866
4867 // store new device and send to effects
4868 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004869 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004870 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004871 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4872 && !mOutput->audioHwDev->supportsAudioPatches(),
4873 "Enumerated device type(%#x) must not be used "
4874 "as it does not support audio patches",
4875 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004876 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004877 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4878 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004879 }
4880
François Gaffie0c280aa2018-07-25 10:02:15 +02004881 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004882#ifdef ADD_BATTERY_DATA
4883 // when changing the audio output device, call addBatteryData to notify
4884 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004885 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004886 uint32_t params = 0;
4887 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004888 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004889 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004890 }
4891
Eric Laurent054d9d32015-04-24 08:48:48 -07004892 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004893 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004894 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4895 }
4896
4897 if (params != 0) {
4898 addBatteryData(params);
4899 }
4900 }
4901#endif
4902
4903 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004904 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004905 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004906
jiabinc52b1ff2019-10-31 17:20:42 -07004907 // mPatch.num_sinks is not set when the thread is created so that
4908 // the first patch creation triggers an ioConfigChanged callback
4909 bool configChanged = (mPatch.num_sinks == 0) ||
4910 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004911 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004912 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004913 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004914
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004915 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004916 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4917 status = hwDevice->createAudioPatch(patch->num_sources,
4918 patch->sources,
4919 patch->num_sinks,
4920 patch->sinks,
4921 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004922 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004923 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004924 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004925 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004926 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004927
4928 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004929 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004930 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004931 // also dispatch to active AudioTracks for MediaMetrics
4932 for (const auto &track : mActiveTracks) {
4933 track->logEndInterval();
4934 track->logBeginInterval(patchSinksAsString);
4935 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004936
Eric Laurente8726fe2015-06-26 09:39:24 -07004937 if (configChanged) {
4938 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4939 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004940 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004941 mActiveTracks.setHasChanged();
4942
Eric Laurent1c333e22014-05-20 10:48:17 -07004943 return status;
4944}
4945
Andy Hung4b17e882023-07-07 13:47:37 -07004946status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004947{
Andy Hungf60abce2016-08-26 11:37:54 -07004948 status_t status;
4949 if (property_get_bool("af.patch_park", false /* default_value */)) {
4950 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4951 // or if HAL does not properly lock against access.
4952 AutoPark<FastMixer> park(mFastMixer);
4953 status = PlaybackThread::releaseAudioPatch_l(handle);
4954 } else {
4955 status = PlaybackThread::releaseAudioPatch_l(handle);
4956 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004957 return status;
4958}
4959
Andy Hung4b17e882023-07-07 13:47:37 -07004960status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004961{
4962 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004963
jiabinc52b1ff2019-10-31 17:20:42 -07004964 mPatch = audio_patch{};
4965 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004966
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004967 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004968 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4969 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004970 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004971 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004972 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004973 // Force meteadata update after a route change
4974 mActiveTracks.setHasChanged();
4975
Eric Laurent1c333e22014-05-20 10:48:17 -07004976 return status;
4977}
4978
Andy Hung4b17e882023-07-07 13:47:37 -07004979void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004980{
Andy Hungf8635b62023-08-31 16:13:39 -07004981 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004982 mTracks.add(track);
4983}
4984
Andy Hung4b17e882023-07-07 13:47:37 -07004985void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004986{
Andy Hungf8635b62023-08-31 16:13:39 -07004987 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004988 destroyTrack_l(track);
4989}
4990
Andy Hung4b17e882023-07-07 13:47:37 -07004991void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004992{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004993 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004994 config->role = AUDIO_PORT_ROLE_SOURCE;
4995 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4996 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004997 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4998 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4999 config->flags.output = mOutput->flags;
5000 }
Eric Laurent83b88082014-06-20 18:31:16 -07005001}
5002
Eric Laurent81784c32012-11-19 14:55:58 -08005003// ----------------------------------------------------------------------------
5004
Andy Hung4b17e882023-07-07 13:47:37 -07005005/* static */
5006sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07005007 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07005008 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07005009 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07005010}
5011
Andy Hung7535ed92023-07-17 17:05:00 -07005012MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005013 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07005014 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005015 // mAudioMixer below
5016 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005017 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005018 mFastMixerFutex(0),
5019 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005020 // mOutputSink below
5021 // mPipeSink below
5022 // mNormalSink below
5023{
Andy Hung7535ed92023-07-17 17:05:00 -07005024 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005025 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005026 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005027 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005028 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5029 mNormalFrameCount);
5030 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5031
Andy Hungfbfc3952015-01-15 13:33:51 -08005032 if (type == DUPLICATING) {
5033 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5034 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5035 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5036 return;
5037 }
Eric Laurent81784c32012-11-19 14:55:58 -08005038 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005039 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005040 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005041 const NBAIO_Format offers[1] = {Format_from_SR_C(
5042 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005043#if !LOG_NDEBUG
5044 ssize_t index =
5045#else
5046 (void)
5047#endif
5048 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005049 ALOG_ASSERT(index == 0);
5050
5051 // initialize fast mixer depending on configuration
5052 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005053 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005054 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005055 } else {
5056 switch (kUseFastMixer) {
5057 case FastMixer_Never:
5058 initFastMixer = false;
5059 break;
5060 case FastMixer_Always:
5061 initFastMixer = true;
5062 break;
5063 case FastMixer_Static:
5064 case FastMixer_Dynamic:
5065 initFastMixer = mFrameCount < mNormalFrameCount;
5066 break;
5067 }
5068 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5069 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5070 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005071 }
5072 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005073 audio_format_t fastMixerFormat;
5074 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5075 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5076 } else {
5077 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5078 }
5079 if (mFormat != fastMixerFormat) {
5080 // change our Sink format to accept our intermediate precision
5081 mFormat = fastMixerFormat;
5082 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005083 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005084 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5085 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5086 }
Eric Laurent81784c32012-11-19 14:55:58 -08005087
5088 // create a MonoPipe to connect our submix to FastMixer
5089 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005090
Andy Hung1258c1a2014-05-23 21:22:17 -07005091 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005092 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005093 format.mFormat = fastMixerFormat;
5094 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5095
Eric Laurent81784c32012-11-19 14:55:58 -08005096 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5097 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5098 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5099 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005100 const NBAIO_Format offersFast[1] = {format};
5101 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005102#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005103 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005104#else
5105 (void)
5106#endif
Andy Hung920f6572022-10-06 12:09:49 -07005107 monoPipe->negotiate(offersFast, std::size(offersFast),
5108 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005109 ALOG_ASSERT(index == 0);
5110 monoPipe->setAvgFrames((mScreenState & 1) ?
5111 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5112 mPipeSink = monoPipe;
5113
Eric Laurent81784c32012-11-19 14:55:58 -08005114 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005115 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005116 FastMixerStateQueue *sq = mFastMixer->sq();
5117#ifdef STATE_QUEUE_DUMP
5118 sq->setObserverDump(&mStateQueueObserverDump);
5119 sq->setMutatorDump(&mStateQueueMutatorDump);
5120#endif
5121 FastMixerState *state = sq->begin();
5122 FastTrack *fastTrack = &state->mFastTracks[0];
5123 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5124 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5125 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005126 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5127 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5128 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005129 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005130 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005131 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005132 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005133 fastTrack->mGeneration++;
5134 state->mFastTracksGen++;
5135 state->mTrackMask = 1;
5136 // fast mixer will use the HAL output sink
5137 state->mOutputSink = mOutputSink.get();
5138 state->mOutputSinkGen++;
5139 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005140 // specify sink channel mask when haptic channel mask present as it can not
5141 // be calculated directly from channel count
5142 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005143 ? AUDIO_CHANNEL_NONE
5144 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005145 state->mCommand = FastMixerState::COLD_IDLE;
5146 // already done in constructor initialization list
5147 //mFastMixerFutex = 0;
5148 state->mColdFutexAddr = &mFastMixerFutex;
5149 state->mColdGen++;
5150 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005151 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005152 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005153 sq->end();
5154 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5155
Eric Tan0513b5d2018-09-17 10:32:48 -07005156 NBLog::thread_info_t info;
5157 info.id = mId;
5158 info.type = NBLog::FASTMIXER;
5159 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5160
Eric Laurent81784c32012-11-19 14:55:58 -08005161 // start the fast mixer
5162 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5163 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005164 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005165 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005166
5167#ifdef AUDIO_WATCHDOG
5168 // create and start the watchdog
5169 mAudioWatchdog = new AudioWatchdog();
5170 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5171 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5172 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005173 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005174#endif
Andy Hung8946a282018-04-19 20:04:56 -07005175 } else {
5176#ifdef TEE_SINK
5177 // Only use the MixerThread tee if there is no FastMixer.
5178 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5179 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5180#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005181 }
5182
5183 switch (kUseFastMixer) {
5184 case FastMixer_Never:
5185 case FastMixer_Dynamic:
5186 mNormalSink = mOutputSink;
5187 break;
5188 case FastMixer_Always:
5189 mNormalSink = mPipeSink;
5190 break;
5191 case FastMixer_Static:
5192 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5193 break;
5194 }
5195}
5196
Andy Hung4b17e882023-07-07 13:47:37 -07005197MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005198{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005199 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005200 FastMixerStateQueue *sq = mFastMixer->sq();
5201 FastMixerState *state = sq->begin();
5202 if (state->mCommand == FastMixerState::COLD_IDLE) {
5203 int32_t old = android_atomic_inc(&mFastMixerFutex);
5204 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005205 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005206 }
5207 }
5208 state->mCommand = FastMixerState::EXIT;
5209 sq->end();
5210 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5211 mFastMixer->join();
5212 // Though the fast mixer thread has exited, it's state queue is still valid.
5213 // We'll use that extract the final state which contains one remaining fast track
5214 // corresponding to our sub-mix.
5215 state = sq->begin();
5216 ALOG_ASSERT(state->mTrackMask == 1);
5217 FastTrack *fastTrack = &state->mFastTracks[0];
5218 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5219 delete fastTrack->mBufferProvider;
5220 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005221 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005222#ifdef AUDIO_WATCHDOG
5223 if (mAudioWatchdog != 0) {
5224 mAudioWatchdog->requestExit();
5225 mAudioWatchdog->requestExitAndWait();
5226 mAudioWatchdog.clear();
5227 }
5228#endif
5229 }
Andy Hung7535ed92023-07-17 17:05:00 -07005230 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005231 delete mAudioMixer;
5232}
5233
Andy Hung4b17e882023-07-07 13:47:37 -07005234void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005235 PlaybackThread::onFirstRef();
5236
Andy Hungf8635b62023-08-31 16:13:39 -07005237 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005238 if (mOutput != nullptr && mOutput->stream != nullptr) {
5239 status_t status = mOutput->stream->setLatencyModeCallback(this);
5240 if (status != INVALID_OPERATION) {
5241 updateHalSupportedLatencyModes_l();
5242 }
5243 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5244 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5245 mBluetoothLatencyModesEnabled.store(
5246 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5247 }
5248}
Eric Laurent81784c32012-11-19 14:55:58 -08005249
Andy Hung4b17e882023-07-07 13:47:37 -07005250uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005251{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005252 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005253 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5254 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5255 }
5256 return latency;
5257}
5258
Andy Hung4b17e882023-07-07 13:47:37 -07005259ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005260{
5261 // FIXME we should only do one push per cycle; confirm this is true
5262 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005263 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005264 FastMixerStateQueue *sq = mFastMixer->sq();
5265 FastMixerState *state = sq->begin();
5266 if (state->mCommand != FastMixerState::MIX_WRITE &&
5267 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5268 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005269
5270 // FIXME workaround for first HAL write being CPU bound on some devices
5271 ATRACE_BEGIN("write");
5272 mOutput->write((char *)mSinkBuffer, 0);
5273 ATRACE_END();
5274
Eric Laurent81784c32012-11-19 14:55:58 -08005275 int32_t old = android_atomic_inc(&mFastMixerFutex);
5276 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005277 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005278 }
5279#ifdef AUDIO_WATCHDOG
5280 if (mAudioWatchdog != 0) {
5281 mAudioWatchdog->resume();
5282 }
5283#endif
5284 }
5285 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005286#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005287 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005288 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005289#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005290 sq->end();
5291 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5292 if (kUseFastMixer == FastMixer_Dynamic) {
5293 mNormalSink = mPipeSink;
5294 }
5295 } else {
5296 sq->end(false /*didModify*/);
5297 }
5298 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005300}
5301
Andy Hung4b17e882023-07-07 13:47:37 -07005302void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005303{
5304 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005305 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005306 FastMixerStateQueue *sq = mFastMixer->sq();
5307 FastMixerState *state = sq->begin();
5308 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005309 // Report any frames trapped in the Monopipe
5310 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5311 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5312 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5313 "monoPipeWritten:%lld monoPipeLeft:%lld",
5314 (long long)mFramesWritten, (long long)mSuspendedFrames,
5315 (long long)mPipeSink->framesWritten(), pipeFrames);
5316 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5317
Eric Laurent81784c32012-11-19 14:55:58 -08005318 state->mCommand = FastMixerState::COLD_IDLE;
5319 state->mColdFutexAddr = &mFastMixerFutex;
5320 state->mColdGen++;
5321 mFastMixerFutex = 0;
5322 sq->end();
5323 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5324 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5325 if (kUseFastMixer == FastMixer_Dynamic) {
5326 mNormalSink = mOutputSink;
5327 }
5328#ifdef AUDIO_WATCHDOG
5329 if (mAudioWatchdog != 0) {
5330 mAudioWatchdog->pause();
5331 }
5332#endif
5333 } else {
5334 sq->end(false /*didModify*/);
5335 }
5336 }
5337 PlaybackThread::threadLoop_standby();
5338}
5339
Andy Hung4b17e882023-07-07 13:47:37 -07005340bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341{
5342 return false;
5343}
5344
Andy Hung4b17e882023-07-07 13:47:37 -07005345bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346{
5347 return !mStandby;
5348}
5349
Andy Hung4b17e882023-07-07 13:47:37 -07005350bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005351{
Andy Hungf8635b62023-08-31 16:13:39 -07005352 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005353 return waitingAsyncCallback_l();
5354}
5355
Eric Laurent81784c32012-11-19 14:55:58 -08005356// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005357void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005358{
Andy Hung160664b2023-09-15 18:19:28 -07005359 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5360 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005361 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005363 // discard any pending drain or write ack by incrementing sequence
5364 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5365 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005367 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5368 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005369 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005370 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005371 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005372}
5373
Andy Hung4b17e882023-07-07 13:47:37 -07005374void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005375{
5376 ALOGV("signal playback thread");
5377 broadcast_l();
5378}
5379
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005380void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005381{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005382 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005383 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5384 invalidateTracks((audio_stream_type_t)i);
5385 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005386 if (isHardError) {
5387 mAfThreadCallback->onHardError(allTrackPortIds);
5388 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005389}
5390
Andy Hung4b17e882023-07-07 13:47:37 -07005391void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005392{
Eric Laurent81784c32012-11-19 14:55:58 -08005393 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005394 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005395 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005396 // increase sleep time progressively when application underrun condition clears.
5397 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5398 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5399 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005400 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005401 sleepTimeShift--;
5402 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005403 mSleepTimeUs = 0;
5404 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005405 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005406
Eric Laurent81784c32012-11-19 14:55:58 -08005407}
5408
Andy Hung4b17e882023-07-07 13:47:37 -07005409void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005410{
5411 // If no tracks are ready, sleep once for the duration of an output
5412 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005413 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005414 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005415 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5416 // Using the Monopipe availableToWrite, we estimate the
5417 // sleep time to retry for more data (before we underrun).
5418 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5419 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5420 const size_t pipeFrames = monoPipe->maxFrames();
5421 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5422 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5423 const size_t framesDelay = std::min(
5424 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5425 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5426 pipeFrames, framesLeft, framesDelay);
5427 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5428 } else {
5429 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5430 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5431 mSleepTimeUs = kMinThreadSleepTimeUs;
5432 }
5433 // reduce sleep time in case of consecutive application underruns to avoid
5434 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5435 // duration we would end up writing less data than needed by the audio HAL if
5436 // the condition persists.
5437 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5438 sleepTimeShift++;
5439 }
Eric Laurent81784c32012-11-19 14:55:58 -08005440 }
5441 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005442 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005443 }
5444 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005445 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5446 // before effects processing or output.
5447 if (mMixerBufferValid) {
5448 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005449 if (mType == SPATIALIZER) {
5450 memset(mSinkBuffer, 0, mSinkBufferSize);
5451 }
Andy Hung98ef9782014-03-04 14:46:50 -08005452 } else {
5453 memset(mSinkBuffer, 0, mSinkBufferSize);
5454 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005455 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005456 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5457 "anticipated start");
5458 }
5459 // TODO add standby time extension fct of effect tail
5460}
5461
Andy Hungb17d24b2023-08-29 14:26:09 -07005462// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07005463PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005464 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005465{
Andy Hungc0691382018-09-12 18:01:57 -07005466 // clean up deleted track ids in AudioMixer before allocating new tracks
5467 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5468 // for each trackId, destroy it in the AudioMixer
5469 if (mAudioMixer->exists(trackId)) {
5470 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005471 }
5472 });
Andy Hungc0691382018-09-12 18:01:57 -07005473 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005474
5475 mixer_state mixerStatus = MIXER_IDLE;
5476 // find out which tracks need to be processed
5477 size_t count = mActiveTracks.size();
5478 size_t mixedTracks = 0;
5479 size_t tracksWithEffect = 0;
5480 // counts only _active_ fast tracks
5481 size_t fastTracks = 0;
5482 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5483
5484 float masterVolume = mMasterVolume;
5485 bool masterMute = mMasterMute;
5486
5487 if (masterMute) {
5488 masterVolume = 0;
5489 }
5490 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005491 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005492 if (chain != 0) {
5493 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5494 chain->setVolume_l(&v, &v);
5495 masterVolume = (float)((v + (1 << 23)) >> 24);
5496 chain.clear();
5497 }
5498
5499 // prepare a new state to push
5500 FastMixerStateQueue *sq = NULL;
5501 FastMixerState *state = NULL;
5502 bool didModify = false;
5503 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005504 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005505 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005506 sq = mFastMixer->sq();
5507 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005508 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005509 }
5510
Andy Hung69aed5f2014-02-25 17:24:40 -08005511 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005512 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005513
Andy Hungbd3b2b02018-05-21 10:53:11 -07005514 // DeferredOperations handles statistics after setting mixerStatus.
5515 class DeferredOperations {
5516 public:
Andy Hungea840382020-05-05 21:50:17 -07005517 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5518 : mMixerStatus(mixerStatus)
5519 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005520
5521 // when leaving scope, tally frames properly.
5522 ~DeferredOperations() {
5523 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5524 // because that is when the underrun occurs.
5525 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005526 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005527 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005528 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005529 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005530 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005531 }
5532 }
Andy Hungea840382020-05-05 21:50:17 -07005533 // send the max underrun frames for this mixer period
5534 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005535 }
5536
5537 // tallyUnderrunFrames() is called to update the track counters
5538 // with the number of underrun frames for a particular mixer period.
5539 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005540 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005541 mUnderrunFrames.emplace_back(track, underrunFrames);
5542 }
5543
5544 private:
5545 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005546 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005547 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005548 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005549 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005550
jiabin245cdd92018-12-07 17:55:15 -08005551 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005552 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005553 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005554
5555 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005556 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005557
5558 // process fast tracks
5559 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005560 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5561 "%s(%d): FastTrack(%d) present without FastMixer",
5562 __func__, id(), track->id());
5563
jiabin245cdd92018-12-07 17:55:15 -08005564 if (track->getHapticPlaybackEnabled()) {
5565 noFastHapticTrack = false;
5566 }
Eric Laurent81784c32012-11-19 14:55:58 -08005567
5568 // It's theoretically possible (though unlikely) for a fast track to be created
5569 // and then removed within the same normal mix cycle. This is not a problem, as
5570 // the track never becomes active so it's fast mixer slot is never touched.
5571 // The converse, of removing an (active) track and then creating a new track
5572 // at the identical fast mixer slot within the same normal mix cycle,
5573 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005574 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005575 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005576 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5577 FastTrack *fastTrack = &state->mFastTracks[j];
5578
5579 // Determine whether the track is currently in underrun condition,
5580 // and whether it had a recent underrun.
5581 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5582 FastTrackUnderruns underruns = ftDump->mUnderruns;
5583 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005584 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005585 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005586 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005587 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005588 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005589 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005590 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005591 // don't count underruns that occur while stopping or pausing
5592 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005593 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005594 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5595 recentUnderruns > 0) {
5596 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005597 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005598 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005599 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005600 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005601
5602 // This is similar to the state machine for normal tracks,
5603 // with a few modifications for fast tracks.
5604 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005605 switch (track->state()) {
5606 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005607 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005608 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005609 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005610 }
5611 break;
Andy Hung11e74242023-06-26 19:20:57 -07005612 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005613 // ramp down is not yet implemented
5614 track->setPaused();
5615 break;
Andy Hung11e74242023-06-26 19:20:57 -07005616 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005617 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005618 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005619 break;
Andy Hung11e74242023-06-26 19:20:57 -07005620 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005621 if (recentFull > 0 || recentPartial > 0) {
5622 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005623 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005624 }
5625 if (recentUnderruns == 0) {
5626 // no recent underruns: stay active
5627 break;
5628 }
5629 // there has recently been an underrun of some kind
5630 if (track->sharedBuffer() == 0) {
5631 // were any of the recent underruns "empty" (no frames available)?
5632 if (recentEmpty == 0) {
5633 // no, then ignore the partial underruns as they are allowed indefinitely
5634 break;
5635 }
5636 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005637 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005638 break;
5639 }
5640 // indicate to client process that the track was disabled because of underrun;
5641 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005642 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005643 // remove from active list, but state remains ACTIVE [confusing but true]
5644 isActive = false;
5645 break;
5646 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005647 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005648 case IAfTrackBase::STOPPING_2:
5649 case IAfTrackBase::PAUSED:
5650 case IAfTrackBase::STOPPED:
5651 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005652 // Check for presentation complete if track is inactive
5653 // We have consumed all the buffers of this track.
5654 // This would be incomplete if we auto-paused on underrun
5655 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005656 uint32_t latency = 0;
5657 status_t result = mOutput->stream->getLatency(&latency);
5658 ALOGE_IF(result != OK,
5659 "Error when retrieving output stream latency: %d", result);
5660 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005661 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005662 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5663 // track stays in active list until presentation is complete
5664 break;
5665 }
5666 }
5667 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005668 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005669 }
5670 if (track->isStopped()) {
5671 // Can't reset directly, as fast mixer is still polling this track
5672 // track->reset();
5673 // So instead mark this track as needing to be reset after push with ack
5674 resetMask |= 1 << i;
5675 }
5676 isActive = false;
5677 break;
Andy Hung11e74242023-06-26 19:20:57 -07005678 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005679 default:
Andy Hung11e74242023-06-26 19:20:57 -07005680 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005681 }
5682
5683 if (isActive) {
5684 // was it previously inactive?
5685 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005686 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5687 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005688 fastTrack->mBufferProvider = eabp;
5689 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005690 fastTrack->mChannelMask = track->channelMask();
5691 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005692 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005693 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005694 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005695 fastTrack->mGeneration++;
5696 state->mTrackMask |= 1 << j;
5697 didModify = true;
5698 // no acknowledgement required for newly active tracks
5699 }
Andy Hung11e74242023-06-26 19:20:57 -07005700 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005701 float volume;
5702 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5703 volume = 0.f;
5704 } else {
5705 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5706 }
5707
5708 handleVoipVolume_l(&volume);
5709
Eric Laurent81784c32012-11-19 14:55:58 -08005710 // cache the combined master volume and stream type volume for fast mixer; this
5711 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005712 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005713 proxy->framesReleased()).first;
5714 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005715 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005716 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005717 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5718 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5719
Andy Hung7535ed92023-07-17 17:05:00 -07005720 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005721 /*muteState=*/{masterVolume == 0.f,
5722 mStreamTypes[track->streamType()].volume == 0.f,
5723 mStreamTypes[track->streamType()].mute,
5724 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005725 vlf == 0.f && vrf == 0.f,
5726 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005727
5728 vlf *= volume;
5729 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005730
jiabin76d94692022-12-15 21:51:21 +00005731 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005732 ++fastTracks;
5733 } else {
5734 // was it previously active?
5735 if (state->mTrackMask & (1 << j)) {
5736 fastTrack->mBufferProvider = NULL;
5737 fastTrack->mGeneration++;
5738 state->mTrackMask &= ~(1 << j);
5739 didModify = true;
5740 // If any fast tracks were removed, we must wait for acknowledgement
5741 // because we're about to decrement the last sp<> on those tracks.
5742 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5743 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005744 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5745 // AudioTrack may start (which may not be with a start() but with a write()
5746 // after underrun) and immediately paused or released. In that case the
5747 // FastTrack state hasn't had time to update.
5748 // TODO Remove the ALOGW when this theory is confirmed.
5749 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005750 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005751 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005752 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005753 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005754 }
5755 tracksToRemove->add(track);
5756 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005757 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005758 }
jiabin245cdd92018-12-07 17:55:15 -08005759 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5760 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5761 didModify = true;
5762 }
Eric Laurent81784c32012-11-19 14:55:58 -08005763 continue;
5764 }
5765
5766 { // local variable scope to avoid goto warning
5767
5768 audio_track_cblk_t* cblk = track->cblk();
5769
5770 // The first time a track is added we wait
5771 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005772 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005773
5774 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005775 // use the trackId as the AudioMixer name.
5776 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005777 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005778 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005779 track->channelMask(),
5780 track->format(),
5781 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005782 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005783 ALOGW("%s(): AudioMixer cannot create track(%d)"
5784 " mask %#x, format %#x, sessionId %d",
5785 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005786 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005787 tracksToRemove->add(track);
5788 track->invalidate(); // consider it dead.
5789 continue;
5790 }
5791 }
5792
Eric Laurent81784c32012-11-19 14:55:58 -08005793 // make sure that we have enough frames to mix one full buffer.
5794 // enforce this condition only once to enable draining the buffer in case the client
5795 // app does not call stop() and relies on underrun to stop:
5796 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5797 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005798 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005799 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5800 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005801
5802 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005803 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005804 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5805 // add frames already consumed but not yet released by the resampler
5806 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005807 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005808
Eric Laurent81784c32012-11-19 14:55:58 -08005809 uint32_t minFrames = 1;
5810 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5811 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005812 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005813 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005814
5815 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005816 if (ATRACE_ENABLED()) {
5817 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005818 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005819 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005820 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005821 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005822 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005823 !track->isPaused() && !track->isTerminated())
5824 {
Andy Hungc0691382018-09-12 18:01:57 -07005825 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005826
5827 mixedTracks++;
5828
Andy Hung69aed5f2014-02-25 17:24:40 -08005829 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5830 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005831 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005832 if (track->mainBuffer() != mSinkBuffer &&
5833 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005834 if (mEffectBufferEnabled) {
5835 mEffectBufferValid = true; // Later can set directly.
5836 }
Eric Laurent81784c32012-11-19 14:55:58 -08005837 chain = getEffectChain_l(track->sessionId());
5838 // Delegate volume control to effect in track effect chain if needed
5839 if (chain != 0) {
5840 tracksWithEffect++;
5841 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005842 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005843 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005844 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005845 }
5846 }
5847
5848
5849 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005850 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005851 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005852 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5853 if (track->state() == IAfTrackBase::RESUMING) {
5854 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005855 // If a new track is paused immediately after start, do not ramp on resume.
5856 if (cblk->mServer != 0) {
5857 param = AudioMixer::RAMP_VOLUME;
5858 }
Eric Laurent81784c32012-11-19 14:55:58 -08005859 }
Andy Hungc0691382018-09-12 18:01:57 -07005860 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005861 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005862 // FIXME should not make a decision based on mServer
5863 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005864 // If the track is stopped before the first frame was mixed,
5865 // do not apply ramp
5866 param = AudioMixer::RAMP_VOLUME;
5867 }
5868
5869 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005870 uint32_t vl, vr; // in U8.24 integer format
5871 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005872 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005873 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005874 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005875 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005876 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005877 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005878
Eric Laurenteab90452019-06-24 15:17:46 -07005879 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5880 v = 0;
5881 }
5882
5883 handleVoipVolume_l(&v);
5884
5885 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005886 vl = vr = 0;
5887 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005888 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005889 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005890 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005891 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5892 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005893 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005894 if (vlf > GAIN_FLOAT_UNITY) {
5895 ALOGV("Track left volume out of range: %.3g", vlf);
5896 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005897 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005898 if (vrf > GAIN_FLOAT_UNITY) {
5899 ALOGV("Track right volume out of range: %.3g", vrf);
5900 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005901 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005902
Andy Hung7535ed92023-07-17 17:05:00 -07005903 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005904 /*muteState=*/{masterVolume == 0.f,
5905 mStreamTypes[track->streamType()].volume == 0.f,
5906 mStreamTypes[track->streamType()].mute,
5907 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005908 vlf == 0.f && vrf == 0.f,
5909 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005910
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005911 // now apply the master volume and stream type volume and shaper volume
5912 vlf *= v * vh;
5913 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005914 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005915 // then derive vl and vr as U8.24 versions for the effect chain
5916 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5917 vl = (uint32_t) (scaleto8_24 * vlf);
5918 vr = (uint32_t) (scaleto8_24 * vrf);
5919 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005920 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005921 // send level comes from shared memory and so may be corrupt
5922 if (sendLevel > MAX_GAIN_INT) {
5923 ALOGV("Track send level out of range: %04X", sendLevel);
5924 sendLevel = MAX_GAIN_INT;
5925 }
Andy Hung6be49402014-05-30 10:42:03 -07005926 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5927 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005928 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005929
Jiabin Huang66aa1e32024-05-13 20:33:29 +00005930 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07005931
Eric Laurent81784c32012-11-19 14:55:58 -08005932 // Delegate volume control to effect in track effect chain if needed
5933 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5934 // Do not ramp volume if volume is controlled by effect
5935 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005936 // Update remaining floating point volume levels
5937 vlf = (float)vl / (1 << 24);
5938 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07005939 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005940 } else {
5941 // force no volume ramp when volume controller was just disabled or removed
5942 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07005943 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005944 param = AudioMixer::VOLUME;
5945 }
Andy Hung11e74242023-06-26 19:20:57 -07005946 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005947 }
5948
Eric Laurent81784c32012-11-19 14:55:58 -08005949 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07005950 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005951 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005952
Andy Hungc0691382018-09-12 18:01:57 -07005953 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5954 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5955 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005956 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005957 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005958 AudioMixer::TRACK,
5959 AudioMixer::FORMAT, (void *)track->format());
5960 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005961 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005962 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005963 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005964
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005965 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005966 mAudioMixer->setParameter(
5967 trackId,
5968 AudioMixer::TRACK,
5969 AudioMixer::MIXER_CHANNEL_MASK,
5970 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5971 } else {
5972 mAudioMixer->setParameter(
5973 trackId,
5974 AudioMixer::TRACK,
5975 AudioMixer::MIXER_CHANNEL_MASK,
5976 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5977 }
5978
Glenn Kastene3aa6592012-12-04 12:22:46 -08005979 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005980 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005981 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005982 if (reqSampleRate == 0) {
5983 reqSampleRate = mSampleRate;
5984 } else if (reqSampleRate > maxSampleRate) {
5985 reqSampleRate = maxSampleRate;
5986 }
Eric Laurent81784c32012-11-19 14:55:58 -08005987 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005988 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005989 AudioMixer::RESAMPLE,
5990 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005991 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005992
Andy Hung8edb8dc2015-03-26 19:13:55 -07005993 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005994 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005995 AudioMixer::TIMESTRETCH,
5996 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005997 // cast away constness for this generic API.
5998 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005999
Andy Hung69aed5f2014-02-25 17:24:40 -08006000 /*
6001 * Select the appropriate output buffer for the track.
6002 *
Andy Hung98ef9782014-03-04 14:46:50 -08006003 * Tracks with effects go into their own effects chain buffer
6004 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006005 *
6006 * Other tracks can use mMixerBuffer for higher precision
6007 * channel accumulation. If this buffer is enabled
6008 * (mMixerBufferEnabled true), then selected tracks will accumulate
6009 * into it.
6010 *
6011 */
6012 if (mMixerBufferEnabled
6013 && (track->mainBuffer() == mSinkBuffer
6014 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006015 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006016 mAudioMixer->setParameter(
6017 trackId,
6018 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006019 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006020 mAudioMixer->setParameter(
6021 trackId,
6022 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006023 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006024 } else {
6025 mAudioMixer->setParameter(
6026 trackId,
6027 AudioMixer::TRACK,
6028 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6029 mAudioMixer->setParameter(
6030 trackId,
6031 AudioMixer::TRACK,
6032 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6033 // TODO: override track->mainBuffer()?
6034 mMixerBufferValid = true;
6035 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006036 } else {
6037 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006038 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006039 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006040 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006041 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006042 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006043 AudioMixer::TRACK,
6044 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6045 }
Eric Laurent81784c32012-11-19 14:55:58 -08006046 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006047 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006048 AudioMixer::TRACK,
6049 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006050 mAudioMixer->setParameter(
6051 trackId,
6052 AudioMixer::TRACK,
6053 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006054 mAudioMixer->setParameter(
6055 trackId,
6056 AudioMixer::TRACK,
6057 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung11e74242023-06-26 19:20:57 -07006058 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006059 mAudioMixer->setParameter(
6060 trackId,
6061 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07006062 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006063
6064 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006065 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006066
6067 // If one track is ready, set the mixer ready if:
6068 // - the mixer was not ready during previous round OR
6069 // - no other track is not ready
6070 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6071 mixerStatus != MIXER_TRACKS_ENABLED) {
6072 mixerStatus = MIXER_TRACKS_READY;
6073 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006074
6075 // Enable the next few lines to instrument a test for underrun log handling.
6076 // TODO: Remove when we have a better way of testing the underrun log.
6077#if 0
6078 static int i;
6079 if ((++i & 0xf) == 0) {
6080 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6081 }
6082#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006083 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006084 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006085 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006086 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6087 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006088 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006089 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006090 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006091
Eric Laurent81784c32012-11-19 14:55:58 -08006092 // clear effect chain input buffer if an active track underruns to avoid sending
6093 // previous audio buffer again to effects
6094 chain = getEffectChain_l(track->sessionId());
6095 if (chain != 0) {
6096 chain->clearInputBuffer();
6097 }
6098
Andy Hungc0691382018-09-12 18:01:57 -07006099 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006100 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6101 track->isStopped() || track->isPaused()) {
6102 // We have consumed all the buffers of this track.
6103 // Remove it from the list of active tracks.
6104 // TODO: use actual buffer filling status instead of latency when available from
6105 // audio HAL
6106 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006107 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006108 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6109 if (track->isStopped()) {
6110 track->reset();
6111 }
6112 tracksToRemove->add(track);
6113 }
6114 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006115 // No buffers for this track. Give it a few chances to
6116 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07006117 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006118 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6119 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006120 tracksToRemove->add(track);
6121 // indicate to client process that the track was disabled because of underrun;
6122 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006123 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006124 // If one track is not ready, mark the mixer also not ready if:
6125 // - the mixer was ready during previous round OR
6126 // - no other track is ready
6127 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6128 mixerStatus != MIXER_TRACKS_READY) {
6129 mixerStatus = MIXER_TRACKS_ENABLED;
6130 }
6131 }
Andy Hungc0691382018-09-12 18:01:57 -07006132 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006133 }
6134
6135 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006136
6137 }
6138
jiabin245cdd92018-12-07 17:55:15 -08006139 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6140 // When there is no fast track playing haptic and FastMixer exists,
6141 // enabling the first FastTrack, which provides mixed data from normal
6142 // tracks, to play haptic data.
6143 FastTrack *fastTrack = &state->mFastTracks[0];
6144 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6145 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6146 didModify = true;
6147 }
6148 }
6149
Eric Laurent81784c32012-11-19 14:55:58 -08006150 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006151 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006152 if (didModify) {
6153 state->mFastTracksGen++;
6154 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6155 if (kUseFastMixer == FastMixer_Dynamic &&
6156 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6157 state->mCommand = FastMixerState::COLD_IDLE;
6158 state->mColdFutexAddr = &mFastMixerFutex;
6159 state->mColdGen++;
6160 mFastMixerFutex = 0;
6161 if (kUseFastMixer == FastMixer_Dynamic) {
6162 mNormalSink = mOutputSink;
6163 }
6164 // If we go into cold idle, need to wait for acknowledgement
6165 // so that fast mixer stops doing I/O.
6166 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6167 pauseAudioWatchdog = true;
6168 }
Eric Laurent81784c32012-11-19 14:55:58 -08006169 }
6170 if (sq != NULL) {
6171 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006172 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6173 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6174 // when bringing the output sink into standby.)
6175 //
6176 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6177 //
6178 // This occurs with BT suspend when we idle the FastMixer with
6179 // active tracks, which may be added or removed.
6180 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006181 }
6182#ifdef AUDIO_WATCHDOG
6183 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6184 mAudioWatchdog->pause();
6185 }
6186#endif
6187
6188 // Now perform the deferred reset on fast tracks that have stopped
6189 while (resetMask != 0) {
6190 size_t i = __builtin_ctz(resetMask);
6191 ALOG_ASSERT(i < count);
6192 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006193 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006194 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6195 track->reset();
6196 }
6197
Andy Hung80d03d22018-04-10 10:32:11 -07006198 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6199 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6200 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6201 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6202 // See also the implementation of destroyTrack_l().
6203 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006204 const int trackId = track->id();
6205 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6206 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006207 }
6208 }
6209
Eric Laurent81784c32012-11-19 14:55:58 -08006210 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006211 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006212
Eric Laurentb3f315a2021-07-13 15:09:05 +02006213 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6214 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006215 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006216 }
6217
6218 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006219 // as long as there are effects we should clear the effects buffer, to avoid
6220 // passing a non-clean buffer to the effect chain
6221 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006222 if (mType == SPATIALIZER) {
6223 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6224 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006225 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006226 // sink or mix buffer must be cleared if all tracks are connected to an
6227 // effect chain as in this case the mixer will not write to the sink or mix buffer
6228 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006229 // always clear sink buffer for spatializer output as the output of the spatializer
6230 // effect will be accumulated into it
6231 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6232 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006233 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006234 if (mMixerBufferValid) {
6235 memset(mMixerBuffer, 0, mMixerBufferSize);
6236 // TODO: In testing, mSinkBuffer below need not be cleared because
6237 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6238 // after mixing.
6239 //
6240 // To enforce this guarantee:
6241 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6242 // (mixedTracks == 0 && fastTracks > 0))
6243 // must imply MIXER_TRACKS_READY.
6244 // Later, we may clear buffers regardless, and skip much of this logic.
6245 }
Andy Hung98ef9782014-03-04 14:46:50 -08006246 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006247 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006248 }
6249
6250 // if any fast tracks, then status is ready
6251 mMixerStatusIgnoringFastTracks = mixerStatus;
6252 if (fastTracks > 0) {
6253 mixerStatus = MIXER_TRACKS_READY;
6254 }
6255 return mixerStatus;
6256}
6257
Andy Hungb17d24b2023-08-29 14:26:09 -07006258// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006259uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006260{
6261 uint32_t trackCount = 0;
6262 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006263 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006264 trackCount++;
6265 }
6266 }
6267 return trackCount;
6268}
6269
Andy Hung4b17e882023-07-07 13:47:37 -07006270bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006271{
Brian Lindahl65e90012022-07-27 18:01:07 +02006272 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6273 // could falsely detect that the frame position has stalled due to underrun because we haven't
6274 // given the Audio HAL enough time to update.
6275 const nsecs_t nowNs = systemTime();
6276 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6277 return mLatchedValue;
6278 }
6279 mPreviousNs = nowNs;
6280 mLatchedValue = false;
6281 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006282 uint64_t position = 0;
6283 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006284 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006285 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006286 if (position != mPreviousPosition) {
6287 mPreviousPosition = position;
6288 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006289 }
6290 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006291 return mLatchedValue;
6292}
6293
Andy Hung4b17e882023-07-07 13:47:37 -07006294void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006295{
6296 mLatchedValue = true;
6297 mPreviousPosition = 0;
6298 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006299}
6300
Andy Hungb17d24b2023-08-29 14:26:09 -07006301// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006302bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006303 audio_channel_mask_t channelMask, audio_format_t format,
6304 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006305{
Andy Hung1bc088a2018-02-09 15:57:31 -08006306 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6307 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006308 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006309 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006310 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006311 ALOGW("%s: invalid format: %#x", __func__, format);
6312 return false;
6313 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006314 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006315 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6316 return false;
6317 }
6318 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006319}
6320
Andy Hungb17d24b2023-08-29 14:26:09 -07006321// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006322bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006323 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006324{
Eric Laurent81784c32012-11-19 14:55:58 -08006325 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006326 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006327
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006328 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006329
Eric Laurent10351942014-05-08 18:49:52 -07006330 AudioParameter param = AudioParameter(keyValuePair);
6331 int value;
6332 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6333 reconfig = true;
6334 }
6335 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006336 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006337 status = BAD_VALUE;
6338 } else {
6339 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006340 reconfig = true;
6341 }
Eric Laurent10351942014-05-08 18:49:52 -07006342 }
6343 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006344 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006345 status = BAD_VALUE;
6346 } else {
6347 // no need to save value, since it's constant
6348 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006349 }
Eric Laurent10351942014-05-08 18:49:52 -07006350 }
6351 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6352 // do not accept frame count changes if tracks are open as the track buffer
6353 // size depends on frame count and correct behavior would not be guaranteed
6354 // if frame count is changed after track creation
6355 if (!mTracks.isEmpty()) {
6356 status = INVALID_OPERATION;
6357 } else {
6358 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006359 }
Eric Laurent10351942014-05-08 18:49:52 -07006360 }
6361 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006362 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006363 }
Eric Laurent81784c32012-11-19 14:55:58 -08006364
Eric Laurent10351942014-05-08 18:49:52 -07006365 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006366 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006367 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006368 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6369 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006370 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006371 mThreadMetrics.logEndInterval();
6372 mThreadSnapshot.onEnd();
6373 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006374 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006375 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006376 }
Eric Laurent10351942014-05-08 18:49:52 -07006377 if (status == NO_ERROR && reconfig) {
6378 readOutputParameters_l();
6379 delete mAudioMixer;
6380 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006381 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006382 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006383 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006384 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006385 track->channelMask(),
6386 track->format(),
6387 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006388 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006389 "%s(): AudioMixer cannot create track(%d)"
6390 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006391 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006392 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006393 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006394 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006395 }
Eric Laurent81784c32012-11-19 14:55:58 -08006396 }
6397
Dean Wheatley68918102021-03-19 22:09:19 +11006398 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006399}
6400
6401
Andy Hung4b17e882023-07-07 13:47:37 -07006402void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006403{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006404 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung160664b2023-09-15 18:19:28 -07006405 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006406 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006407 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006408 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6409 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6410 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006411 if (hasFastMixer()) {
6412 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6413
6414 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6415 // while we are dumping it. It may be inconsistent, but it won't mutate!
6416 // This is a large object so we place it on the heap.
6417 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006418 const std::unique_ptr<FastMixerDumpState> copy =
6419 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006420 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006421
6422#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006423 // Similar for state queue
6424 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6425 observerCopy.dump(fd);
6426 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6427 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006428#endif
6429
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006430#ifdef AUDIO_WATCHDOG
6431 if (mAudioWatchdog != 0) {
6432 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6433 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6434 wdCopy.dump(fd);
6435 }
6436#endif
6437
6438 } else {
6439 dprintf(fd, " No FastMixer\n");
6440 }
Eric Laurent90cea102023-05-15 15:08:27 +02006441
6442 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6443 mBluetoothLatencyModesEnabled ? "" : "not ");
6444 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6445 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6446 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006447}
6448
Andy Hung4b17e882023-07-07 13:47:37 -07006449uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006450{
6451 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6452}
6453
Andy Hung4b17e882023-07-07 13:47:37 -07006454uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006455{
6456 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6457}
6458
Andy Hung4b17e882023-07-07 13:47:37 -07006459void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006460{
6461 PlaybackThread::cacheParameters_l();
6462
6463 // FIXME: Relaxed timing because of a certain device that can't meet latency
6464 // Should be reduced to 2x after the vendor fixes the driver issue
6465 // increase threshold again due to low power audio mode. The way this warning
6466 // threshold is calculated and its usefulness should be reconsidered anyway.
6467 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6468}
6469
Andy Hung4b17e882023-07-07 13:47:37 -07006470void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006471 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006472}
6473
Andy Hung4b17e882023-07-07 13:47:37 -07006474void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006475 // Only handle latency mode if:
6476 // - mBluetoothLatencyModesEnabled is true
6477 // - the HAL supports latency modes
6478 // - the selected device is Bluetooth LE or A2DP
6479 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6480 return;
6481 }
6482 if (mOutDeviceTypeAddrs.size() != 1
6483 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6484 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6485 return;
6486 }
6487
6488 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6489 if (mSupportedLatencyModes.size() == 1) {
6490 // If the HAL only support one latency mode currently, confirm the choice
6491 latencyMode = mSupportedLatencyModes[0];
6492 } else if (mSupportedLatencyModes.size() > 1) {
6493 // Request low latency if:
6494 // - At least one active track is either:
6495 // - a fast track with gaming usage or
6496 // - a track with acessibility usage
6497 for (const auto& track : mActiveTracks) {
6498 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6499 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6500 latencyMode = AUDIO_LATENCY_MODE_LOW;
6501 break;
6502 }
6503 }
6504 }
6505
6506 if (latencyMode != mSetLatencyMode) {
6507 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6508 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6509 __func__, mId, toString(latencyMode).c_str(), status);
6510 if (status == NO_ERROR) {
6511 mSetLatencyMode = latencyMode;
6512 }
6513 }
6514}
6515
Andy Hung4b17e882023-07-07 13:47:37 -07006516void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006517
6518 if (mOutput == nullptr || mOutput->stream == nullptr) {
6519 return;
6520 }
6521 std::vector<audio_latency_mode_t> latencyModes;
6522 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6523 if (status != NO_ERROR) {
6524 latencyModes.clear();
6525 }
6526 if (latencyModes != mSupportedLatencyModes) {
6527 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6528 __func__, mId, status, toString(latencyModes).c_str());
6529 mSupportedLatencyModes.swap(latencyModes);
6530 sendHalLatencyModesChangedEvent_l();
6531 }
6532}
6533
Andy Hung4b17e882023-07-07 13:47:37 -07006534status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006535 std::vector<audio_latency_mode_t>* modes) {
6536 if (modes == nullptr) {
6537 return BAD_VALUE;
6538 }
Andy Hungf8635b62023-08-31 16:13:39 -07006539 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006540 *modes = mSupportedLatencyModes;
6541 return NO_ERROR;
6542}
6543
Andy Hung4b17e882023-07-07 13:47:37 -07006544void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006545 std::vector<audio_latency_mode_t> modes) {
Andy Hungf8635b62023-08-31 16:13:39 -07006546 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006547 if (modes != mSupportedLatencyModes) {
6548 ALOGD("%s: thread(%d) supported latency modes: %s",
6549 __func__, mId, toString(modes).c_str());
6550 mSupportedLatencyModes.swap(modes);
6551 sendHalLatencyModesChangedEvent_l();
6552 }
6553}
6554
Andy Hung4b17e882023-07-07 13:47:37 -07006555status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006556 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6557 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6558 return INVALID_OPERATION;
6559 }
6560 mBluetoothLatencyModesEnabled.store(enabled);
6561 return NO_ERROR;
6562}
6563
Eric Laurent81784c32012-11-19 14:55:58 -08006564// ----------------------------------------------------------------------------
6565
Andy Hung4b17e882023-07-07 13:47:37 -07006566/* static */
6567sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006568 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006569 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6570 const audio_offload_info_t& offloadInfo) {
6571 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006572 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006573}
6574
Andy Hung7535ed92023-07-17 17:05:00 -07006575DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006576 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6577 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006578 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006579 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006580{
Andy Hung7535ed92023-07-17 17:05:00 -07006581 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006582}
6583
Andy Hung4b17e882023-07-07 13:47:37 -07006584DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006585{
6586}
6587
Andy Hung4b17e882023-07-07 13:47:37 -07006588void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006589{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006590 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006591 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6592 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6593}
6594
Andy Hung4b17e882023-07-07 13:47:37 -07006595void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006596{
Andy Hungf8635b62023-08-31 16:13:39 -07006597 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006598 if (mMasterBalance != balance) {
6599 mMasterBalance.store(balance);
6600 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6601 broadcast_l();
6602 }
6603}
6604
Andy Hung4b17e882023-07-07 13:47:37 -07006605void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006606{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006607 float left, right;
6608
Andy Hung333ab962019-05-28 20:23:35 -07006609 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006610 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006611
Andy Hung398ffa22022-12-13 19:19:53 -08006612 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6613 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6614
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006615 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6616 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006617
6618 const int64_t volumeShaperFrames =
6619 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6620 const auto [shaperVolume, shaperActive] =
6621 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006622 mVolumeShaperActive = shaperActive;
6623
Vlad Popae2f5aef2022-07-25 16:00:20 +02006624 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6625 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6626 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6627
6628 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6629
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006630 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006631 left = right = 0;
6632 } else {
6633 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006634 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006635
Glenn Kastenc56f3422014-03-21 17:53:17 -07006636 if (left > GAIN_FLOAT_UNITY) {
6637 left = GAIN_FLOAT_UNITY;
6638 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006639 if (right > GAIN_FLOAT_UNITY) {
6640 right = GAIN_FLOAT_UNITY;
6641 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006642 left *= v;
6643 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006644 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006645 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6646 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6647 right *= mMasterBalanceRight;
6648 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006649 }
6650
Andy Hung7535ed92023-07-17 17:05:00 -07006651 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006652 /*muteState=*/{mMasterMute,
6653 mStreamTypes[track->streamType()].volume == 0.f,
6654 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006655 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006656 clientVolumeMute,
6657 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006658
Eric Laurentbfb1b832013-01-07 09:53:42 -08006659 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006660 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006661 if (left != mLeftVolFloat || right != mRightVolFloat) {
6662 mLeftVolFloat = left;
6663 mRightVolFloat = right;
6664
Eric Laurentbfb1b832013-01-07 09:53:42 -08006665 // Delegate volume control to effect in track effect chain if needed
6666 // only one effect chain can be present on DirectOutputThread, so if
6667 // there is one, the track is connected to it
6668 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006669 // if effect chain exists, volume is handled by it.
6670 // Convert volumes from float to 8.24
6671 uint32_t vl = (uint32_t)(left * (1 << 24));
6672 uint32_t vr = (uint32_t)(right * (1 << 24));
6673 // Direct/Offload effect chains set output volume in setVolume_l().
6674 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6675 } else {
6676 // otherwise we directly set the volume.
6677 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006678 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006679 }
6680 }
6681}
6682
Andy Hung4b17e882023-07-07 13:47:37 -07006683void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006684{
Andy Hung11e74242023-06-26 19:20:57 -07006685 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6686 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006687
Eric Laurent0f0631e2015-07-06 18:01:25 -07006688 if (previousTrack != 0 && latestTrack != 0) {
6689 if (mType == DIRECT) {
6690 if (previousTrack.get() != latestTrack.get()) {
6691 mFlushPending = true;
6692 }
6693 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006694 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6695 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006696 mFlushPending = true;
6697 }
6698 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006699 } else if (previousTrack == 0) {
6700 // there could be an old track added back during track transition for direct
6701 // output, so always issues flush to flush data of the previous track if it
6702 // was already destroyed with HAL paused, then flush can resume the playback
6703 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006704 }
6705 PlaybackThread::onAddNewTrack_l();
6706}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006707
Andy Hung4b17e882023-07-07 13:47:37 -07006708PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006709 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006710)
6711{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006712 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006713 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006714 bool doHwPause = false;
6715 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006716
6717 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006718 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006719 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006720 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006721 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006722 continue;
6723 }
6724
Andy Hung11e74242023-06-26 19:20:57 -07006725 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006726#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006727 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006728#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006729 // Only consider last track started for volume and mixer state control.
6730 // In theory an older track could underrun and restart after the new one starts
6731 // but as we only care about the transition phase between two tracks on a
6732 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006733 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006734 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006735
Kuowei Li23666472021-01-20 10:23:25 +08006736 if (track->isPausePending()) {
6737 track->pauseAck();
6738 // It is possible a track might have been flushed or stopped.
6739 // Other operations such as flush pending might occur on the next prepare.
6740 if (track->isPausing()) {
6741 track->setPaused();
6742 }
6743 // Always perform pause, as an immediate flush will change
6744 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006745 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006746 doHwPause = true;
6747 mHwPaused = true;
6748 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006749 } else if (track->isFlushPending()) {
6750 track->flushAck();
6751 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006752 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006753 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006754 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006755 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006756 if (last) {
6757 mLeftVolFloat = mRightVolFloat = -1.0;
6758 if (mHwPaused) {
6759 doHwResume = true;
6760 mHwPaused = false;
6761 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006762 }
6763 }
6764
Eric Laurent81784c32012-11-19 14:55:58 -08006765 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006766 // for all its buffers to be filled before processing it.
6767 // Allow draining the buffer in case the client
6768 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006769 // hence the test on (track->retryCount() > 1).
6770 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006771 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6772 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006773 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006774
6775 // target retry count that we will use is based on the time we wait for retries.
6776 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6777 // the retry threshold is when we accept any size for PCM data. This is slightly
6778 // smaller than the retry count so we can push small bits of data without a glitch.
6779 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006780 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006781 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006782 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006783 minFrames = mNormalFrameCount;
6784 } else {
6785 minFrames = 1;
6786 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006787
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006788 const size_t framesReady = track->framesReady();
6789 const int trackId = track->id();
6790 if (ATRACE_ENABLED()) {
6791 std::string traceName("nRdy");
6792 traceName += std::to_string(trackId);
6793 ATRACE_INT(traceName.c_str(), framesReady);
6794 }
6795 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006796 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006797 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006798 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006799
Andy Hung11e74242023-06-26 19:20:57 -07006800 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6801 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006802 if (last) {
6803 // make sure processVolume_l() will apply new volume even if 0
6804 mLeftVolFloat = mRightVolFloat = -1.0;
6805 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006806 if (!mHwSupportsPause) {
6807 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006808 }
6809 }
6810
6811 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006812 processVolume_l(track, last);
6813 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006814 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006815 if (previousTrack != 0) {
6816 if (track != previousTrack.get()) {
6817 // Flush any data still being written from last track
6818 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006819 // Invalidate previous track to force a seek when resuming.
6820 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006821 }
6822 }
6823 mPreviousTrack = track;
6824
Eric Laurentd595b7c2013-04-03 17:27:56 -07006825 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006826 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006827 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006828 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006829 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006830 doHwResume = true;
6831 mHwPaused = false;
6832 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006833 }
Eric Laurent81784c32012-11-19 14:55:58 -08006834 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006835 // clear effect chain input buffer if the last active track started underruns
6836 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006837 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006838 mEffectChains[0]->clearInputBuffer();
6839 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006840 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006841 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006842 if (last && mHwPaused) {
6843 doHwResume = true;
6844 mHwPaused = false;
6845 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006846 }
6847 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6848 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006849 // We have consumed all the buffers of this track.
6850 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006851 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006852 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006853 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006854 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006855 if (presComplete) {
6856 mOutput->presentationComplete();
6857 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006858 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006859 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006860 }
Eric Laurent81784c32012-11-19 14:55:58 -08006861 if (track->isStopped()) {
6862 track->reset();
6863 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006864 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006865 }
6866 } else {
6867 // No buffers for this track. Give it a few chances to
6868 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006869 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006870 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006871 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006872 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006873 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006874 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006875 } else {
6876 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6877 tracksToRemove->add(track);
6878 // indicate to client process that the track was disabled because of
6879 // underrun; it will then automatically call start() when data is available
6880 track->disable();
6881 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6882 // unlike mixerthread, HAL can be paused for direct output
6883 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6884 "minFrames = %u, mFormat = %#x",
6885 framesReady, minFrames, mFormat);
6886 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6887 doHwPause = true;
6888 mHwPaused = true;
6889 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006890 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006891 } else if (last) {
6892 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006893 }
6894 }
6895 }
6896 }
6897
Eric Laurentd1f69b02014-12-15 14:33:13 -08006898 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006899 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006900 for (size_t i = 0; i < mTracks.size(); i++) {
6901 if (mTracks[i]->isFlushPending()) {
6902 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006903 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006904 }
6905 }
6906 }
6907
6908 // make sure the pause/flush/resume sequence is executed in the right order.
6909 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6910 // before flush and then resume HW. This can happen in case of pause/flush/resume
6911 // if resume is received before pause is executed.
6912 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006913 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006914 status_t result = mOutput->stream->pause();
6915 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006916 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006917 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006918 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006919 flushHw_l();
6920 }
6921 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006922 status_t result = mOutput->stream->resume();
6923 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006924 }
Eric Laurent81784c32012-11-19 14:55:58 -08006925 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006926 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006927
6928 return mixerStatus;
6929}
6930
Andy Hung4b17e882023-07-07 13:47:37 -07006931void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006932{
Eric Laurent81784c32012-11-19 14:55:58 -08006933 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006934 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006935 // output audio to hardware
6936 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006937 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006938 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006939 status_t status = mActiveTrack->getNextBuffer(&buffer);
6940 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006941 // no need to pad with 0 for compressed audio
6942 if (audio_has_proportional_frames(mFormat)) {
6943 memset(curBuf, 0, frameCount * mFrameSize);
6944 }
Eric Laurent81784c32012-11-19 14:55:58 -08006945 break;
6946 }
6947 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6948 frameCount -= buffer.frameCount;
6949 curBuf += buffer.frameCount * mFrameSize;
6950 mActiveTrack->releaseBuffer(&buffer);
6951 }
Andy Hung2098f272014-02-27 14:00:06 -08006952 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006953 mSleepTimeUs = 0;
6954 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006955 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006956}
6957
Andy Hung4b17e882023-07-07 13:47:37 -07006958void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006959{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006960 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006961 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006962 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006963 return;
6964 }
Andy Hung85ba3332021-04-27 17:40:26 -07006965 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6966 mSleepTimeUs = mActiveSleepTimeUs;
6967 } else {
6968 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006969 }
Andy Hung85ba3332021-04-27 17:40:26 -07006970 // Note: In S or later, we do not write zeroes for
6971 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006972}
6973
Andy Hung4b17e882023-07-07 13:47:37 -07006974void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006975{
6976 {
Andy Hungf8635b62023-08-31 16:13:39 -07006977 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006978 for (size_t i = 0; i < mTracks.size(); i++) {
6979 if (mTracks[i]->isFlushPending()) {
6980 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006981 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006982 }
6983 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006984 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006985 flushHw_l();
6986 }
6987 }
6988 PlaybackThread::threadLoop_exit();
6989}
6990
6991// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07006992bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006993{
6994 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006995 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006996
6997 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6998 // after a timeout and we will enter standby then.
6999 if (mTracks.size() > 0) {
7000 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07007001 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07007002 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007003 }
7004
Eric Laurent5cff4032015-05-26 13:49:58 -07007005 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08007006}
7007
Andy Hungb17d24b2023-08-29 14:26:09 -07007008// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07007009bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007010 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007011{
7012 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007013 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007014
Eric Laurent10351942014-05-08 18:49:52 -07007015 AudioParameter param = AudioParameter(keyValuePair);
7016 int value;
7017 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007018 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007019 }
Eric Laurent10351942014-05-08 18:49:52 -07007020 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7021 // do not accept frame count changes if tracks are open as the track buffer
7022 // size depends on frame count and correct behavior would not be garantied
7023 // if frame count is changed after track creation
7024 if (!mTracks.isEmpty()) {
7025 status = INVALID_OPERATION;
7026 } else {
7027 reconfig = true;
7028 }
7029 }
7030 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007031 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007032 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007033 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007034 if (!mStandby) {
7035 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007036 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007037 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007038 }
Eric Laurent10351942014-05-08 18:49:52 -07007039 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007040 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007041 }
7042 if (status == NO_ERROR && reconfig) {
7043 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007044 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007045 }
7046 }
7047
Dean Wheatley68918102021-03-19 22:09:19 +11007048 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007049}
7050
Andy Hung4b17e882023-07-07 13:47:37 -07007051uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007052{
7053 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007054 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007055 time = PlaybackThread::activeSleepTimeUs();
7056 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007057 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007058 }
7059 return time;
7060}
7061
Andy Hung4b17e882023-07-07 13:47:37 -07007062uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007063{
7064 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007065 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007066 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7067 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007068 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007069 }
7070 return time;
7071}
7072
Andy Hung4b17e882023-07-07 13:47:37 -07007073uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007074{
7075 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007076 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007077 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7078 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007079 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007080 }
7081 return time;
7082}
7083
Andy Hung4b17e882023-07-07 13:47:37 -07007084void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007085{
7086 PlaybackThread::cacheParameters_l();
7087
7088 // use shorter standby delay as on normal output to release
7089 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007090 // no delay on outputs with HW A/V sync
7091 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007092 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007093 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007094 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007095 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007096 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007097 }
Eric Laurent81784c32012-11-19 14:55:58 -08007098}
7099
Andy Hung4b17e882023-07-07 13:47:37 -07007100void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007101{
ziyangch8f194f12021-12-01 13:48:04 -08007102 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007103 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007104 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007105 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007106 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007107 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007108 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007109}
7110
Andy Hung4b17e882023-07-07 13:47:37 -07007111int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007112 // If a VolumeShaper is active, we must wake up periodically to update volume.
7113 const int64_t NS_PER_MS = 1000000;
7114 return mVolumeShaperActive ?
7115 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7116}
7117
Eric Laurent81784c32012-11-19 14:55:58 -08007118// ----------------------------------------------------------------------------
7119
Andy Hung4b17e882023-07-07 13:47:37 -07007120AsyncCallbackThread::AsyncCallbackThread(
7121 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007122 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007123 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007124 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007125 mDrainSequence(0),
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007126 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007127{
7128}
7129
Andy Hung4b17e882023-07-07 13:47:37 -07007130void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007131{
7132 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7133}
7134
Andy Hung4b17e882023-07-07 13:47:37 -07007135bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007136{
7137 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007138 uint32_t writeAckSequence;
7139 uint32_t drainSequence;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007140 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007141
7142 {
Andy Hungb17d24b2023-08-29 14:26:09 -07007143 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007144 while (!((mWriteAckSequence & 1) ||
7145 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007146 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007147 exitPending())) {
Andy Hungb17d24b2023-08-29 14:26:09 -07007148 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007149 }
7150
Eric Laurentbfb1b832013-01-07 09:53:42 -08007151 if (exitPending()) {
7152 break;
7153 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007154 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7155 mWriteAckSequence, mDrainSequence);
7156 writeAckSequence = mWriteAckSequence;
7157 mWriteAckSequence &= ~1;
7158 drainSequence = mDrainSequence;
7159 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007160 asyncError = mAsyncError;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007161 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007162 }
7163 {
Andy Hung4b17e882023-07-07 13:47:37 -07007164 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007165 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007166 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007167 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007168 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007169 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007170 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007171 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007172 if (asyncError != ASYNC_ERROR_NONE) {
7173 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007174 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007175 }
7176 }
7177 }
7178 return false;
7179}
7180
Andy Hung4b17e882023-07-07 13:47:37 -07007181void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007182{
7183 ALOGV("AsyncCallbackThread::exit");
Andy Hungf8635b62023-08-31 16:13:39 -07007184 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007185 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -07007186 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007187}
7188
Andy Hung4b17e882023-07-07 13:47:37 -07007189void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007190{
Andy Hungf8635b62023-08-31 16:13:39 -07007191 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007192 // bit 0 is cleared
7193 mWriteAckSequence = sequence << 1;
7194}
7195
Andy Hung4b17e882023-07-07 13:47:37 -07007196void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007197{
Andy Hungf8635b62023-08-31 16:13:39 -07007198 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007199 // ignore unexpected callbacks
7200 if (mWriteAckSequence & 2) {
7201 mWriteAckSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007202 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007203 }
7204}
7205
Andy Hung4b17e882023-07-07 13:47:37 -07007206void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007207{
Andy Hungf8635b62023-08-31 16:13:39 -07007208 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007209 // bit 0 is cleared
7210 mDrainSequence = sequence << 1;
7211}
7212
Andy Hung4b17e882023-07-07 13:47:37 -07007213void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007214{
Andy Hungf8635b62023-08-31 16:13:39 -07007215 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007216 // ignore unexpected callbacks
7217 if (mDrainSequence & 2) {
7218 mDrainSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007219 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007220 }
7221}
7222
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007223void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007224{
Andy Hungf8635b62023-08-31 16:13:39 -07007225 audio_utils::lock_guard _l(mutex());
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007226 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungb17d24b2023-08-29 14:26:09 -07007227 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007228}
7229
Eric Laurentbfb1b832013-01-07 09:53:42 -08007230
7231// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007232
7233/* static */
7234sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007235 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007236 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7237 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007238 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007239}
7240
Andy Hung7535ed92023-07-17 17:05:00 -07007241OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007242 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7243 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007244 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007245 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007246{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007247 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007248 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007249 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007250}
7251
Andy Hung4b17e882023-07-07 13:47:37 -07007252void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007253{
7254 if (mFlushPending || mHwPaused) {
7255 // If a flush is pending or track was paused, just discard buffered data
Andy Hung94dfbb42023-09-06 19:41:47 -07007256 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007257 flushHw_l();
7258 } else {
7259 mMixerStatus = MIXER_DRAIN_ALL;
7260 threadLoop_drain();
7261 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007262 if (mUseAsyncWrite) {
7263 ALOG_ASSERT(mCallbackThread != 0);
7264 mCallbackThread->exit();
7265 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007266 PlaybackThread::threadLoop_exit();
7267}
7268
Andy Hung4b17e882023-07-07 13:47:37 -07007269PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007270 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007271)
7272{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007273 size_t count = mActiveTracks.size();
7274
7275 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007276 bool doHwPause = false;
7277 bool doHwResume = false;
7278
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007279 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007280
Eric Laurentbfb1b832013-01-07 09:53:42 -08007281 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007282 for (const sp<IAfTrack>& t : mActiveTracks) {
7283 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007284#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007285 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007286#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007287 // Only consider last track started for volume and mixer state control.
7288 // In theory an older track could underrun and restart after the new one starts
7289 // but as we only care about the transition phase between two tracks on a
7290 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007291 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007292 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007293
Haynes Mathew George7844f672014-01-15 12:32:55 -08007294 if (track->isInvalid()) {
7295 ALOGW("An invalidated track shouldn't be in active list");
7296 tracksToRemove->add(track);
7297 continue;
7298 }
7299
Andy Hung11e74242023-06-26 19:20:57 -07007300 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007301 ALOGW("An idle track shouldn't be in active list");
7302 continue;
7303 }
7304
Kuowei Li23666472021-01-20 10:23:25 +08007305 if (track->isPausePending()) {
7306 track->pauseAck();
7307 // It is possible a track might have been flushed or stopped.
7308 // Other operations such as flush pending might occur on the next prepare.
7309 if (track->isPausing()) {
7310 track->setPaused();
7311 }
7312 // Always perform pause if last, as an immediate flush will change
7313 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007314 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007315 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007316 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007317 mHwPaused = true;
7318 }
7319 // If we were part way through writing the mixbuffer to
7320 // the HAL we must save this until we resume
7321 // BUG - this will be wrong if a different track is made active,
7322 // in that case we want to discard the pending data in the
7323 // mixbuffer and tell the client to present it again when the
7324 // track is resumed
7325 mPausedWriteLength = mCurrentWriteLength;
7326 mPausedBytesRemaining = mBytesRemaining;
7327 mBytesRemaining = 0; // stop writing
7328 }
7329 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007330 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007331 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007332 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007333 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007334 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007335 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007336 track->flushAck();
7337 if (last) {
7338 mFlushPending = true;
7339 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007340 } else if (track->isResumePending()){
7341 track->resumeAck();
7342 if (last) {
7343 if (mPausedBytesRemaining) {
7344 // Need to continue write that was interrupted
7345 mCurrentWriteLength = mPausedWriteLength;
7346 mBytesRemaining = mPausedBytesRemaining;
7347 mPausedBytesRemaining = 0;
7348 }
7349 if (mHwPaused) {
7350 doHwResume = true;
7351 mHwPaused = false;
7352 // threadLoop_mix() will handle the case that we need to
7353 // resume an interrupted write
7354 }
7355 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007356 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007357
Eric Laurent3df841a2016-07-15 15:15:40 -07007358 mLeftVolFloat = mRightVolFloat = -1.0;
7359
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007360 // Do not handle new data in this iteration even if track->framesReady()
7361 mixerStatus = MIXER_TRACKS_ENABLED;
7362 }
7363 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007364 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007365 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007366 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7367 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007368 if (last) {
7369 // make sure processVolume_l() will apply new volume even if 0
7370 mLeftVolFloat = mRightVolFloat = -1.0;
7371 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007372 }
7373
7374 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007375 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007376 if (previousTrack != 0) {
7377 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007378 // Flush any data still being written from last track
7379 mBytesRemaining = 0;
7380 if (mPausedBytesRemaining) {
7381 // Last track was paused so we also need to flush saved
7382 // mixbuffer state and invalidate track so that it will
7383 // re-submit that unwritten data when it is next resumed
7384 mPausedBytesRemaining = 0;
7385 // Invalidate is a bit drastic - would be more efficient
7386 // to have a flag to tell client that some of the
7387 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007388 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007389 }
7390 // flush data already sent to the DSP if changing audio session as audio
7391 // comes from a different source. Also invalidate previous track to force a
7392 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007393 if (previousTrack->sessionId() != track->sessionId()) {
7394 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007395 }
7396 }
7397 }
7398 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007399 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007400 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007401 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007402 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007403 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007404 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007405 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007406 mixerStatus = MIXER_TRACKS_READY;
7407 }
7408 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007409 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007410 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007411 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007412 // Hardware buffer can hold a large amount of audio so we must
7413 // wait for all current track's data to drain before we say
7414 // that the track is stopped.
7415 if (mBytesRemaining == 0) {
7416 // Only start draining when all data in mixbuffer
7417 // has been written
7418 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007419 track->setState(IAfTrackBase::STOPPING_2);
7420 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007421 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7422 if (last && !mStandby) {
7423 // do not modify drain sequence if we are already draining. This happens
7424 // when resuming from pause after drain.
7425 if ((mDrainSequence & 1) == 0) {
7426 mSleepTimeUs = 0;
7427 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7428 mixerStatus = MIXER_DRAIN_TRACK;
7429 mDrainSequence += 2;
7430 }
7431 if (mHwPaused) {
7432 // It is possible to move from PAUSED to STOPPING_1 without
7433 // a resume so we must ensure hardware is running
7434 doHwResume = true;
7435 mHwPaused = false;
7436 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007437 }
7438 }
Eric Laurente93cc032016-05-05 10:15:10 -07007439 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007440 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007441 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007442 }
7443 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007444 // Drain has completed or we are in standby, signal presentation complete
7445 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007446 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007447 mOutput->presentationComplete();
7448 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007449 track->reset();
7450 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007451 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007452 if (!mUseAsyncWrite) {
7453 // If we don't get explicit drain notification we must
7454 // register discontinuity regardless of whether this is
7455 // the previous (!last) or the upcoming (last) track
7456 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007457 mTimestampVerifier.discontinuity(
7458 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007459 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007460 }
7461 } else {
7462 // No buffers for this track. Give it a few chances to
7463 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007464 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007465 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007466 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007467 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007468 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007469 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007470 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7471 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007472 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007473 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007474 // it will then automatically call start() when data is available
7475 track->disable();
7476 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007477 } else if (last){
7478 mixerStatus = MIXER_TRACKS_ENABLED;
7479 }
7480 }
7481 }
7482 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007483 if (track->isReady()) { // check ready to prevent premature start.
7484 processVolume_l(track, last);
7485 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007486 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007487
Eric Laurentea0fade2013-10-04 16:23:48 -07007488 // make sure the pause/flush/resume sequence is executed in the right order.
7489 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7490 // before flush and then resume HW. This can happen in case of pause/flush/resume
7491 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007492 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007493 status_t result = mOutput->stream->pause();
7494 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007495 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007496 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007497 if (mFlushPending) {
7498 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007499 }
Eric Laurentfd477972013-10-25 18:10:40 -07007500 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007501 status_t result = mOutput->stream->resume();
7502 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007503 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007504
Eric Laurentbfb1b832013-01-07 09:53:42 -08007505 // remove all the tracks that need to be...
7506 removeTracks_l(*tracksToRemove);
7507
7508 return mixerStatus;
7509}
7510
Eric Laurentbfb1b832013-01-07 09:53:42 -08007511// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007512bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007513{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007514 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7515 mWriteAckSequence, mDrainSequence);
7516 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007517 return true;
7518 }
7519 return false;
7520}
7521
Andy Hung4b17e882023-07-07 13:47:37 -07007522bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007523{
Andy Hungf8635b62023-08-31 16:13:39 -07007524 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007525 return waitingAsyncCallback_l();
7526}
7527
Andy Hung4b17e882023-07-07 13:47:37 -07007528void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007529{
Eric Laurente659ef42014-09-29 13:06:46 -07007530 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007531 // Flush anything still waiting in the mixbuffer
7532 mCurrentWriteLength = 0;
7533 mBytesRemaining = 0;
7534 mPausedWriteLength = 0;
7535 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007536 // reset bytes written count to reflect that DSP buffers are empty after flush.
7537 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007538
Eric Laurentbfb1b832013-01-07 09:53:42 -08007539 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007540 // discard any pending drain or write ack by incrementing sequence
7541 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7542 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007543 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007544 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7545 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007546 }
7547}
7548
Andy Hung4b17e882023-07-07 13:47:37 -07007549void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007550{
Andy Hungf8635b62023-08-31 16:13:39 -07007551 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007552 if (PlaybackThread::invalidateTracks_l(streamType)) {
7553 mFlushPending = true;
7554 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007555}
7556
Andy Hung4b17e882023-07-07 13:47:37 -07007557void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07007558 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007559 if (PlaybackThread::invalidateTracks_l(portIds)) {
7560 mFlushPending = true;
7561 }
7562}
7563
Eric Laurentbfb1b832013-01-07 09:53:42 -08007564// ----------------------------------------------------------------------------
7565
Andy Hung4b17e882023-07-07 13:47:37 -07007566/* static */
7567sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007568 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007569 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007570 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007571}
7572
Andy Hung7535ed92023-07-17 17:05:00 -07007573DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007574 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007575 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007576 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007577 mWaitTimeMs(UINT_MAX)
7578{
7579 addOutputTrack(mainThread);
7580}
7581
Andy Hung4b17e882023-07-07 13:47:37 -07007582DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007583{
7584 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7585 mOutputTracks[i]->destroy();
7586 }
7587}
7588
Andy Hung4b17e882023-07-07 13:47:37 -07007589void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007590{
7591 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007592 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007593 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007594 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007595 if (mMixerBufferValid) {
7596 memset(mMixerBuffer, 0, mMixerBufferSize);
7597 } else {
7598 memset(mSinkBuffer, 0, mSinkBufferSize);
7599 }
Eric Laurent81784c32012-11-19 14:55:58 -08007600 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007601 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007602 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007603 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007604 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007605}
7606
Andy Hung4b17e882023-07-07 13:47:37 -07007607void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007608{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007609 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007610 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007611 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007612 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007613 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007614 }
7615 } else if (mBytesWritten != 0) {
7616 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7617 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007618 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007619 } else {
7620 // flush remaining overflow buffers in output tracks
7621 writeFrames = 0;
7622 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007623 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007624 }
7625}
7626
Andy Hung4b17e882023-07-07 13:47:37 -07007627ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007628{
7629 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007630 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7631
7632 // Consider the first OutputTrack for timestamp and frame counting.
7633
7634 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7635 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7636 // we always claim success.
7637 if (i == 0) {
7638 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7639 ALOGD_IF(correction != 0 && writeFrames != 0,
7640 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7641 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7642 mFramesWritten -= correction;
7643 }
7644
7645 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007646 }
Andy Hungcf10d742020-04-28 15:38:24 -07007647 if (mStandby) {
7648 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007649 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007650 mStandby = false;
7651 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007652 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007653}
7654
Andy Hung4b17e882023-07-07 13:47:37 -07007655void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007656{
7657 // DuplicatingThread implements standby by stopping all tracks
7658 for (size_t i = 0; i < outputTracks.size(); i++) {
7659 outputTracks[i]->stop();
7660 }
7661}
7662
Andy Hung8a5abfd2023-12-07 19:35:12 -08007663void DuplicatingThread::threadLoop_exit()
7664{
7665 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7666 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7667 // Do so here in the threadLoop_exit().
7668
7669 SortedVector <sp<IAfOutputTrack>> localTracks;
7670 {
7671 audio_utils::lock_guard l(mutex());
7672 localTracks = std::move(mOutputTracks);
7673 mOutputTracks.clear();
7674 }
7675 localTracks.clear();
7676 outputTracks.clear();
7677 PlaybackThread::threadLoop_exit();
7678}
7679
Andy Hung4b17e882023-07-07 13:47:37 -07007680void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007681{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007682 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007683
7684 std::stringstream ss;
7685 const size_t numTracks = mOutputTracks.size();
7686 ss << " " << numTracks << " OutputTracks";
7687 if (numTracks > 0) {
7688 ss << ":";
7689 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007690 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007691 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007692 if (thread.get() != nullptr) {
7693 ss << thread.get() << ", " << thread->id();
7694 } else {
7695 ss << "null";
7696 }
7697 ss << ")";
7698 }
7699 }
7700 ss << "\n";
7701 std::string result = ss.str();
7702 write(fd, result.c_str(), result.size());
7703}
7704
Andy Hung4b17e882023-07-07 13:47:37 -07007705void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007706{
7707 outputTracks = mOutputTracks;
7708}
7709
Andy Hung4b17e882023-07-07 13:47:37 -07007710void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007711{
7712 outputTracks.clear();
7713}
7714
Andy Hung4b17e882023-07-07 13:47:37 -07007715void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007716{
Andy Hungf8635b62023-08-31 16:13:39 -07007717 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007718 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7719 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7720 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7721 const size_t frameCount =
7722 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7723 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7724 // from different OutputTracks and their associated MixerThreads (e.g. one may
7725 // nearly empty and the other may be dropping data).
7726
Svet Ganov33761132021-05-13 22:51:08 +00007727 // TODO b/182392769: use attribution source util, move to server edge
7728 AttributionSourceState attributionSource = AttributionSourceState();
7729 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007730 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007731 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007732 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007733 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007734 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007735 this,
7736 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007737 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007738 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007739 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007740 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007741 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7742 if (status != NO_ERROR) {
7743 ALOGE("addOutputTrack() initCheck failed %d", status);
7744 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007745 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007746 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7747 mOutputTracks.add(outputTrack);
7748 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7749 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007750}
7751
Andy Hung4b17e882023-07-07 13:47:37 -07007752void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007753{
Andy Hungf8635b62023-08-31 16:13:39 -07007754 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007755 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7756 if (mOutputTracks[i]->thread() == thread) {
7757 mOutputTracks[i]->destroy();
7758 mOutputTracks.removeAt(i);
7759 updateWaitTime_l();
Andy Hung160664b2023-09-15 18:19:28 -07007760 // NO_THREAD_SAFETY_ANALYSIS
7761 // Lambda workaround: as thread != this
7762 // we can safely call the remote thread getOutput.
7763 const bool equalOutput =
7764 [&](){ return thread->getOutput() == mOutput; }();
7765 if (equalOutput) {
7766 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007767 }
Eric Laurent81784c32012-11-19 14:55:58 -08007768 return;
7769 }
7770 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007771 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007772}
7773
Andy Hungb17d24b2023-08-29 14:26:09 -07007774// caller must hold mutex()
Andy Hung4b17e882023-07-07 13:47:37 -07007775void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007776{
7777 mWaitTimeMs = UINT_MAX;
7778 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007779 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007780 if (strong != 0) {
7781 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7782 if (waitTimeMs < mWaitTimeMs) {
7783 mWaitTimeMs = waitTimeMs;
7784 }
7785 }
7786 }
7787}
7788
Andy Hung4b17e882023-07-07 13:47:37 -07007789bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007790{
7791 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007792 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007793 if (thread == 0) {
7794 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7795 outputTracks[i].get());
7796 return false;
7797 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007798 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007799 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007800 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007801 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7802 thread.get());
7803 return false;
7804 }
7805 }
7806 return true;
7807}
7808
Andy Hung4b17e882023-07-07 13:47:37 -07007809void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007810 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007811{
Kevin Rocard12381092018-04-11 09:19:59 -07007812 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7813 outputTrack->setMetadatas(metadata.tracks);
7814 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007815}
7816
Andy Hung4b17e882023-07-07 13:47:37 -07007817uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007818{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007819 // return half the wait time in microseconds.
7820 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007821}
7822
Andy Hung4b17e882023-07-07 13:47:37 -07007823void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007824{
7825 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7826 updateWaitTime_l();
7827
7828 MixerThread::cacheParameters_l();
7829}
7830
Eric Laurentb3f315a2021-07-13 15:09:05 +02007831// ----------------------------------------------------------------------------
7832
Andy Hung4b17e882023-07-07 13:47:37 -07007833/* static */
7834sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007835 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007836 AudioStreamOut* output,
7837 audio_io_handle_t id,
7838 bool systemReady,
7839 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007840 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007841}
7842
Andy Hung7535ed92023-07-17 17:05:00 -07007843SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007844 AudioStreamOut* output,
7845 audio_io_handle_t id,
7846 bool systemReady,
7847 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007848 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007849{
7850}
7851
Andy Hung4b17e882023-07-07 13:47:37 -07007852void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007853 // if mSupportedLatencyModes is empty, the HAL stream does not support
7854 // latency mode control and we can exit.
7855 if (mSupportedLatencyModes.empty()) {
7856 return;
7857 }
7858 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7859 if (mSupportedLatencyModes.size() == 1) {
7860 // If the HAL only support one latency mode currently, confirm the choice
7861 latencyMode = mSupportedLatencyModes[0];
7862 } else if (mSupportedLatencyModes.size() > 1) {
7863 // Request low latency if:
7864 // - The low latency mode is requested by the spatializer controller
7865 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7866 // AND
7867 // - At least one active track is spatialized
7868 bool hasSpatializedActiveTrack = false;
7869 for (const auto& track : mActiveTracks) {
7870 if (track->isSpatialized()) {
7871 hasSpatializedActiveTrack = true;
7872 break;
7873 }
7874 }
7875 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7876 latencyMode = AUDIO_LATENCY_MODE_LOW;
7877 }
7878 }
7879
7880 if (latencyMode != mSetLatencyMode) {
7881 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007882 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7883 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007884 if (status == NO_ERROR) {
7885 mSetLatencyMode = latencyMode;
7886 }
7887 }
7888}
7889
Andy Hung4b17e882023-07-07 13:47:37 -07007890status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007891 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7892 return BAD_VALUE;
7893 }
Andy Hungf8635b62023-08-31 16:13:39 -07007894 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007895 mRequestedLatencyMode = mode;
7896 return NO_ERROR;
7897}
7898
Andy Hung4b17e882023-07-07 13:47:37 -07007899void SpatializerThread::checkOutputStageEffects()
Andy Hungf8635b62023-08-31 16:13:39 -07007900NO_THREAD_SAFETY_ANALYSIS
7901// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007902{
7903 bool hasVirtualizer = false;
7904 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007905 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007906 {
Andy Hungf8635b62023-08-31 16:13:39 -07007907 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007908 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007909 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007910 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007911 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7912 }
7913
7914 finalDownMixer = mFinalDownMixer;
7915 mFinalDownMixer.clear();
7916 }
7917
7918 if (hasVirtualizer) {
7919 if (finalDownMixer != nullptr) {
7920 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007921 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007922 }
7923 finalDownMixer.clear();
7924 } else if (!hasDownMixer) {
7925 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07007926 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007927 EFFECT_UIID_DOWNMIX, &descriptors);
7928 if (status != NO_ERROR) {
7929 return;
7930 }
7931 ALOG_ASSERT(!descriptors.empty(),
7932 "%s getDescriptors() returned no error but empty list", __func__);
7933
7934 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7935 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007936 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007937
7938 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7939 ALOGW("%s error creating downmixer %d", __func__, status);
7940 finalDownMixer.clear();
7941 } else {
7942 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007943 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007944 }
7945 }
7946
7947 {
Andy Hungf8635b62023-08-31 16:13:39 -07007948 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007949 mFinalDownMixer = finalDownMixer;
7950 }
7951}
7952
Andy Hunge2514462023-12-06 14:59:24 -08007953void SpatializerThread::threadLoop_exit()
7954{
7955 // The Spatializer EffectHandle must be released on the PlaybackThread
7956 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
7957 mFinalDownMixer.clear();
7958
7959 PlaybackThread::threadLoop_exit();
7960}
7961
Eric Laurent81784c32012-11-19 14:55:58 -08007962// ----------------------------------------------------------------------------
7963// Record
7964// ----------------------------------------------------------------------------
7965
Andy Hung7535ed92023-07-17 17:05:00 -07007966sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007967 AudioStreamIn* input,
7968 audio_io_handle_t id,
7969 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007970 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07007971}
7972
Andy Hung7535ed92023-07-17 17:05:00 -07007973RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007974 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007975 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007976 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007977 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07007978 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007979 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007980 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007981 mActiveTracks(&this->mLocalLog),
7982 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007983 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007984 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007985 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7986 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007987 // mFastCapture below
7988 , mFastCaptureFutex(0)
7989 // mInputSource
7990 // mPipeSink
7991 // mPipeSource
7992 , mPipeFramesP2(0)
7993 // mPipeMemory
7994 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007995 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007996 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007997{
Glenn Kastend7dca052015-03-05 16:05:54 -08007998 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07007999 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008000
George Burgess IVa8f90c12020-05-14 11:27:19 -07008001 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008002 mIsMsdDevice = strcmp(
8003 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8004 }
8005
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008006 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008007
Andy Hungc8fddf32018-08-08 18:32:37 -07008008 // TODO: We may also match on address as well as device type for
8009 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008010 // TODO: This property should be ensure that only contains one single device type.
8011 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8012 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008013 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8014 : AUDIO_DEVICE_NONE));
8015
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008016 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008017 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008018 size_t numCounterOffers = 0;
8019 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008020#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008021 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008022#else
8023 (void)
8024#endif
8025 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008026 ALOG_ASSERT(index == 0);
8027
8028 // initialize fast capture depending on configuration
8029 bool initFastCapture;
8030 switch (kUseFastCapture) {
8031 case FastCapture_Never:
8032 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008033 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008034 break;
8035 case FastCapture_Always:
8036 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008037 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008038 break;
8039 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008040 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008041 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008042 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008043 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8044 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8045 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008046 break;
8047 // case FastCapture_Dynamic:
8048 }
8049
8050 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008051 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008052 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008053 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8054 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008055 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008056 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008057 const sp<MemoryDealer> roHeap(readOnlyHeap());
8058 sp<IMemory> pipeMemory;
8059 if ((roHeap == 0) ||
8060 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008061 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008062 ALOGE("not enough memory for pipe buffer size=%zu; "
8063 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8064 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8065 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008066 goto failed;
8067 }
8068 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8069 memset(pipeBuffer, 0, pipeSize);
8070 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008071 const NBAIO_Format offersFast[1] = {format};
8072 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008073 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008074 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008075 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008076 mPipeSink = pipe;
8077 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008078 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008079 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008080 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008081 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008082 mPipeSource = pipeReader;
8083 mPipeFramesP2 = pipeFramesP2;
8084 mPipeMemory = pipeMemory;
8085
8086 // create fast capture
8087 mFastCapture = new FastCapture();
8088 FastCaptureStateQueue *sq = mFastCapture->sq();
8089#ifdef STATE_QUEUE_DUMP
8090 // FIXME
8091#endif
8092 FastCaptureState *state = sq->begin();
8093 state->mCblk = NULL;
8094 state->mInputSource = mInputSource.get();
8095 state->mInputSourceGen++;
8096 state->mPipeSink = pipe;
8097 state->mPipeSinkGen++;
8098 state->mFrameCount = mFrameCount;
8099 state->mCommand = FastCaptureState::COLD_IDLE;
8100 // already done in constructor initialization list
8101 //mFastCaptureFutex = 0;
8102 state->mColdFutexAddr = &mFastCaptureFutex;
8103 state->mColdGen++;
8104 state->mDumpState = &mFastCaptureDumpState;
8105#ifdef TEE_SINK
8106 // FIXME
8107#endif
Andy Hung7535ed92023-07-17 17:05:00 -07008108 mFastCaptureNBLogWriter =
8109 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008110 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8111 sq->end();
8112 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8113
8114 // start the fast capture
8115 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8116 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008117 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008118 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008119#ifdef AUDIO_WATCHDOG
8120 // FIXME
8121#endif
8122
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008123 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008124 }
Andy Hung8946a282018-04-19 20:04:56 -07008125#ifdef TEE_SINK
8126 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8127 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8128#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008129failed: ;
8130
8131 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008132}
8133
Andy Hung4b17e882023-07-07 13:47:37 -07008134RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008135{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008136 if (mFastCapture != 0) {
8137 FastCaptureStateQueue *sq = mFastCapture->sq();
8138 FastCaptureState *state = sq->begin();
8139 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8140 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8141 if (old == -1) {
8142 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8143 }
8144 }
8145 state->mCommand = FastCaptureState::EXIT;
8146 sq->end();
8147 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8148 mFastCapture->join();
8149 mFastCapture.clear();
8150 }
Andy Hung7535ed92023-07-17 17:05:00 -07008151 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8152 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008153 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008154}
8155
Andy Hung4b17e882023-07-07 13:47:37 -07008156void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008157{
Glenn Kastend7dca052015-03-05 16:05:54 -08008158 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008159}
8160
Andy Hung4b17e882023-07-07 13:47:37 -07008161void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008162{
8163 ALOGV(" preExit()");
Andy Hungf8635b62023-08-31 16:13:39 -07008164 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008165 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008166 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008167 track->invalidate();
8168 }
8169 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008170 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008171}
8172
Andy Hung4b17e882023-07-07 13:47:37 -07008173bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008174{
Eric Laurent81784c32012-11-19 14:55:58 -08008175 nsecs_t lastWarning = 0;
8176
8177 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008178
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008179reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008180 {
Andy Hungf8635b62023-08-31 16:13:39 -07008181 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008182 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008183 }
8184
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008185 // used to request a deferred sleep, to be executed later while mutex is unlocked
8186 uint32_t sleepUs = 0;
8187
Andy Hung1381a072023-10-20 16:41:18 -07008188 // timestamp correction enable is determined under lock, used in processing step.
8189 bool timestampCorrectionEnabled = false;
8190
Andy Hung446f4df2019-02-21 12:26:41 -08008191 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8192
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008193 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008194 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungfdb84b92024-03-15 10:15:10 -07008195 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8196 sp<IAfRecordTrack> activeTrack;
Andy Hungb2b01c62024-04-23 13:56:19 -07008197 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008198 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008199
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008200 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008201 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008202
Glenn Kasten735f45f2014-08-18 15:51:59 -07008203 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008204 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008205
Glenn Kasten735f45f2014-08-18 15:51:59 -07008206 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008207 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008208
Eric Laurent33403f02020-05-29 18:35:06 -07008209 bool silenceFastCapture = false;
8210
Andy Hungb17d24b2023-08-29 14:26:09 -07008211 { // scope for mutex()
8212 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008213
Eric Laurent021cf962014-05-13 10:18:14 -07008214 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008215
Eric Laurent000a4192014-01-29 15:17:32 -08008216 // check exitPending here because checkForNewParameters_l() and
Andy Hungb17d24b2023-08-29 14:26:09 -07008217 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008218 if (exitPending()) {
8219 break;
8220 }
8221
Eric Laurent5c25d562016-07-13 17:17:45 -07008222 // sleep with mutex unlocked
8223 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008224 ATRACE_BEGIN("sleepC");
Andy Hungb17d24b2023-08-29 14:26:09 -07008225 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008226 ATRACE_END();
8227 sleepUs = 0;
8228 continue;
8229 }
8230
Glenn Kasten2b806402013-11-20 16:37:38 -08008231 // if no active track(s), then standby and release wakelock
8232 size_t size = mActiveTracks.size();
8233 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008234 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008235 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008236 releaseWakeLock_l();
8237 ALOGV("RecordThread: loop stopping");
8238 // go to sleep
Andy Hungb17d24b2023-08-29 14:26:09 -07008239 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008240 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008241 goto reacquire_wakelock;
8242 }
8243
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008244 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008245 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008246 for (size_t i = 0; i < size; ) {
Andy Hungb2b01c62024-04-23 13:56:19 -07008247 if (activeTrack) { // ensure track release is outside lock.
8248 oldActiveTracks.emplace_back(std::move(activeTrack));
8249 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008250 activeTrack = mActiveTracks[i];
8251 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008252 if (activeTrack->isFastTrack()) {
8253 ALOG_ASSERT(fastTrackToRemove == 0);
8254 fastTrackToRemove = activeTrack;
8255 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008256 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008257 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008258 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008259 continue;
8260 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008261
Andy Hung11e74242023-06-26 19:20:57 -07008262 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008263 switch (activeTrackState) {
8264
Andy Hung11e74242023-06-26 19:20:57 -07008265 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008266 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008267 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008268 if (activeTrack->isFastTrack()) {
8269 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8270 // Keep a ref on fast track to wait for FastCapture thread to get updated
8271 // state before potential track removal
8272 fastTrackToRemove = activeTrack;
8273 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008274 doBroadcast = true;
8275 size--;
8276 continue;
8277
Andy Hung11e74242023-06-26 19:20:57 -07008278 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008279 sleepUs = 10000;
8280 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008281 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008282 continue;
8283
Andy Hung11e74242023-06-26 19:20:57 -07008284 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008285 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008286 if (mStandby) {
8287 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008288 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008289 mStandby = false;
8290 }
Andy Hung11e74242023-06-26 19:20:57 -07008291 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008292 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008293 break;
8294
Andy Hung11e74242023-06-26 19:20:57 -07008295 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008296 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008297 break;
8298
Andy Hung11e74242023-06-26 19:20:57 -07008299 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8300 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8301 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008302 default:
Andy Hungce685402018-10-05 17:23:27 -07008303 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8304 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008305 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008306
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008307 if (activeTrack->isFastTrack()) {
8308 ALOG_ASSERT(!mFastTrackAvail);
8309 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008310 // if the active fast track is silenced either:
8311 // 1) silence the whole capture from fast capture buffer if this is
8312 // the only active track
8313 // 2) invalidate this track: this will cause the client to reconnect and possibly
8314 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008315 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008316 if (activeTrack->isSilenced()) {
8317 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008318 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008319 } else {
8320 silenceFastCapture = true;
8321 }
8322 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008323 // Invalidate fast tracks if access to audio history is required as this is not
8324 // possible with fast tracks. Once the fast track has been invalidated, no new
8325 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8326 if (mMaxSharedAudioHistoryMs != 0) {
8327 invalidate = true;
8328 }
8329 if (invalidate) {
8330 activeTrack->invalidate();
8331 ALOG_ASSERT(fastTrackToRemove == 0);
8332 fastTrackToRemove = activeTrack;
8333 removeTrack_l(activeTrack);
8334 mActiveTracks.remove(activeTrack);
8335 size--;
8336 continue;
8337 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008338 fastTrack = activeTrack;
8339 }
Eric Laurent33403f02020-05-29 18:35:06 -07008340
8341 activeTracks.add(activeTrack);
8342 i++;
8343
Glenn Kasten9e982352013-08-14 14:39:50 -07008344 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008345
Andy Hung94dfbb42023-09-06 19:41:47 -07008346 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008347
Kevin Rocard069c2712018-03-29 19:09:14 -07008348 updateMetadata_l();
8349
Eric Laurent5c25d562016-07-13 17:17:45 -07008350 if (allStopped) {
8351 standbyIfNotAlreadyInStandby();
8352 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008353 if (doBroadcast) {
Andy Hungb17d24b2023-08-29 14:26:09 -07008354 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008355 }
8356
8357 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008358 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008359 if (sleepUs == 0) {
8360 sleepUs = kRecordThreadSleepUs;
8361 }
8362 continue;
8363 }
8364 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008365
Andy Hung1381a072023-10-20 16:41:18 -07008366 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008367 lockEffectChains_l(effectChains);
8368 }
8369
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008370 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008371
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008372 size_t size = effectChains.size();
8373 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008374 // thread mutex is not locked, but effect chain is locked
8375 effectChains[i]->process_l();
8376 }
8377
Glenn Kasten735f45f2014-08-18 15:51:59 -07008378 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008379 if (mFastCapture != 0) {
8380 FastCaptureStateQueue *sq = mFastCapture->sq();
8381 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008382 bool didModify = false;
8383 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008384 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8385 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8386 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8387 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8388 if (old == -1) {
8389 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8390 }
8391 }
8392 state->mCommand = FastCaptureState::READ_WRITE;
8393#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008394 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008395 FastThreadDumpState::kSamplingNforLowRamDevice :
8396 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008397#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008398 didModify = true;
8399 }
8400 audio_track_cblk_t *cblkOld = state->mCblk;
8401 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8402 if (cblkNew != cblkOld) {
8403 state->mCblk = cblkNew;
8404 // block until acked if removing a fast track
8405 if (cblkOld != NULL) {
8406 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8407 }
8408 didModify = true;
8409 }
jiabin01c8f562018-07-19 17:47:28 -07008410 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8411 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8412 if (state->mFastPatchRecordBufferProvider != abp) {
8413 state->mFastPatchRecordBufferProvider = abp;
8414 state->mFastPatchRecordFormat = fastTrack == 0 ?
8415 AUDIO_FORMAT_INVALID : fastTrack->format();
8416 didModify = true;
8417 }
Eric Laurent33403f02020-05-29 18:35:06 -07008418 if (state->mSilenceCapture != silenceFastCapture) {
8419 state->mSilenceCapture = silenceFastCapture;
8420 didModify = true;
8421 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008422 sq->end(didModify);
8423 if (didModify) {
8424 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008425#if 0
8426 if (kUseFastCapture == FastCapture_Dynamic) {
8427 mNormalSource = mPipeSource;
8428 }
8429#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008430 }
8431 }
8432
Glenn Kasten735f45f2014-08-18 15:51:59 -07008433 // now run the fast track destructor with thread mutex unlocked
8434 fastTrackToRemove.clear();
8435
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008436 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8437 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8438 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8439 // If destination is non-contiguous, first read past the nominal end of buffer, then
8440 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008441
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008442 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008443 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008444 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008445
8446 // If an NBAIO source is present, use it to read the normal capture's data
8447 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008448 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008449
8450 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8451 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8452 // we immediately retry the read() to get data and prevent another overflow.
8453 for (int retries = 0; retries <= 2; ++retries) {
8454 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8455 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8456 framesToRead);
8457 if (framesRead != OVERRUN) break;
8458 }
8459
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008460 const ssize_t availableToRead = mPipeSource->availableToRead();
8461 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008462 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008463 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008464 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8465 "more frames to read than fifo size, %zd > %zu",
8466 availableToRead, mPipeFramesP2);
8467 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8468 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8469 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8470 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008471 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8472 }
8473 if (framesRead < 0) {
8474 status_t status = (status_t) framesRead;
8475 switch (status) {
8476 case OVERRUN:
8477 ALOGW("overrun on read from pipe");
8478 framesRead = 0;
8479 break;
8480 case NEGOTIATE:
8481 ALOGE("re-negotiation is needed");
8482 framesRead = -1; // Will cause an attempt to recover.
8483 break;
8484 default:
8485 ALOGE("unknown error %d on read from pipe", status);
8486 break;
8487 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008488 }
8489 // otherwise use the HAL / AudioStreamIn directly
8490 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008491 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008492 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008493 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008494 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008495 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008496 if (result < 0) {
8497 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008498 } else {
8499 framesRead = bytesRead / mFrameSize;
8500 }
8501 }
8502
Andy Hung446f4df2019-02-21 12:26:41 -08008503 const int64_t lastIoEndNs = systemTime(); // end IO timing
8504
Andy Hung3f0c9022016-01-15 17:49:46 -08008505 // Update server timestamp with server stats
8506 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008507 if (framesRead >= 0) {
8508 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8509 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8510 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008511
8512 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008513 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008514 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008515 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008516 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8517 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8518 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008519 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008520 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8521
8522 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hung94dfbb42023-09-06 19:41:47 -07008523 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008524 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008525 id(), (long long)time, (long long)position);
8526 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8527 position = correctedTimestamp.mFrames;
8528 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008529 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008530 id(), (long long)time, (long long)position);
8531 }
8532
Andy Hung3f0c9022016-01-15 17:49:46 -08008533 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8534 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8535 // Note: In general record buffers should tend to be empty in
8536 // a properly running pipeline.
8537 //
8538 // Also, it is not advantageous to call get_presentation_position during the read
8539 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008540 } else {
8541 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008542 }
8543 }
Andy Hunge6c37112019-02-26 17:38:10 -08008544
8545 // From the timestamp, input read latency is negative output write latency.
8546 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008547 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008548 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8549 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8550 mLatencyMs.add(latencyMs);
8551 }
8552
Andy Hung3f0c9022016-01-15 17:49:46 -08008553 // Use this to track timestamp information
8554 // ALOGD("%s", mTimestamp.toString().c_str());
8555
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008556 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008557 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008558 // Force input into standby so that it tries to recover at next read attempt
8559 inputStandBy();
8560 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008561 }
8562 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008563 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008564 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008565 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008566 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008567
Andy Hung8946a282018-04-19 20:04:56 -07008568#ifdef TEE_SINK
8569 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8570#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008571 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008572 {
8573 size_t part1 = mRsmpInFramesP2 - rear;
8574 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008575 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008576 (framesRead - part1) * mFrameSize);
8577 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008578 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008579 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008580
8581 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008582
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008583 // loop over each active track
8584 for (size_t i = 0; i < size; i++) {
8585 activeTrack = activeTracks[i];
8586
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008587 // skip fast tracks, as those are handled directly by FastCapture
8588 if (activeTrack->isFastTrack()) {
8589 continue;
8590 }
8591
Andy Hung73c02e42015-03-29 01:13:58 -07008592 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008593 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8594
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008595 enum {
8596 OVERRUN_UNKNOWN,
8597 OVERRUN_TRUE,
8598 OVERRUN_FALSE
8599 } overrun = OVERRUN_UNKNOWN;
8600
8601 // loop over getNextBuffer to handle circular sink
8602 for (;;) {
8603
Andy Hung11e74242023-06-26 19:20:57 -07008604 activeTrack->sinkBuffer().frameCount = ~0;
8605 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8606 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008607 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8608
Andy Hung73c02e42015-03-29 01:13:58 -07008609 // check available frames and handle overrun conditions
8610 // if the record track isn't draining fast enough.
8611 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008612 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008613 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008614 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008615 overrun = OVERRUN_TRUE;
8616 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008617 if (framesOut == 0 || framesIn == 0) {
8618 break;
8619 }
8620
Andy Hung6770c6f2015-04-07 13:43:36 -07008621 // Don't allow framesOut to be larger than what is possible with resampling
8622 // from framesIn.
8623 // This isn't strictly necessary but helps limit buffer resizing in
8624 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008625 if (audio_is_linear_pcm(activeTrack->format())) {
8626 framesOut = min(framesOut,
8627 destinationFramesPossible(
8628 framesIn, mSampleRate, activeTrack->sampleRate()));
8629 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008630
8631 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008632 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008633 // straight from RecordThread buffer to RecordTrack buffer.
8634 AudioBufferProvider::Buffer buffer;
8635 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008636 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008637 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008638 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008639 ALOGV_IF(buffer.frameCount != framesOut,
8640 "%s() read less than expected (%zu vs %zu)",
8641 __func__, buffer.frameCount, framesOut);
8642 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008643 memcpy(activeTrack->sinkBuffer().raw,
8644 buffer.raw, buffer.frameCount * mFrameSize);
8645 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008646 } else {
8647 framesOut = 0;
8648 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008649 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008650 }
8651 } else {
8652 // process frames from the RecordThread buffer provider to the RecordTrack
8653 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008654 framesOut = activeTrack->recordBufferConverter()->convert(
8655 activeTrack->sinkBuffer().raw,
8656 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008657 framesOut);
8658 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008659
8660 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8661 overrun = OVERRUN_FALSE;
8662 }
8663
Andy Hung93bb5732023-05-04 21:16:34 -07008664 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8665 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008666 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008667 if (framesToDrop == 0) {
8668 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008669 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008670 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008671 // Sanitize before releasing if the track has no access to the source data
8672 // An idle UID receives silence from non virtual devices until active
8673 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008674 memset(activeTrack->sinkBuffer().raw,
8675 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008676 }
Andy Hung11e74242023-06-26 19:20:57 -07008677 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008678 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008679 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008680 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008681 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008682 }
8683 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008684
8685 switch (overrun) {
8686 case OVERRUN_TRUE:
8687 // client isn't retrieving buffers fast enough
8688 if (!activeTrack->setOverflow()) {
8689 nsecs_t now = systemTime();
8690 // FIXME should lastWarning per track?
8691 if ((now - lastWarning) > kWarningThrottleNs) {
8692 ALOGW("RecordThread: buffer overflow");
8693 lastWarning = now;
8694 }
8695 }
8696 break;
8697 case OVERRUN_FALSE:
8698 activeTrack->clearOverflow();
8699 break;
8700 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008701 break;
8702 }
8703
Andy Hung3f0c9022016-01-15 17:49:46 -08008704 // update frame information and push timestamp out
8705 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008706 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008707 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8708 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008709 }
8710
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008711unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008712 // enable changes in effect chain
8713 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008714 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008715 if (audio_has_proportional_frames(mFormat)
8716 && loopCount == lastLoopCountRead + 1) {
8717 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8718 const double jitterMs =
8719 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8720 {framesRead, readPeriodNs},
8721 {0, 0} /* lastTimestamp */, mSampleRate);
8722 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8723
Andy Hungf8635b62023-08-31 16:13:39 -07008724 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008725 mIoJitterMs.add(jitterMs);
8726 mProcessTimeMs.add(processMs);
8727 }
8728 // update timing info.
8729 mLastIoBeginNs = lastIoBeginNs;
8730 mLastIoEndNs = lastIoEndNs;
8731 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008732 }
8733
Glenn Kasten93e471f2013-08-19 08:40:07 -07008734 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008735
8736 {
Andy Hungf8635b62023-08-31 16:13:39 -07008737 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008738 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008739 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008740 track->invalidate();
8741 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008742 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008743 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008744 }
8745
8746 releaseWakeLock();
8747
8748 ALOGV("RecordThread %p exiting", this);
8749 return false;
8750}
8751
Andy Hung4b17e882023-07-07 13:47:37 -07008752void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008753{
8754 if (!mStandby) {
8755 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008756 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008757 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008758 mStandby = true;
8759 }
8760}
8761
Andy Hung4b17e882023-07-07 13:47:37 -07008762void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008763{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008764 // Idle the fast capture if it's currently running
8765 if (mFastCapture != 0) {
8766 FastCaptureStateQueue *sq = mFastCapture->sq();
8767 FastCaptureState *state = sq->begin();
8768 if (!(state->mCommand & FastCaptureState::IDLE)) {
8769 state->mCommand = FastCaptureState::COLD_IDLE;
8770 state->mColdFutexAddr = &mFastCaptureFutex;
8771 state->mColdGen++;
8772 mFastCaptureFutex = 0;
8773 sq->end();
8774 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8775 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8776#if 0
8777 if (kUseFastCapture == FastCapture_Dynamic) {
8778 // FIXME
8779 }
8780#endif
8781#ifdef AUDIO_WATCHDOG
8782 // FIXME
8783#endif
8784 } else {
8785 sq->end(false /*didModify*/);
8786 }
8787 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008788 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008789 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008790
8791 // If going into standby, flush the pipe source.
8792 if (mPipeSource.get() != nullptr) {
8793 const ssize_t flushed = mPipeSource->flush();
8794 if (flushed > 0) {
8795 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8796 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8797 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8798 }
8799 }
Eric Laurent81784c32012-11-19 14:55:58 -08008800}
8801
Andy Hungb17d24b2023-08-29 14:26:09 -07008802// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07008803sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008804 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008805 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008806 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008807 audio_format_t format,
8808 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008809 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008810 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008811 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008812 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008813 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008814 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008815 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008816 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008817 audio_port_handle_t portId,
8818 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008819{
Glenn Kasten74935e42013-12-19 08:56:45 -08008820 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008821 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008822 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008823 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008824 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008825 audio_input_flags_t requestedFlags = *flags;
8826 uint32_t sampleRate;
8827
8828 lStatus = initCheck();
8829 if (lStatus != NO_ERROR) {
8830 ALOGE("createRecordTrack_l() audio driver not initialized");
8831 goto Exit;
8832 }
8833
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008834 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8835 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8836 lStatus = BAD_VALUE;
8837 goto Exit;
8838 }
8839
Eric Laurentec376dc2021-04-08 20:41:22 +02008840 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008841 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008842 lStatus = PERMISSION_DENIED;
8843 goto Exit;
8844 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008845 if (maxSharedAudioHistoryMs < 0
Andy Hung409572b2023-07-19 12:47:35 -07008846 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008847 lStatus = BAD_VALUE;
8848 goto Exit;
8849 }
8850 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008851 if (*pSampleRate == 0) {
8852 *pSampleRate = mSampleRate;
8853 }
8854 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008855
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008856 // special case for FAST flag considered OK if fast capture is present and access to
8857 // audio history is not required
8858 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008859 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8860 }
8861
Eric Laurentf14db3c2017-12-08 14:20:36 -08008862 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008863 if ((*flags & inputFlags) != *flags) {
8864 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8865 " input flags (%08x)",
8866 *flags, inputFlags);
8867 *flags = (audio_input_flags_t)(*flags & inputFlags);
8868 }
Eric Laurent81784c32012-11-19 14:55:58 -08008869
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008870 // client expresses a preference for FAST and no access to audio history,
8871 // but we get the final say
8872 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008873 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008874 // we formerly checked for a callback handler (non-0 tid),
8875 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008876 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008877 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008878 // Frame count is not specified (0), or is less than or equal the pipe depth.
8879 // It is OK to provide a higher capacity than requested.
8880 // We will force it to mPipeFramesP2 below.
8881 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008882 // PCM data
8883 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008884 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008885 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008886 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008887 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008888 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008889 hasFastCapture() &&
8890 // there are sufficient fast track slots available
8891 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008892 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008893 // check compatibility with audio effects.
Andy Hungf8635b62023-08-31 16:13:39 -07008894 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008895 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008896 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008897 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008898 audio_input_flags_t old = *flags;
8899 chain->checkInputFlagCompatibility(flags);
8900 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008901 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8902 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008903 }
8904 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008905 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008906 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8907 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008908 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008909 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8910 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008911 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008912 this, frameCount, mFrameCount, mPipeFramesP2,
8913 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008914 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008915 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008916 }
8917 }
8918
Eric Laurentf14db3c2017-12-08 14:20:36 -08008919 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8920 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8921 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8922 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8923 lStatus = BAD_TYPE;
8924 goto Exit;
8925 }
8926
Glenn Kasten74105912014-07-03 12:28:53 -07008927 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008928 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008929 // fast track: frame count is exactly the pipe depth
8930 frameCount = mPipeFramesP2;
8931 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008932 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008933 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008934 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8935 // or 20 ms if there is a fast capture
8936 // TODO This could be a roundupRatio inline, and const
8937 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8938 * sampleRate + mSampleRate - 1) / mSampleRate;
8939 // minimum number of notification periods is at least kMinNotifications,
8940 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8941 static const size_t kMinNotifications = 3;
8942 static const uint32_t kMinMs = 30;
8943 // TODO This could be a roundupRatio inline
8944 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8945 // TODO This could be a roundupRatio inline
8946 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8947 maxNotificationFrames;
8948 const size_t minFrameCount = maxNotificationFrames *
8949 max(kMinNotifications, minNotificationsByMs);
8950 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008951 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8952 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008953 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008954 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008955 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008956 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008957
Andy Hungb17d24b2023-08-29 14:26:09 -07008958 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07008959 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008960 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008961 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008962 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008963 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008964 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008965 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008966 }
Eric Laurent81784c32012-11-19 14:55:58 -08008967
Andy Hung11e74242023-06-26 19:20:57 -07008968 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008969 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008970 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07008971 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008972 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008973
Glenn Kasten03003332013-08-06 15:40:54 -07008974 lStatus = track->initCheck();
8975 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008976 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008977 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008978 goto Exit;
8979 }
8980 mTracks.add(track);
8981
Eric Laurent05067782016-06-01 18:27:28 -07008982 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008983 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8984 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8985 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008986 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008987 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008988
8989 if (maxSharedAudioHistoryMs != 0) {
8990 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8991 }
Eric Laurent81784c32012-11-19 14:55:58 -08008992 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008993
Eric Laurent81784c32012-11-19 14:55:58 -08008994 lStatus = NO_ERROR;
8995
8996Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008997 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008998 return track;
8999}
9000
Andy Hung4b17e882023-07-07 13:47:37 -07009001status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009002 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009003 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009004{
9005 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9006 sp<ThreadBase> strongMe = this;
9007 status_t status = NO_ERROR;
9008
9009 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009010 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009011 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07009012 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07009013 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009014 event, triggerSession,
9015 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009016 }
9017
9018 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009019 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hungf8635b62023-08-31 16:13:39 -07009020 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009021 if (recordTrack->isInvalid()) {
9022 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009023 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9024 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009025 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009026 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07009027 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009028 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9029 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009030 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07009031 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009032 } else {
Andy Hung11e74242023-06-26 19:20:57 -07009033 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009034 }
9035 return status;
9036 }
9037
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009038 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9039 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9040 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07009041 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009042 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009043 if (recordTrack->isExternalTrack()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009044 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009045 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07009046 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009047 if (recordTrack->isInvalid()) {
9048 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07009049 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9050 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009051 // STARTING_2 forces destroy to call stopInput.
9052 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009053 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9054 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009055 }
Andy Hung11e74242023-06-26 19:20:57 -07009056 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009057 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07009058 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009059 // Someone else has changed state, let them take over,
9060 // leave mState in the new state.
9061 recordTrack->clearSyncStartEvent();
9062 return INVALID_OPERATION;
9063 }
9064 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009065 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009066 ALOGW("%s(%d): startInput failed, status %d",
9067 __func__, recordTrack->id(), status);
9068 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9069 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009070 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009071 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009072 return status;
9073 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009074 sendIoConfigEvent_l(
9075 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009076 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009077
9078 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9079
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009080 // Catch up with current buffer indices if thread is already running.
9081 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9082 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9083 // see previously buffered data before it called start(), but with greater risk of overrun.
9084
Andy Hung11e74242023-06-26 19:20:57 -07009085 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009086 if (!recordTrack->isDirect()) {
9087 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07009088 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009089 }
Andy Hung11e74242023-06-26 19:20:57 -07009090 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009091 // signal thread to start
Andy Hungb17d24b2023-08-29 14:26:09 -07009092 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009093 return status;
9094 }
Eric Laurent81784c32012-11-19 14:55:58 -08009095}
9096
Andy Hung4b17e882023-07-07 13:47:37 -07009097void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009098{
Andy Hung4b17e882023-07-07 13:47:37 -07009099 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009100
9101 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07009102 sp<IAfTrackBase> ptr =
9103 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9104 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07009105 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07009106 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009107 }
Eric Laurent81784c32012-11-19 14:55:58 -08009108 }
9109}
9110
Andy Hung4b17e882023-07-07 13:47:37 -07009111bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009112 ALOGV("RecordThread::stop");
Andy Hungb17d24b2023-08-29 14:26:09 -07009113 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009114 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07009115 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009116 return false;
9117 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009118 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07009119 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009120
Andy Hungabfab202019-03-07 19:45:54 -08009121 // NOTE: Waiting here is important to keep stop synchronous.
9122 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07009123 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009124 mWaitWorkCV.notify_all(); // signal thread to stop
9125 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009126 }
Andy Hungce685402018-10-05 17:23:27 -07009127
Andy Hung11e74242023-06-26 19:20:57 -07009128 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009129 ALOGV("Record stopped OK");
9130 return true;
9131 }
Andy Hungce685402018-10-05 17:23:27 -07009132
9133 // don't handle anything - we've been invalidated or restarted and in a different state
9134 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07009135 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009136 return false;
9137}
9138
Andy Hung4b17e882023-07-07 13:47:37 -07009139bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009140{
9141 return false;
9142}
9143
Andy Hung4b17e882023-07-07 13:47:37 -07009144status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009145{
9146#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9147 if (!isValidSyncEvent(event)) {
9148 return BAD_VALUE;
9149 }
9150
Glenn Kastend848eb42016-03-08 13:42:11 -08009151 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009152 status_t ret = NAME_NOT_FOUND;
9153
Andy Hungf8635b62023-08-31 16:13:39 -07009154 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009155
9156 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009157 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009158 if (eventSession == track->sessionId()) {
9159 (void) track->setSyncEvent(event);
9160 ret = NO_ERROR;
9161 }
9162 }
9163 return ret;
9164#else
9165 return BAD_VALUE;
9166#endif
9167}
9168
Andy Hung4b17e882023-07-07 13:47:37 -07009169status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07009170 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009171{
9172 ALOGV("RecordThread::getActiveMicrophones");
Andy Hungf8635b62023-08-31 16:13:39 -07009173 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009174 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009175 return NO_INIT;
9176 }
jiabin9ff780e2018-03-19 18:19:52 -07009177 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9178 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009179}
9180
Andy Hung4b17e882023-07-07 13:47:37 -07009181status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009182 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009183{
Paul McLean12340082019-03-19 09:35:05 -06009184 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hungf8635b62023-08-31 16:13:39 -07009185 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009186 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009187 return NO_INIT;
9188 }
Paul McLean12340082019-03-19 09:35:05 -06009189 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009190}
9191
Andy Hung4b17e882023-07-07 13:47:37 -07009192status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009193{
Paul McLean12340082019-03-19 09:35:05 -06009194 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hungf8635b62023-08-31 16:13:39 -07009195 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009196 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009197 return NO_INIT;
9198 }
Paul McLean12340082019-03-19 09:35:05 -06009199 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009200}
9201
Andy Hung4b17e882023-07-07 13:47:37 -07009202status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009203 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9204 int64_t sharedAudioStartMs) {
Andy Hungf8635b62023-08-31 16:13:39 -07009205 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009206 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9207}
9208
Andy Hung4b17e882023-07-07 13:47:37 -07009209status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009210 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9211 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009212
Eric Laurentec376dc2021-04-08 20:41:22 +02009213 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9214 return BAD_VALUE;
9215 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009216
9217 if (sharedAudioStartMs < 0
9218 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009219 return BAD_VALUE;
9220 }
9221
Eric Laurent2407ce32021-04-26 14:56:03 +02009222 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9223 // As we cannot detect more than one wraparound, only accept values up current write position
9224 // after one wraparound
9225 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9226 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009227 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009228 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9229 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009230 // Bring the start frame position within the input buffer to match the documented
9231 // "best effort" behavior of the API.
9232 if (sharedOffset < 0) {
9233 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009234 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009235 sharedAudioStartFrames =
9236 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009237 }
9238
Eric Laurentec376dc2021-04-08 20:41:22 +02009239 mSharedAudioPackageName = sharedAudioPackageName;
9240 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009241 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009242 } else {
9243 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009244 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009245 }
9246 return NO_ERROR;
9247}
9248
Andy Hung4b17e882023-07-07 13:47:37 -07009249void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009250 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9251 mSharedAudioStartFrames = -1;
9252 mSharedAudioPackageName = "";
9253}
9254
Andy Hung4b17e882023-07-07 13:47:37 -07009255ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009256{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009257 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009258 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009259 }
9260 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009261 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009262 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009263 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009264 }
9265 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009266 MetadataUpdate change;
9267 change.recordMetadataUpdate = metadata.tracks;
9268 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009269}
9270
Andy Hungb17d24b2023-08-29 14:26:09 -07009271// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07009272void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009273{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009274 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009275 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009276
Eric Laurent81784c32012-11-19 14:55:58 -08009277 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009278 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009279 removeTrack_l(track);
9280 }
9281}
9282
Andy Hung4b17e882023-07-07 13:47:37 -07009283void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009284{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009285 String8 result;
9286 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009287 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009288
Eric Laurent81784c32012-11-19 14:55:58 -08009289 mTracks.remove(track);
9290 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009291 if (track->isFastTrack()) {
9292 ALOG_ASSERT(!mFastTrackAvail);
9293 mFastTrackAvail = true;
9294 }
Eric Laurent81784c32012-11-19 14:55:58 -08009295}
9296
Andy Hung4b17e882023-07-07 13:47:37 -07009297void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009298{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009299 AudioStreamIn *input = mInput;
9300 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9301 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009302 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009303 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009304 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009305 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009306 }
Andy Hungbfa64962017-06-12 14:43:19 -07009307
9308 if (input != nullptr) {
9309 dprintf(fd, " Hal stream dump:\n");
9310 (void)input->stream->dump(fd);
9311 }
9312
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009313 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009314 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009315
Glenn Kasten2f90c512015-12-02 11:40:09 -08009316 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9317 // while we are dumping it. It may be inconsistent, but it won't mutate!
9318 // This is a large object so we place it on the heap.
9319 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009320 const std::unique_ptr<FastCaptureDumpState> copy =
9321 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009322 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009323}
9324
Andy Hung4b17e882023-07-07 13:47:37 -07009325void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009326{
Eric Laurent81784c32012-11-19 14:55:58 -08009327 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009328 size_t numtracks = mTracks.size();
9329 size_t numactive = mActiveTracks.size();
9330 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009331 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009332 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009333 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009334 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009335 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009336 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009337 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009338 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009339 if (track != 0) {
9340 bool active = mActiveTracks.indexOf(track) >= 0;
9341 if (active) {
9342 numactiveseen++;
9343 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009344 result.append(prefix);
9345 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009346 }
Eric Laurent81784c32012-11-19 14:55:58 -08009347 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009348 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009349 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009350 }
9351
Marco Nelissenb2208842014-02-07 14:00:50 -08009352 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009353 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009354 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009355 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009356 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009357 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009358 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009359 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009360 result.append(prefix);
9361 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009362 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009363 }
Eric Laurent81784c32012-11-19 14:55:58 -08009364
9365 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009366 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009367}
9368
Andy Hung4b17e882023-07-07 13:47:37 -07009369void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009370{
Andy Hungf8635b62023-08-31 16:13:39 -07009371 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009372 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009373 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009374 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009375 track->setSilenced(silenced);
9376 }
9377 }
9378}
Andy Hung73c02e42015-03-29 01:13:58 -07009379
Andy Hung11e74242023-06-26 19:20:57 -07009380void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009381{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009382 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009383 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009384 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009385 const int32_t rear = recordThread->mRsmpInRear;
9386 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009387 if (mRecordTrack->startFrames() >= 0) {
9388 int32_t startFrames = mRecordTrack->startFrames();
9389 // Accept a recent wraparound of mRsmpInRear
9390 if (startFrames <= rear) {
9391 deltaFrames = rear - startFrames;
9392 } else {
9393 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009394 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009395 // start frame cannot be further in the past than start of resampling buffer
9396 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9397 deltaFrames = recordThread->mRsmpInFrames;
9398 }
9399 }
9400 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009401}
9402
Andy Hung11e74242023-06-26 19:20:57 -07009403void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009404 size_t *framesAvailable, bool *hasOverrun)
9405{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009406 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009407 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009408 const int32_t rear = recordThread->mRsmpInRear;
9409 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009410 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009411
9412 size_t framesIn;
9413 bool overrun = false;
9414 if (filled < 0) {
9415 // should not happen, but treat like a massive overrun and re-sync
9416 framesIn = 0;
9417 mRsmpInFront = rear;
9418 overrun = true;
9419 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9420 framesIn = (size_t) filled;
9421 } else {
9422 // client is not keeping up with server, but give it latest data
9423 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009424 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9425 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009426 overrun = true;
9427 }
9428 if (framesAvailable != NULL) {
9429 *framesAvailable = framesIn;
9430 }
9431 if (hasOverrun != NULL) {
9432 *hasOverrun = overrun;
9433 }
9434}
9435
Eric Laurent81784c32012-11-19 14:55:58 -08009436// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009437status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009438 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009439{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009440 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009441 if (threadBase == 0) {
9442 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009443 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009444 return NOT_ENOUGH_DATA;
9445 }
Andy Hung4b17e882023-07-07 13:47:37 -07009446 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009447 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009448 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009449 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009450 // FIXME should not be P2 (don't want to increase latency)
9451 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009452 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009453 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009454
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009455 front &= recordThread->mRsmpInFramesP2 - 1;
9456 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009457 if (part1 > (size_t) filled) {
9458 part1 = filled;
9459 }
9460 size_t ask = buffer->frameCount;
9461 ALOG_ASSERT(ask > 0);
9462 if (part1 > ask) {
9463 part1 = ask;
9464 }
9465 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009466 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009467 buffer->raw = NULL;
9468 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009469 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009470 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009471 }
9472
Andy Hung57446612015-04-19 23:56:46 -07009473 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009474 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009475 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009476 return NO_ERROR;
9477}
9478
9479// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009480void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009481 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009482{
Hongwei Wang95e37682019-04-12 11:13:36 -07009483 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009484 if (stepCount == 0) {
9485 return;
9486 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009487 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009488 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009489 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009490 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009491 buffer->frameCount = 0;
9492}
9493
Andy Hung4b17e882023-07-07 13:47:37 -07009494void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009495{
Andy Hungf8635b62023-08-31 16:13:39 -07009496 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009497 checkBtNrec_l();
9498}
9499
Andy Hung4b17e882023-07-07 13:47:37 -07009500void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009501{
9502 // disable AEC and NS if the device is a BT SCO headset supporting those
9503 // pre processings
Andy Hung94dfbb42023-09-06 19:41:47 -07009504 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009505 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009506 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9507 for (size_t i = 0; i < mEffectChains.size(); i++) {
9508 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9509 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9510 }
9511 }
9512}
9513
Andy Hung97a893e2015-03-29 01:03:07 -07009514
Andy Hung4b17e882023-07-07 13:47:37 -07009515bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009516 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009517{
9518 bool reconfig = false;
9519
Eric Laurent10351942014-05-08 18:49:52 -07009520 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009521
Eric Laurent10351942014-05-08 18:49:52 -07009522 audio_format_t reqFormat = mFormat;
9523 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009524 // 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 +08009525 [[maybe_unused]] audio_channel_mask_t channelMask =
9526 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009527
9528 AudioParameter param = AudioParameter(keyValuePair);
9529 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009530
9531 // scope for AutoPark extends to end of method
9532 AutoPark<FastCapture> park(mFastCapture);
9533
Eric Laurent10351942014-05-08 18:49:52 -07009534 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9535 // channel count change can be requested. Do we mandate the first client defines the
9536 // HAL sampling rate and channel count or do we allow changes on the fly?
9537 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9538 samplingRate = value;
9539 reconfig = true;
9540 }
9541 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009542 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009543 status = BAD_VALUE;
9544 } else {
9545 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009546 reconfig = true;
9547 }
Eric Laurent10351942014-05-08 18:49:52 -07009548 }
9549 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9550 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009551 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009552 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009553 status = BAD_VALUE;
9554 } else {
9555 channelMask = mask;
9556 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009557 }
Eric Laurent10351942014-05-08 18:49:52 -07009558 }
9559 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9560 // do not accept frame count changes if tracks are open as the track buffer
9561 // size depends on frame count and correct behavior would not be guaranteed
9562 // if frame count is changed after track creation
9563 if (mActiveTracks.size() > 0) {
9564 status = INVALID_OPERATION;
9565 } else {
9566 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009567 }
Eric Laurent10351942014-05-08 18:49:52 -07009568 }
9569 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009570 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009571 }
9572 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9573 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009574 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009575 }
Glenn Kastene198c362013-08-13 09:13:36 -07009576
Eric Laurent10351942014-05-08 18:49:52 -07009577 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009578 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009579 if (status == INVALID_OPERATION) {
9580 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009581 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009582 }
9583 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009584 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009585 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9586 if (mInput->stream->getAudioProperties(&config) == OK &&
9587 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9588 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009589 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009590 status = NO_ERROR;
9591 }
Eric Laurent81784c32012-11-19 14:55:58 -08009592 }
Eric Laurent10351942014-05-08 18:49:52 -07009593 if (status == NO_ERROR) {
9594 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009595 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009596 }
9597 }
Eric Laurent81784c32012-11-19 14:55:58 -08009598 }
Eric Laurent10351942014-05-08 18:49:52 -07009599
Eric Laurent81784c32012-11-19 14:55:58 -08009600 return reconfig;
9601}
9602
Andy Hung4b17e882023-07-07 13:47:37 -07009603String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009604{
Andy Hungf8635b62023-08-31 16:13:39 -07009605 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009606 if (initCheck() == NO_ERROR) {
9607 String8 out_s8;
9608 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9609 return out_s8;
9610 }
Eric Laurent81784c32012-11-19 14:55:58 -08009611 }
Andy Hung920f6572022-10-06 12:09:49 -07009612 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009613}
9614
Andy Hung94dfbb42023-09-06 19:41:47 -07009615void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009616 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009617 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009618 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009619 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009620 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009621 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009622 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9623 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009624 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009625 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009626 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009627 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009628 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009629 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009630 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009631 break;
9632 }
Andy Hung94dfbb42023-09-06 19:41:47 -07009633 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009634}
9635
Andy Hung4b17e882023-07-07 13:47:37 -07009636void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009637{
Dean Wheatley6c009512023-10-23 09:34:14 +11009638 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9639 mSampleRate = audioConfig.sample_rate;
9640 mChannelMask = audioConfig.channel_mask;
9641 if (!audio_is_input_channel(mChannelMask)) {
9642 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9643 }
9644
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009645 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009646
9647 // Get actual HAL format.
9648 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9649 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9650 // Get format from the shim, which will be different than the HAL format
9651 // if recording compressed audio from IEC61937 wrapped sources.
9652 mFormat = audioConfig.format;
9653 if (!audio_is_valid_format(mFormat)) {
9654 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9655 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009656 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009657 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9658 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009659 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009660 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009661 ALOGI("HAL format %#x is not linear pcm", mFormat);
9662 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009663 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009664 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9665 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009666 result = mInput->stream->getBufferSize(&mBufferSize);
9667 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009668 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009669 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9670 "mBufferSize=%zu, mFrameCount=%zu",
9671 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009672
Eric Laurentec376dc2021-04-08 20:41:22 +02009673 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9674 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009675 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009676
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009677 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9678 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009679
9680 audio_input_flags_t flags = mInput->flags;
9681 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9682 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07009683 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009684 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9685 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9686 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9687 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9688 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9689 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009690}
9691
Andy Hung4b17e882023-07-07 13:47:37 -07009692uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009693{
Andy Hungf8635b62023-08-31 16:13:39 -07009694 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009695 uint32_t result;
9696 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9697 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009698 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009699 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009700}
9701
Andy Hung4b17e882023-07-07 13:47:37 -07009702KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009703{
Glenn Kastend848eb42016-03-08 13:42:11 -08009704 KeyedVector<audio_session_t, bool> ids;
Andy Hungf8635b62023-08-31 16:13:39 -07009705 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009706 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009707 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009708 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009709 if (ids.indexOfKey(sessionId) < 0) {
9710 ids.add(sessionId, true);
9711 }
9712 }
9713 return ids;
9714}
9715
Andy Hung4b17e882023-07-07 13:47:37 -07009716AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009717{
Andy Hungf8635b62023-08-31 16:13:39 -07009718 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009719 AudioStreamIn *input = mInput;
9720 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009721 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009722 return input;
9723}
9724
Andy Hungb17d24b2023-08-29 14:26:09 -07009725// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009726sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009727{
9728 if (mInput == NULL) {
9729 return NULL;
9730 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009731 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009732}
9733
Andy Hung4b17e882023-07-07 13:47:37 -07009734status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009735{
Eric Laurent81784c32012-11-19 14:55:58 -08009736 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009737 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009738 chain->setInBuffer(NULL);
9739 chain->setOutBuffer(NULL);
9740
9741 checkSuspendOnAddEffectChain_l(chain);
9742
Eric Laurent1b928682014-10-02 19:41:47 -07009743 // make sure enabled pre processing effects state is communicated to the HAL as we
9744 // just moved them to a new input stream.
9745 chain->syncHalEffectsState();
9746
Eric Laurent81784c32012-11-19 14:55:58 -08009747 mEffectChains.add(chain);
9748
9749 return NO_ERROR;
9750}
9751
Andy Hung4b17e882023-07-07 13:47:37 -07009752size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009753{
9754 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009755
9756 for (size_t i = 0; i < mEffectChains.size(); i++) {
9757 if (chain == mEffectChains[i]) {
9758 mEffectChains.removeAt(i);
9759 break;
9760 }
Eric Laurent81784c32012-11-19 14:55:58 -08009761 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009762 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009763}
9764
Andy Hung4b17e882023-07-07 13:47:37 -07009765status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009766 audio_patch_handle_t *handle)
9767{
9768 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009769
9770 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009771 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009772 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009773 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009774 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009775 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009776 }
9777
Eric Laurentd8365c52017-07-16 15:27:05 -07009778 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009779
9780 // store new source and send to effects
9781 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9782 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009783 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009784 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009785 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009786 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009787
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009788 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009789 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9790 status = hwDevice->createAudioPatch(patch->num_sources,
9791 patch->sources,
9792 patch->num_sinks,
9793 patch->sinks,
9794 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009795 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009796 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9797 patch->sinks[0].ext.mix.usecase.source,
9798 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009799 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009800 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009801
jiabinc52b1ff2019-10-31 17:20:42 -07009802 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009803 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009804 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009805 }
Eric Laurent296fb132015-05-01 11:38:42 -07009806
Andy Hungc2b11cb2020-04-22 09:04:01 -07009807 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009808 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009809 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009810 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009811 // also dispatch to active AudioRecords
9812 for (const auto &track : mActiveTracks) {
9813 track->logEndInterval();
9814 track->logBeginInterval(pathSourcesAsString);
9815 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009816 // Force meteadata update after a route change
9817 mActiveTracks.setHasChanged();
9818
Eric Laurent1c333e22014-05-20 10:48:17 -07009819 return status;
9820}
9821
Andy Hung4b17e882023-07-07 13:47:37 -07009822status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009823{
9824 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009825
jiabinc52b1ff2019-10-31 17:20:42 -07009826 mPatch = audio_patch{};
9827 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009828
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009829 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009830 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9831 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009832 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009833 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009834 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009835 // Force meteadata update after a route change
9836 mActiveTracks.setHasChanged();
9837
Eric Laurent1c333e22014-05-20 10:48:17 -07009838 return status;
9839}
9840
Andy Hung4b17e882023-07-07 13:47:37 -07009841void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009842{
Andy Hungf8635b62023-08-31 16:13:39 -07009843 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009844 mOutDevices = outDevices;
9845 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9846 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009847 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009848 }
9849}
9850
Andy Hung4b17e882023-07-07 13:47:37 -07009851int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009852{
9853 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009854 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009855 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009856 int32_t oldestFront = mRsmpInRear;
9857 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009858 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009859 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009860 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009861 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009862 if (filled > maxFilled) {
9863 oldestFront = front;
9864 maxFilled = filled;
9865 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009866 }
Andy Hung920f6572022-10-06 12:09:49 -07009867 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009868 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9869 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009870 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009871}
9872
Andy Hung4b17e882023-07-07 13:47:37 -07009873void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009874{
9875 if (offset == 0) {
9876 return;
9877 }
9878 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009879 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009880 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009881 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009882 }
9883}
9884
Andy Hung4b17e882023-07-07 13:47:37 -07009885void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009886{
9887 // This is the formula for calculating the temporary buffer size.
9888 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9889 // 1 full output buffer, regardless of the alignment of the available input.
9890 // The value is somewhat arbitrary, and could probably be even larger.
9891 // A larger value should allow more old data to be read after a track calls start(),
9892 // without increasing latency.
9893 //
9894 // Note this is independent of the maximum downsampling ratio permitted for capture.
9895 size_t minRsmpInFrames = mFrameCount * 7;
9896
9897 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9898 // capture history available to another client using the same session ID:
9899 // dimension the resampler input buffer accordingly.
9900
9901 // Get oldest client read position: getOldestFront_l() must be called before altering
9902 // mRsmpInRear, or mRsmpInFrames
9903 int32_t previousFront = getOldestFront_l();
9904 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9905 int32_t previousRear = mRsmpInRear;
9906 mRsmpInRear = 0;
9907
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009908 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009909 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009910 "resizeInputBuffer_l() called with invalid max shared history %d",
9911 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009912 if (maxSharedAudioHistoryMs != 0) {
9913 // resizeInputBuffer_l should never be called with a non zero shared history if the
9914 // buffer was not already allocated
9915 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9916 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9917 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9918 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009919 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009920 return;
9921 }
9922 mRsmpInFrames = rsmpInFrames;
9923 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009924 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009925 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9926 // initialized
9927 if (mRsmpInFrames < minRsmpInFrames) {
9928 mRsmpInFrames = minRsmpInFrames;
9929 }
9930 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9931
9932 // TODO optimize audio capture buffer sizes ...
9933 // Here we calculate the size of the sliding buffer used as a source
9934 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9935 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9936 // be better to have it derived from the pipe depth in the long term.
9937 // The current value is higher than necessary. However it should not add to latency.
9938
9939 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9940 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9941
9942 void *rsmpInBuffer;
9943 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9944 // if posix_memalign fails, will segv here.
9945 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9946
9947 // Copy audio history if any from old buffer before freeing it
9948 if (previousRear != 0) {
9949 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9950 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9951
9952 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9953 previousFront &= previousRsmpInFramesP2 - 1;
9954 size_t part1 = previousRsmpInFramesP2 - previousFront;
9955 if (part1 > (size_t) unread) {
9956 part1 = unread;
9957 }
9958 if (part1 != 0) {
9959 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9960 part1 * mFrameSize);
9961 mRsmpInRear = part1;
9962 part1 = unread - part1;
9963 if (part1 != 0) {
9964 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9965 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9966 mRsmpInRear += part1;
9967 }
9968 }
9969 // Update front for all clients according to new rear
9970 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9971 } else {
9972 mRsmpInRear = 0;
9973 }
9974 free(mRsmpInBuffer);
9975 mRsmpInBuffer = rsmpInBuffer;
9976}
9977
Andy Hung4b17e882023-07-07 13:47:37 -07009978void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009979{
Andy Hungf8635b62023-08-31 16:13:39 -07009980 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009981 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009982 if (record->getSource()) {
9983 mSource = record->getSource();
9984 }
Eric Laurent83b88082014-06-20 18:31:16 -07009985}
9986
Andy Hung4b17e882023-07-07 13:47:37 -07009987void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009988{
Andy Hungf8635b62023-08-31 16:13:39 -07009989 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009990 if (mSource == record->getSource()) {
9991 mSource = mInput;
9992 }
Eric Laurent83b88082014-06-20 18:31:16 -07009993 destroyTrack_l(record);
9994}
9995
Andy Hung4b17e882023-07-07 13:47:37 -07009996void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009997{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009998 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009999 config->role = AUDIO_PORT_ROLE_SINK;
10000 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10001 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010002 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10003 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10004 config->flags.input = mInput->flags;
10005 }
Eric Laurent83b88082014-06-20 18:31:16 -070010006}
Eric Laurent1c333e22014-05-20 10:48:17 -070010007
Eric Laurent6acd1d42017-01-04 14:23:29 -080010008// ----------------------------------------------------------------------------
10009// Mmap
10010// ----------------------------------------------------------------------------
10011
Andy Hung765de282023-07-07 15:58:48 -070010012// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10013// MmapPlaybackThread or MmapCaptureThread instance.
10014class MmapThreadHandle : public MmapStreamInterface {
10015public:
10016 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10017 ~MmapThreadHandle() override;
10018
10019 // MmapStreamInterface virtuals
10020 status_t createMmapBuffer(int32_t minSizeFrames,
10021 struct audio_mmap_buffer_info* info) final;
10022 status_t getMmapPosition(struct audio_mmap_position* position) final;
10023 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10024 status_t start(const AudioClient& client,
10025 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10026 status_t stop(audio_port_handle_t handle) final;
10027 status_t standby() final;
10028 status_t reportData(const void* buffer, size_t frameCount) final;
10029private:
10030 const sp<IAfMmapThread> mThread;
10031};
10032
10033/* static */
10034sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10035 const sp<IAfMmapThread>& mmapThread) {
10036 return sp<MmapThreadHandle>::make(mmapThread);
10037}
10038
10039MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010040 : mThread(thread)
10041{
Phil Burk9fabbf82017-08-03 12:02:00 -070010042 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010043}
10044
Andy Hung765de282023-07-07 15:58:48 -070010045// MmapStreamInterface could be directly implemented by MmapThread excepting this
10046// special handling on adapter dtor.
10047MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010048{
Phil Burk9fabbf82017-08-03 12:02:00 -070010049 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050}
10051
Andy Hung765de282023-07-07 15:58:48 -070010052status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010053 struct audio_mmap_buffer_info *info)
10054{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055 return mThread->createMmapBuffer(minSizeFrames, info);
10056}
10057
Andy Hung765de282023-07-07 15:58:48 -070010058status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010059{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060 return mThread->getMmapPosition(position);
10061}
10062
Andy Hung765de282023-07-07 15:58:48 -070010063status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010064 int64_t *timeNanos) {
10065 return mThread->getExternalPosition(position, timeNanos);
10066}
10067
Andy Hung765de282023-07-07 15:58:48 -070010068status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010069 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010070{
jiabind1f1cb62020-03-24 11:57:57 -070010071 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010072}
10073
Andy Hung765de282023-07-07 15:58:48 -070010074status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010075{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010076 return mThread->stop(handle);
10077}
10078
Andy Hung765de282023-07-07 15:58:48 -070010079status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010080{
Eric Laurent18b57012017-02-13 16:23:52 -080010081 return mThread->standby();
10082}
10083
Andy Hung765de282023-07-07 15:58:48 -070010084status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10085{
jiabinfc791ee2023-02-15 19:43:40 +000010086 return mThread->reportData(buffer, frameCount);
10087}
10088
Eric Laurent6acd1d42017-01-04 14:23:29 -080010089
Andy Hung4b17e882023-07-07 13:47:37 -070010090MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010091 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010092 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -070010093 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010094 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010095 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010096 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010097 mActiveTracks(&this->mLocalLog),
10098 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10099 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010100{
Eric Laurent18b57012017-02-13 16:23:52 -080010101 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010102 readHalParameters_l();
10103}
10104
Andy Hung4b17e882023-07-07 13:47:37 -070010105void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106{
10107 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10108}
10109
Andy Hung4b17e882023-07-07 13:47:37 -070010110void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010111{
Andy Hung11e74242023-06-26 19:20:57 -070010112 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010113 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010114 {
Andy Hungf8635b62023-08-31 16:13:39 -070010115 audio_utils::lock_guard _l(mutex());
Andy Hung11e74242023-06-26 19:20:57 -070010116 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010117 activeTracks.add(t);
10118 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010119 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010120 }
Andy Hung11e74242023-06-26 19:20:57 -070010121 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010122 stop(t->portId());
10123 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010124 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010125 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010126 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010127 } else {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010128 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129 }
10130}
10131
10132
Andy Hung160664b2023-09-15 18:19:28 -070010133void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010134 audio_stream_type_t streamType __unused,
10135 audio_session_t sessionId,
10136 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010137 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138 audio_port_handle_t portId)
10139{
10140 mAttr = *attr;
10141 mSessionId = sessionId;
10142 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010143 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144 mPortId = portId;
10145}
10146
Andy Hung4b17e882023-07-07 13:47:37 -070010147status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010148 struct audio_mmap_buffer_info *info)
10149{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010150 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010151 if (mHalStream == 0) {
10152 return NO_INIT;
10153 }
Eric Laurent18b57012017-02-13 16:23:52 -080010154 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010155 return mHalStream->createMmapBuffer(minSizeFrames, info);
10156}
10157
Andy Hung4b17e882023-07-07 13:47:37 -070010158status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010159{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010160 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 if (mHalStream == 0) {
10162 return NO_INIT;
10163 }
10164 return mHalStream->getMmapPosition(position);
10165}
10166
Andy Hung4b17e882023-07-07 13:47:37 -070010167status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010168{
Eric Laurentdda206a2022-07-08 17:28:35 +020010169 // The HAL must receive track metadata before starting the stream
10170 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010171 status_t ret = mHalStream->start();
10172 if (ret != NO_ERROR) {
10173 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10174 return ret;
10175 }
Andy Hungcf10d742020-04-28 15:38:24 -070010176 if (mStandby) {
10177 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010178 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010179 mStandby = false;
10180 }
Eric Laurent331679c2018-04-16 17:03:16 -070010181 return NO_ERROR;
10182}
10183
Andy Hung4b17e882023-07-07 13:47:37 -070010184status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010185 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010186 audio_port_handle_t *handle)
10187{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010188 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010189 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010190 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191 if (mHalStream == 0) {
10192 return NO_INIT;
10193 }
10194
10195 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196
Eric Laurentdda206a2022-07-08 17:28:35 +020010197 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010198 if (*handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010199 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010200 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010201 }
10202
10203 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10204
10205 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010206 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010207 client.attributionSource);
10208
Andy Hungbcfd9e12023-09-19 14:48:41 -070010209 const auto localSessionId = mSessionId;
10210 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010211 if (isOutput()) {
10212 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10213 config.sample_rate = mSampleRate;
10214 config.channel_mask = mChannelMask;
10215 config.format = mFormat;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010216 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010217 audio_output_flags_t flags =
10218 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010219 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010220 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010221 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010222 bool isBitPerfect;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010223 mutex().unlock();
10224 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10225 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010226 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010227 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010228 &config,
10229 flags,
10230 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010231 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010232 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010233 &isSpatialized,
10234 &isBitPerfect);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010235 mutex().lock();
10236 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010237 ALOGD_IF(!secondaryOutputs.empty(),
10238 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010239 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010240 audio_config_base_t config;
10241 config.sample_rate = mSampleRate;
10242 config.channel_mask = mChannelMask;
10243 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010244 audio_port_handle_t deviceId = mDeviceId;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010245 mutex().unlock();
10246 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010247 RECORD_RIID_INVALID,
Andy Hungbcfd9e12023-09-19 14:48:41 -070010248 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010249 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010250 &config,
10251 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10252 &deviceId,
10253 &portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010254 mutex().lock();
10255 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010256 }
10257 // APM should not chose a different input or output stream for the same set of attributes
10258 // and audo configuration
10259 if (ret != NO_ERROR || io != mId) {
10260 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10261 __FUNCTION__, ret, io, mId);
10262 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263 }
10264
10265 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010266 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010267 ret = AudioSystem::startOutput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010268 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 } else {
jiabin09609032022-06-15 19:26:01 +000010270 {
10271 // Add the track record before starting input so that the silent status for the
10272 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010273 setClientSilencedState_l(portId, false /*silenced*/);
10274 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010275 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010276 ret = AudioSystem::startInput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010277 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010278 }
10279
10280 // abort if start is rejected by audio policy manager
10281 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010282 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010283 if (!mActiveTracks.isEmpty()) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010284 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010286 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010287 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010288 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010290 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010291 } else {
10292 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 }
jiabin09609032022-06-15 19:26:01 +000010294 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295 return PERMISSION_DENIED;
10296 }
10297
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010298 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010299 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10300 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010301 mChannelMask, mSessionId, isOutput(),
10302 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010303 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010304 if (!isOutput()) {
10305 track->setSilenced_l(isClientSilenced_l(portId));
10306 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307
Eric Laurent4eb58f12018-12-07 16:41:02 -080010308 if (isOutput()) {
10309 // force volume update when a new track is added
10310 mHalVolFloat = -1.0f;
10311 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010312 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010313 if (t->isSilenced_l()
10314 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010315 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010316 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010317 }
10318 }
10319
Eric Laurent6acd1d42017-01-04 14:23:29 -080010320 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010321 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010322 if (chain != 0) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010323 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010324 chain->incTrackCnt();
10325 chain->incActiveTrackCnt();
10326 }
10327
Andy Hungc2b11cb2020-04-22 09:04:01 -070010328 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010330
10331 if (mActiveTracks.size() == 1) {
10332 ret = exitStandby_l();
10333 }
10334
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335 broadcast_l();
10336
Eric Laurentdda206a2022-07-08 17:28:35 +020010337 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338
Eric Laurentdda206a2022-07-08 17:28:35 +020010339 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340}
10341
Andy Hung4b17e882023-07-07 13:47:37 -070010342status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010343{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010344 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010345 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346
10347 if (mHalStream == 0) {
10348 return NO_INIT;
10349 }
10350
Eric Laurenta54f1282017-07-01 19:39:32 -070010351 if (handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010352 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010353 return NO_ERROR;
10354 }
10355
Andy Hung11e74242023-06-26 19:20:57 -070010356 sp<IAfMmapTrack> track;
10357 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010358 if (handle == t->portId()) {
10359 track = t;
10360 break;
10361 }
10362 }
10363 if (track == 0) {
10364 return BAD_VALUE;
10365 }
10366
10367 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010368 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369
Andy Hungb17d24b2023-08-29 14:26:09 -070010370 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010371 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010372 AudioSystem::stopOutput(track->portId());
10373 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010375 AudioSystem::stopInput(track->portId());
10376 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010377 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010378 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010379
Andy Hung116bc262023-06-20 18:56:17 -070010380 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381 if (chain != 0) {
10382 chain->decActiveTrackCnt();
10383 chain->decTrackCnt();
10384 }
10385
Eric Laurentdda206a2022-07-08 17:28:35 +020010386 if (mActiveTracks.isEmpty()) {
10387 mHalStream->stop();
10388 }
10389
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390 broadcast_l();
10391
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392 return NO_ERROR;
10393}
10394
Andy Hung4b17e882023-07-07 13:47:37 -070010395status_t MmapThread::standby()
Andy Hungbcfd9e12023-09-19 14:48:41 -070010396NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010397{
10398 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010399 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010400
10401 if (mHalStream == 0) {
10402 return NO_INIT;
10403 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010404 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010405 return INVALID_OPERATION;
10406 }
10407 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010408 if (!mStandby) {
10409 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010410 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010411 mStandby = true;
10412 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010413 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010414 return NO_ERROR;
10415}
10416
Andy Hung4b17e882023-07-07 13:47:37 -070010417status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010418 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10419 return INVALID_OPERATION;
10420}
10421
Andy Hung4b17e882023-07-07 13:47:37 -070010422void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010423{
10424 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10425 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10426 mFormat = mHALFormat;
10427 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10428 result = mHalStream->getFrameSize(&mFrameSize);
10429 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010430 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10431 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010432 result = mHalStream->getBufferSize(&mBufferSize);
10433 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10434 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010435
Andy Hungcf10d742020-04-28 15:38:24 -070010436 // TODO: make a readHalParameters call?
10437 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010438 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -070010439 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010440 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10441 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10442 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10443 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10444 /*
10445 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10446 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10447 (int32_t)mHapticChannelMask)
10448 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10449 (int32_t)mHapticChannelCount)
10450 */
10451 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -070010452 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010453 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10454 (int32_t)mFrameCount) // sic - added HAL
10455 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456}
10457
Andy Hung4b17e882023-07-07 13:47:37 -070010458bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459{
Andy Hung94dfbb42023-09-06 19:41:47 -070010460 {
10461 audio_utils::unique_lock _l(mutex());
10462 checkSilentMode_l();
10463 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464
10465 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10466
10467 while (!exitPending())
10468 {
Andy Hung116bc262023-06-20 18:56:17 -070010469 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470
Andy Hung13850be2019-03-14 11:33:09 -070010471 { // under Thread lock
Andy Hungb17d24b2023-08-29 14:26:09 -070010472 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010473
Eric Laurent6acd1d42017-01-04 14:23:29 -080010474 if (mSignalPending) {
10475 // A signal was raised while we were unlocked
10476 mSignalPending = false;
10477 } else {
10478 if (mConfigEvents.isEmpty()) {
10479 // we're about to wait, flush the binder command buffer
10480 IPCThreadState::self()->flushCommands();
10481
10482 if (exitPending()) {
10483 break;
10484 }
10485
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010487 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -070010488 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010489 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010490
10491 checkSilentMode_l();
10492
10493 continue;
10494 }
10495 }
10496
10497 processConfigEvents_l();
10498
10499 processVolume_l();
10500
10501 checkInvalidTracks_l();
10502
Andy Hung94dfbb42023-09-06 19:41:47 -070010503 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010504
Kevin Rocard069c2712018-03-29 19:09:14 -070010505 updateMetadata_l();
10506
Eric Laurent6acd1d42017-01-04 14:23:29 -080010507 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010508 } // release Thread lock
10509
Eric Laurent6acd1d42017-01-04 14:23:29 -080010510 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010511 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512 }
Andy Hung13850be2019-03-14 11:33:09 -070010513
10514 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010515 unlockEffectChains(effectChains);
10516 // Effect chains will be actually deleted here if they were removed from
10517 // mEffectChains list during mixing or effects processing
10518 }
10519
10520 threadLoop_exit();
10521
10522 if (!mStandby) {
10523 threadLoop_standby();
10524 mStandby = true;
10525 }
10526
Eric Laurent6acd1d42017-01-04 14:23:29 -080010527 ALOGV("Thread %p type %d exiting", this, mType);
10528 return false;
10529}
10530
Andy Hungb17d24b2023-08-29 14:26:09 -070010531// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070010532bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010533 status_t& status)
10534{
10535 AudioParameter param = AudioParameter(keyValuePair);
10536 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010537 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010538 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010539 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010540 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010541 if (sendToHal) {
10542 status = mHalStream->setParameters(keyValuePair);
10543 } else {
10544 status = NO_ERROR;
10545 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010546
10547 return false;
10548}
10549
Andy Hung4b17e882023-07-07 13:47:37 -070010550String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551{
Andy Hungf8635b62023-08-31 16:13:39 -070010552 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553 String8 out_s8;
10554 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10555 return out_s8;
10556 }
Andy Hung920f6572022-10-06 12:09:49 -070010557 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558}
10559
Andy Hung94dfbb42023-09-06 19:41:47 -070010560void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010561 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010562 sp<AudioIoDescriptor> desc;
10563 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564 switch (event) {
10565 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010566 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010568 isInput = true;
10569 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010571 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010573 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10574 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010575 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576 case AUDIO_INPUT_CLOSED:
10577 case AUDIO_OUTPUT_CLOSED:
10578 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010579 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010580 break;
10581 }
Andy Hung94dfbb42023-09-06 19:41:47 -070010582 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010583}
10584
Andy Hung4b17e882023-07-07 13:47:37 -070010585status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010586 audio_patch_handle_t *handle)
Andy Hungb17d24b2023-08-29 14:26:09 -070010587NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588{
10589 status_t status = NO_ERROR;
10590
10591 // store new device and send to effects
10592 audio_devices_t type = AUDIO_DEVICE_NONE;
10593 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010594 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10595 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10596 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010597 if (isOutput()) {
10598 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010599 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10600 && !mAudioHwDev->supportsAudioPatches(),
10601 "Enumerated device type(%#x) must not be used "
10602 "as it does not support audio patches",
10603 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010604 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010605 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10606 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 }
10608 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010609 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010610 } else {
10611 type = patch->sources[0].ext.device.type;
10612 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010613 numDevices = mPatch.num_sources;
10614 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010615 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616 }
10617
10618 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010619 if (isOutput()) {
10620 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10621 } else {
10622 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10623 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624 }
10625
jiabinc52b1ff2019-10-31 17:20:42 -070010626 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627 // store new source and send to effects
10628 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10629 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10630 for (size_t i = 0; i < mEffectChains.size(); i++) {
10631 mEffectChains[i]->setAudioSource_l(mAudioSource);
10632 }
10633 }
10634 }
10635
10636 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010637 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10638 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010639 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010640 audio_port_config port;
10641 std::optional<audio_source_t> source;
10642 if (isOutput()) {
10643 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010644 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010645 port = patch->sources[0];
10646 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010647 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010648 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649 *handle = AUDIO_PATCH_HANDLE_NONE;
10650 }
10651
jiabinc52b1ff2019-10-31 17:20:42 -070010652 if (numDevices == 0 || mDeviceId != deviceId) {
10653 if (isOutput()) {
10654 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10655 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010656 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010657 } else {
10658 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10659 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10660 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010661 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010662 if (mDeviceId != deviceId && callback != 0) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010663 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010664 callback->onRoutingChanged(deviceId);
Andy Hungb17d24b2023-08-29 14:26:09 -070010665 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010666 }
jiabinc52b1ff2019-10-31 17:20:42 -070010667 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010668 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010670 // Force meteadata update after a route change
10671 mActiveTracks.setHasChanged();
10672
Eric Laurent6acd1d42017-01-04 14:23:29 -080010673 return status;
10674}
10675
Andy Hung4b17e882023-07-07 13:47:37 -070010676status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010677{
10678 status_t status = NO_ERROR;
10679
jiabinc52b1ff2019-10-31 17:20:42 -070010680 mPatch = audio_patch{};
10681 mOutDeviceTypeAddrs.clear();
10682 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010683
10684 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10685 supportsAudioPatches : false;
10686
10687 if (supportsAudioPatches) {
10688 status = mHalDevice->releaseAudioPatch(handle);
10689 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010690 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010691 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010692 // Force meteadata update after a route change
10693 mActiveTracks.setHasChanged();
10694
Eric Laurent6acd1d42017-01-04 14:23:29 -080010695 return status;
10696}
10697
Andy Hung4b17e882023-07-07 13:47:37 -070010698void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hungbcfd9e12023-09-19 14:48:41 -070010699NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010701 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702 if (isOutput()) {
10703 config->role = AUDIO_PORT_ROLE_SOURCE;
10704 config->ext.mix.hw_module = mAudioHwDev->handle();
10705 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10706 } else {
10707 config->role = AUDIO_PORT_ROLE_SINK;
10708 config->ext.mix.hw_module = mAudioHwDev->handle();
10709 config->ext.mix.usecase.source = mAudioSource;
10710 }
10711}
10712
Andy Hung4b17e882023-07-07 13:47:37 -070010713status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010714{
10715 audio_session_t session = chain->sessionId();
10716
10717 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10718 // Attach all tracks with same session ID to this chain.
10719 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010720 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010721 if (session == track->sessionId()) {
10722 chain->incTrackCnt();
10723 chain->incActiveTrackCnt();
10724 }
10725 }
10726
10727 chain->setThread(this);
10728 chain->setInBuffer(nullptr);
10729 chain->setOutBuffer(nullptr);
10730 chain->syncHalEffectsState();
10731
10732 mEffectChains.add(chain);
10733 checkSuspendOnAddEffectChain_l(chain);
10734 return NO_ERROR;
10735}
10736
Andy Hung4b17e882023-07-07 13:47:37 -070010737size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010738{
10739 audio_session_t session = chain->sessionId();
10740
10741 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10742
10743 for (size_t i = 0; i < mEffectChains.size(); i++) {
10744 if (chain == mEffectChains[i]) {
10745 mEffectChains.removeAt(i);
10746 // detach all active tracks from the chain
10747 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010748 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010749 if (session == track->sessionId()) {
10750 chain->decActiveTrackCnt();
10751 chain->decTrackCnt();
10752 }
10753 }
10754 break;
10755 }
10756 }
10757 return mEffectChains.size();
10758}
10759
Andy Hung4b17e882023-07-07 13:47:37 -070010760void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010761{
10762 mHalStream->standby();
10763}
10764
Andy Hung4b17e882023-07-07 13:47:37 -070010765void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010766{
Phil Burk7dce7282017-09-27 13:51:41 -070010767 // Do not call callback->onTearDown() because it is redundant for thread exit
10768 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010769}
10770
Andy Hung4b17e882023-07-07 13:47:37 -070010771status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010772{
10773 return BAD_VALUE;
10774}
10775
Andy Hung4b17e882023-07-07 13:47:37 -070010776bool MmapThread::isValidSyncEvent(
10777 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010778{
10779 return false;
10780}
10781
Andy Hung4b17e882023-07-07 13:47:37 -070010782status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010783 const effect_descriptor_t *desc, audio_session_t sessionId)
10784{
10785 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010786 if (audio_is_global_session(sessionId)) {
10787 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010788 desc->name, mThreadName);
10789 return BAD_VALUE;
10790 }
10791
10792 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10793 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10794 desc->name);
10795 return BAD_VALUE;
10796 }
10797 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010798 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10799 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010800 return BAD_VALUE;
10801 }
10802
10803 // Only allow effects without processing load or latency
10804 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10805 return BAD_VALUE;
10806 }
10807
Andy Hung116bc262023-06-20 18:56:17 -070010808 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010809 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10810 return BAD_VALUE;
10811 }
10812
Eric Laurent6acd1d42017-01-04 14:23:29 -080010813 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010814}
10815
Andy Hung4b17e882023-07-07 13:47:37 -070010816void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010817{
Eric Laurent039c24a2022-10-07 14:01:59 +020010818 sp<MmapStreamCallback> callback;
Andy Hung11e74242023-06-26 19:20:57 -070010819 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010821 callback = mCallback.promote();
10822 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10823 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10824 mNoCallbackWarningCount++;
10825 }
10826 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010827 }
10828 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010829 if (callback != 0) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010830 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010831 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungb17d24b2023-08-29 14:26:09 -070010832 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010833 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010834}
10835
Andy Hung4b17e882023-07-07 13:47:37 -070010836void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010838 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10839 mAttr.content_type, mAttr.usage, mAttr.source);
10840 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010841 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010842 dprintf(fd, " No active clients\n");
10843 }
10844}
10845
Andy Hung4b17e882023-07-07 13:47:37 -070010846void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010847{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010848 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010849 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010850 dprintf(fd, " %zu Tracks\n", numtracks);
10851 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010852 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010853 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010854 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010855 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010856 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010857 result.append(prefix);
10858 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010859 }
10860 } else {
10861 dprintf(fd, "\n");
10862 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010863 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010864}
10865
Andy Hung4b17e882023-07-07 13:47:37 -070010866/* static */
10867sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010868 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010869 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010870 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010871}
10872
10873MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010874 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010875 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010876 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010877 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010878 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010879{
10880 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10881 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070010882 mMasterVolume = afThreadCallback->masterVolume_l();
10883 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent19611512023-07-03 18:14:07 +020010884
10885 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10886 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10887 mStreamTypes[stream].volume = 0.0f;
10888 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
10889 }
10890 // Audio patch and call assistant volume are always max
10891 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10892 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10893 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10894 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10895
Eric Laurent6acd1d42017-01-04 14:23:29 -080010896 if (mAudioHwDev) {
10897 if (mAudioHwDev->canSetMasterVolume()) {
10898 mMasterVolume = 1.0;
10899 }
10900
10901 if (mAudioHwDev->canSetMasterMute()) {
10902 mMasterMute = false;
10903 }
10904 }
10905}
10906
Andy Hung4b17e882023-07-07 13:47:37 -070010907void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010908 audio_stream_type_t streamType,
10909 audio_session_t sessionId,
10910 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010911 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912 audio_port_handle_t portId)
10913{
Andy Hung160664b2023-09-15 18:19:28 -070010914 audio_utils::lock_guard l(mutex());
10915 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010916 mStreamType = streamType;
10917}
10918
Andy Hung4b17e882023-07-07 13:47:37 -070010919AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010920{
Andy Hungf8635b62023-08-31 16:13:39 -070010921 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010922 AudioStreamOut *output = mOutput;
10923 mOutput = NULL;
10924 return output;
10925}
10926
Andy Hung4b17e882023-07-07 13:47:37 -070010927void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010928{
Andy Hungf8635b62023-08-31 16:13:39 -070010929 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010930 // Don't apply master volume in SW if our HAL can do it for us.
10931 if (mAudioHwDev &&
10932 mAudioHwDev->canSetMasterVolume()) {
10933 mMasterVolume = 1.0;
10934 } else {
10935 mMasterVolume = value;
10936 }
10937}
10938
Andy Hung4b17e882023-07-07 13:47:37 -070010939void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010940{
Andy Hungf8635b62023-08-31 16:13:39 -070010941 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942 // Don't apply master mute in SW if our HAL can do it for us.
10943 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10944 mMasterMute = false;
10945 } else {
10946 mMasterMute = muted;
10947 }
10948}
10949
Andy Hung4b17e882023-07-07 13:47:37 -070010950void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010951{
Andy Hungf8635b62023-08-31 16:13:39 -070010952 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010953 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010955 broadcast_l();
10956 }
10957}
10958
Andy Hung4b17e882023-07-07 13:47:37 -070010959float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010960{
Andy Hungf8635b62023-08-31 16:13:39 -070010961 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010962 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010963}
10964
Andy Hung4b17e882023-07-07 13:47:37 -070010965void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010966{
Andy Hungf8635b62023-08-31 16:13:39 -070010967 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010968 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010970 broadcast_l();
10971 }
10972}
10973
Andy Hung4b17e882023-07-07 13:47:37 -070010974void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010975{
Andy Hungf8635b62023-08-31 16:13:39 -070010976 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010977 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070010978 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010979 track->invalidate();
10980 }
10981 broadcast_l();
10982 }
10983}
10984
Andy Hung4b17e882023-07-07 13:47:37 -070010985void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010986{
Andy Hungf8635b62023-08-31 16:13:39 -070010987 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010988 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070010989 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010990 if (portIds.find(track->portId()) != portIds.end()) {
10991 track->invalidate();
10992 trackMatch = true;
10993 portIds.erase(track->portId());
10994 }
10995 if (portIds.empty()) {
10996 break;
10997 }
10998 }
10999 if (trackMatch) {
11000 broadcast_l();
11001 }
11002}
11003
Andy Hung4b17e882023-07-07 13:47:37 -070011004void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011005NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011006{
11007 float volume;
11008
Eric Laurent19611512023-07-03 18:14:07 +020011009 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011010 volume = 0;
11011 } else {
Eric Laurent19611512023-07-03 18:14:07 +020011012 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011013 }
11014
11015 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011016 // Convert volumes from float to 8.24
11017 uint32_t vol = (uint32_t)(volume * (1 << 24));
11018
11019 // Delegate volume control to effect in track effect chain if needed
11020 // only one effect chain can be present on DirectOutputThread, so if
11021 // there is one, the track is connected to it
11022 if (!mEffectChains.isEmpty()) {
11023 mEffectChains[0]->setVolume_l(&vol, &vol);
11024 volume = (float)vol / (1 << 24);
11025 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011026 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011027 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11028 mHalVolFloat = volume; // HW volume control worked, so update value.
11029 mNoCallbackWarningCount = 0;
11030 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011031 sp<MmapStreamCallback> callback = mCallback.promote();
11032 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011033 mHalVolFloat = volume; // SW volume control worked, so update value.
11034 mNoCallbackWarningCount = 0;
Andy Hungb17d24b2023-08-29 14:26:09 -070011035 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011036 callback->onVolumeChanged(volume);
Andy Hungb17d24b2023-08-29 14:26:09 -070011037 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011038 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011039 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11040 ALOGW("Could not set MMAP stream volume: no volume callback!");
11041 mNoCallbackWarningCount++;
11042 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011044 }
Andy Hung11e74242023-06-26 19:20:57 -070011045 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011046 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070011047 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011048 /*muteState=*/{mMasterMute,
Eric Laurent19611512023-07-03 18:14:07 +020011049 streamVolume_l() == 0.f,
11050 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011051 // TODO(b/241533526): adjust logic to include mute from AppOps
11052 false /*muteFromPlaybackRestricted*/,
11053 false /*muteFromClientVolume*/,
11054 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011055 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011056 }
11057}
11058
Andy Hung4b17e882023-07-07 13:47:37 -070011059ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011060{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011061 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011062 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011063 }
11064 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011065 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011066 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011067 playback_track_metadata_v7_t trackMetadata;
11068 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011069 .usage = track->attributes().usage,
11070 .content_type = track->attributes().content_type,
11071 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011072 };
11073 trackMetadata.channel_mask = track->channelMask(),
11074 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11075 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011076 }
11077 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011078
11079 MetadataUpdate change;
11080 change.playbackMetadataUpdate = metadata.tracks;
11081 return change;
11082};
Kevin Rocard069c2712018-03-29 19:09:14 -070011083
Andy Hung4b17e882023-07-07 13:47:37 -070011084void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011085{
11086 if (!mMasterMute) {
11087 char value[PROPERTY_VALUE_MAX];
11088 if (property_get("ro.audio.silent", value, "0") > 0) {
11089 char *endptr;
11090 unsigned long ul = strtoul(value, &endptr, 0);
11091 if (*endptr == '\0' && ul != 0) {
Andy Hung6fb26892024-02-20 16:32:57 -080011092 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011093 // The setprop command will not allow a property to be changed after
11094 // the first time it is set, so we don't have to worry about un-muting.
11095 setMasterMute_l(true);
11096 }
11097 }
11098 }
11099}
11100
Andy Hung4b17e882023-07-07 13:47:37 -070011101void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011102{
11103 MmapThread::toAudioPortConfig(config);
11104 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11105 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11106 config->flags.output = mOutput->flags;
11107 }
11108}
11109
Andy Hung4b17e882023-07-07 13:47:37 -070011110status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070011111 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011112{
11113 if (mOutput == nullptr) {
11114 return NO_INIT;
11115 }
11116 struct timespec timestamp;
11117 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11118 if (status == NO_ERROR) {
11119 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11120 }
11121 return status;
11122}
11123
Andy Hung4b17e882023-07-07 13:47:37 -070011124status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011125 // Send to MelProcessor for sound dose measurement.
11126 auto processor = mMelProcessor.load();
11127 if (processor) {
11128 processor->process(buffer, frameCount * mFrameSize);
11129 }
11130
jiabinfc791ee2023-02-15 19:43:40 +000011131 return NO_ERROR;
11132}
11133
Andy Hungb17d24b2023-08-29 14:26:09 -070011134// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011135void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011136 const sp<audio_utils::MelProcessor>& processor)
11137{
11138 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011139 mMelProcessor.store(processor);
11140 if (processor) {
11141 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011142 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011143
11144 // no need to update output format for MMapPlaybackThread since it is
11145 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011146}
11147
Andy Hungb17d24b2023-08-29 14:26:09 -070011148// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011149void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011150{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011151 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11152 auto melProcessor = mMelProcessor.load();
11153 if (melProcessor != nullptr) {
11154 melProcessor->pause();
11155 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011156}
11157
Andy Hung4b17e882023-07-07 13:47:37 -070011158void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011159{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011160 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011161
Glenn Kastend3bb6452016-12-05 18:14:37 -080011162 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent19611512023-07-03 18:14:07 +020011163 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011164 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11165}
11166
Andy Hung4b17e882023-07-07 13:47:37 -070011167/* static */
11168sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070011169 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070011170 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011171 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011172}
11173
11174MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011175 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011176 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011177 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011178 mInput(input)
11179{
11180 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11181 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11182}
11183
Andy Hung4b17e882023-07-07 13:47:37 -070011184status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011185{
Phil Burkf054fc32018-12-06 09:45:59 -080011186 {
11187 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011188 if (mInput != nullptr && mInput->stream != nullptr) {
11189 mInput->stream->setGain(1.0f);
11190 }
11191 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011192 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011193}
11194
Andy Hung4b17e882023-07-07 13:47:37 -070011195AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011196{
Andy Hungf8635b62023-08-31 16:13:39 -070011197 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011198 AudioStreamIn *input = mInput;
11199 mInput = NULL;
11200 return input;
11201}
Kevin Rocard069c2712018-03-29 19:09:14 -070011202
Andy Hung4b17e882023-07-07 13:47:37 -070011203void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011204{
11205 bool changed = false;
11206 bool silenced = false;
11207
11208 sp<MmapStreamCallback> callback = mCallback.promote();
11209 if (callback == 0) {
11210 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11211 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11212 mNoCallbackWarningCount++;
11213 }
11214 }
11215
11216 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11217 // track is silenced and unmute otherwise
11218 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11219 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11220 changed = true;
11221 silenced = mActiveTracks[i]->isSilenced_l();
11222 }
11223 }
11224
11225 if (changed) {
11226 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11227 }
11228}
11229
Andy Hung4b17e882023-07-07 13:47:37 -070011230ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011231{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011232 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011233 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011234 }
11235 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011236 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011237 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011238 record_track_metadata_v7_t trackMetadata;
11239 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011240 .source = track->attributes().source,
11241 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011242 };
11243 trackMetadata.channel_mask = track->channelMask(),
11244 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11245 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011246 }
11247 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011248 MetadataUpdate change;
11249 change.recordMetadataUpdate = metadata.tracks;
11250 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011251}
11252
Andy Hung4b17e882023-07-07 13:47:37 -070011253void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011254{
Andy Hungf8635b62023-08-31 16:13:39 -070011255 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011256 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011257 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011258 mActiveTracks[i]->setSilenced_l(silenced);
11259 broadcast_l();
11260 }
11261 }
jiabin09609032022-06-15 19:26:01 +000011262 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011263}
11264
Andy Hung4b17e882023-07-07 13:47:37 -070011265void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011266{
11267 MmapThread::toAudioPortConfig(config);
11268 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11269 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11270 config->flags.input = mInput->flags;
11271 }
11272}
11273
Andy Hung4b17e882023-07-07 13:47:37 -070011274status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011275 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011276{
11277 if (mInput == nullptr) {
11278 return NO_INIT;
11279 }
11280 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11281}
11282
jiabinc658e452022-10-21 20:52:21 +000011283// ----------------------------------------------------------------------------
11284
Andy Hung4b17e882023-07-07 13:47:37 -070011285/* static */
11286sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011287 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011288 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011289 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011290}
11291
Andy Hung7535ed92023-07-17 17:05:00 -070011292BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011293 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011294 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011295
Andy Hung4b17e882023-07-07 13:47:37 -070011296PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011297 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011298 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11299 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011300 float volumeLeft = 1.0f;
11301 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011302 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11303 const int trackId = mActiveTracks[0]->id();
11304 mAudioMixer->setParameter(
11305 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11306 mAudioMixer->setParameter(
11307 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11308 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011309 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011310 mIsBitPerfect = true;
11311 } else {
11312 mIsBitPerfect = false;
11313 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11314 // active.
11315 for (const auto& track : mActiveTracks) {
11316 const int trackId = track->id();
11317 mAudioMixer->setParameter(
11318 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11319 }
11320 }
jiabin76d94692022-12-15 21:51:21 +000011321 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11322 mVolumeLeft = volumeLeft;
11323 mVolumeRight = volumeRight;
11324 setVolumeForOutput_l(volumeLeft, volumeRight);
11325 }
jiabinc658e452022-10-21 20:52:21 +000011326 return result;
11327}
11328
Andy Hung4b17e882023-07-07 13:47:37 -070011329void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011330 MixerThread::threadLoop_mix();
11331 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11332}
11333
Glenn Kasten63238ef2015-03-02 15:50:29 -080011334} // namespace android