blob: 5e3c9ea2fa28d29e219223d491edd7d0ccf96959 [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>
Eric Laurent4eb45d02023-12-20 12:07:17 +010050#include <com_android_media_audio.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070051#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080052#include <cutils/properties.h>
Andy Hung409572b2023-07-19 12:47:35 -070053#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070054#include <media/AudioContainers.h>
55#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070056#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070057#include <media/AudioResamplerPublic.h>
Andy Hung409572b2023-07-19 12:47:35 -070058#ifdef ADD_BATTERY_DATA
59#include <media/IMediaPlayerService.h>
60#include <media/IMediaDeathNotifier.h>
61#endif
62#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080063#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070064#include <media/TypeConverter.h>
Andy Hung409572b2023-07-19 12:47:35 -070065#include <media/audiohal/EffectsFactoryHalInterface.h>
66#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070067#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068#include <media/nbaio/AudioStreamOutSink.h>
69#include <media/nbaio/MonoPipe.h>
70#include <media/nbaio/MonoPipeReader.h>
71#include <media/nbaio/Pipe.h>
72#include <media/nbaio/PipeReader.h>
73#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080074#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070075#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070076#include <mediautils/SchedulingPolicyService.h>
77#include <mediautils/ServiceUtilities.h>
Andy Hung409572b2023-07-19 12:47:35 -070078#include <powermanager/PowerManager.h>
79#include <private/android_filesystem_config.h>
80#include <private/media/AudioTrackShared.h>
81#include <system/audio_effects/effect_aec.h>
82#include <system/audio_effects/effect_downmix.h>
83#include <system/audio_effects/effect_ns.h>
84#include <system/audio_effects/effect_spatializer.h>
85#include <utils/Log.h>
86#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080087
Andy Hung409572b2023-07-19 12:47:35 -070088#include <fcntl.h>
89#include <linux/futex.h>
90#include <math.h>
91#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080092#include <pthread.h>
Andy Hung409572b2023-07-19 12:47:35 -070093#include <sstream>
94#include <string>
95#include <sys/stat.h>
96#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080097
Eric Laurent81784c32012-11-19 14:55:58 -080098// ----------------------------------------------------------------------------
99
100// Note: the following macro is used for extremely verbose logging message. In
101// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
102// 0; but one side effect of this is to turn all LOGV's as well. Some messages
103// are so verbose that we want to suppress them even when we have ALOG_ASSERT
104// turned on. Do not uncomment the #def below unless you really know what you
105// are doing and want to see all of the extremely verbose messages.
106//#define VERY_VERY_VERBOSE_LOGGING
107#ifdef VERY_VERY_VERBOSE_LOGGING
108#define ALOGVV ALOGV
109#else
110#define ALOGVV(a...) do { } while(0)
111#endif
112
Andy Hung6770c6f2015-04-07 13:43:36 -0700113// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700114#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116template <typename T>
117static inline T min(const T& a, const T& b)
118{
119 return a < b ? a : b;
120}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700121
Eric Laurent81784c32012-11-19 14:55:58 -0800122namespace android {
123
Andy Hung4b17e882023-07-07 13:47:37 -0700124using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700125using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000126using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700127
Andy Hung409572b2023-07-19 12:47:35 -0700128// Keep in sync with java definition in media/java/android/media/AudioRecord.java
129static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
130
Eric Laurent81784c32012-11-19 14:55:58 -0800131// retry counts for buffer fill timeout
132// 50 * ~20msecs = 1 second
133static const int8_t kMaxTrackRetries = 50;
134static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700135
Eric Laurent81784c32012-11-19 14:55:58 -0800136// allow less retry attempts on direct output thread.
137// direct outputs can be a scarce resource in audio hardware and should
138// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700139// Notes:
140// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
141// in case the data write is bursty for the AudioTrack. The application
142// should endeavor to write at least once every kMaxTrackRetriesDirectMs
143// to prevent an underrun situation. If the data is bursty, then
144// the application can also throttle the data sent to be even.
145// 2) For compressed audio data, any data present in the AudioTrack buffer
146// will be sent and reset the retry count. This delivers data as
147// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
148// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
149// of data to be available, then any remaining data is delivered.
150// This is required to ensure the last bit of data is delivered before underrun.
151//
152// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
153// or the size of the HAL period for proportional / linear PCM tracks.
154static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800155
156// don't warn about blocked writes or record buffer overflows more often than this
157static const nsecs_t kWarningThrottleNs = seconds(5);
158
159// RecordThread loop sleep time upon application overrun or audio HAL read error
160static const int kRecordThreadSleepUs = 5000;
161
Eric Laurent10351942014-05-08 18:49:52 -0700162// maximum time to wait in sendConfigEvent_l() for a status to be received
163static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800164
165// minimum sleep time for the mixer thread loop when tracks are active but in underrun
166static const uint32_t kMinThreadSleepTimeUs = 5000;
167// maximum divider applied to the active sleep time in the mixer thread loop
168static const uint32_t kMaxThreadSleepTimeShift = 2;
169
Andy Hung09a50072014-02-27 14:30:47 -0800170// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700171// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800172static const uint32_t kMinNormalSinkBufferSizeMs = 20;
173// maximum normal sink buffer size
174static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800175
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700176// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
177// FIXME This should be based on experimentally observed scheduling jitter
178static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
179
Eric Laurent972a1732013-09-04 09:42:59 -0700180// Offloaded output thread standby delay: allows track transition without going to standby
181static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
182
Eric Laurent51716182016-02-29 18:00:56 -0800183// Direct output thread minimum sleep time in idle or active(underrun) state
184static const nsecs_t kDirectMinSleepTimeUs = 10000;
185
Brian Lindahl65e90012022-07-27 18:01:07 +0200186// Minimum amount of time between checking to see if the timestamp is advancing
187// for underrun detection. If we check too frequently, we may not detect a
188// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800189static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200190
Glenn Kasten1b291842016-07-18 14:55:21 -0700191// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
192// balance between power consumption and latency, and allows threads to be scheduled reliably
193// by the CFS scheduler.
194// FIXME Express other hardcoded references to 20ms with references to this constant and move
195// it appropriately.
196#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800197
Eric Laurent81784c32012-11-19 14:55:58 -0800198// Whether to use fast mixer
199static const enum {
200 FastMixer_Never, // never initialize or use: for debugging only
201 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
202 // normal mixer multiplier is 1
203 FastMixer_Static, // initialize if needed, then use all the time if initialized,
204 // multiplier is calculated based on min & max normal mixer buffer size
205 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
206 // multiplier is calculated based on min & max normal mixer buffer size
207 // FIXME for FastMixer_Dynamic:
208 // Supporting this option will require fixing HALs that can't handle large writes.
209 // For example, one HAL implementation returns an error from a large write,
210 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
211 // We could either fix the HAL implementations, or provide a wrapper that breaks
212 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
213} kUseFastMixer = FastMixer_Static;
214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700215// Whether to use fast capture
216static const enum {
217 FastCapture_Never, // never initialize or use: for debugging only
218 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
219 FastCapture_Static, // initialize if needed, then use all the time if initialized
220} kUseFastCapture = FastCapture_Static;
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222// Priorities for requestPriority
223static const int kPriorityAudioApp = 2;
224static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700225static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000226// Request real-time priority for PlaybackThread in ARC
227static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800228
Glenn Kastenea38ee72016-04-18 11:08:01 -0700229// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
230// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
231// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700232
233// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800234static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800235
Glenn Kasten03490092014-05-27 12:30:54 -0700236// The minimum and maximum allowed values
237static const int kFastTrackMultiplierMin = 1;
238static const int kFastTrackMultiplierMax = 2;
239
240// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
241static int sFastTrackMultiplier = kFastTrackMultiplier;
242
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700243// See Thread::readOnlyHeap().
244// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
245// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
246// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700247static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700248
Andy Hung409572b2023-07-19 12:47:35 -0700249static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hungd58c4732023-07-20 21:31:38 -0700250
251static nsecs_t getStandbyTimeInNanos() {
252 static nsecs_t standbyTimeInNanos = []() {
253 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
254 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
255 ALOGI("%s: Using %d ms as standby time", __func__, ms);
256 return milliseconds(ms);
257 }();
258 return standbyTimeInNanos;
259}
260
Andy Hungd21a2ab2023-07-20 21:44:14 -0700261// Set kEnableExtendedChannels to true to enable greater than stereo output
262// for the MixerThread and device sink. Number of channels allowed is
263// FCC_2 <= channels <= FCC_LIMIT.
264constexpr bool kEnableExtendedChannels = true;
265
266// Returns true if channel mask is permitted for the PCM sink in the MixerThread
267/* static */
268bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
269 switch (audio_channel_mask_get_representation(channelMask)) {
270 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
271 // Haptic channel mask is only applicable for channel position mask.
272 const uint32_t channelCount = audio_channel_count_from_out_mask(
273 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
274 const uint32_t maxChannelCount = kEnableExtendedChannels
275 ? FCC_LIMIT : FCC_2;
276 if (channelCount < FCC_2 // mono is not supported at this time
277 || channelCount > maxChannelCount) {
278 return false;
279 }
280 // check that channelMask is the "canonical" one we expect for the channelCount.
281 return audio_channel_position_mask_is_out_canonical(channelMask);
282 }
283 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
284 if (kEnableExtendedChannels) {
285 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
286 if (channelCount >= FCC_2 // mono is not supported at this time
287 && channelCount <= FCC_LIMIT) {
288 return true;
289 }
290 }
291 return false;
292 default:
293 return false;
294 }
295}
296
297// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
298constexpr bool kEnableExtendedPrecision = true;
299
300// Returns true if format is permitted for the PCM sink in the MixerThread
301/* static */
302bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
303 switch (format) {
304 case AUDIO_FORMAT_PCM_16_BIT:
305 return true;
306 case AUDIO_FORMAT_PCM_FLOAT:
307 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
308 case AUDIO_FORMAT_PCM_32_BIT:
309 case AUDIO_FORMAT_PCM_8_24_BIT:
310 return kEnableExtendedPrecision;
311 default:
312 return false;
313 }
314}
315
Eric Laurent81784c32012-11-19 14:55:58 -0800316// ----------------------------------------------------------------------------
317
Andy Hung409572b2023-07-19 12:47:35 -0700318// formatToString() needs to be exact for MediaMetrics purposes.
319// Do not use media/TypeConverter.h toString().
320/* static */
321std::string IAfThreadBase::formatToString(audio_format_t format) {
322 std::string result;
323 FormatConverter::toString(format, result);
324 return result;
325}
326
Andy Hungb68f5eb2019-12-03 16:49:17 -0800327// TODO: move all toString helpers to audio.h
328// under #ifdef __cplusplus #endif
329static std::string patchSinksToString(const struct audio_patch *patch)
330{
331 std::stringstream ss;
332 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700333 if (i > 0) {
334 ss << "|";
335 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800336 ss << "(" << toString(patch->sinks[i].ext.device.type)
337 << ", " << patch->sinks[i].ext.device.address << ")";
338 }
339 return ss.str();
340}
341
342static std::string patchSourcesToString(const struct audio_patch *patch)
343{
344 std::stringstream ss;
345 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700346 if (i > 0) {
347 ss << "|";
348 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800349 ss << "(" << toString(patch->sources[i].ext.device.type)
350 << ", " << patch->sources[i].ext.device.address << ")";
351 }
352 return ss.str();
353}
354
Andy Hung4bd53e72022-11-17 17:21:45 -0800355static std::string toString(audio_latency_mode_t mode) {
356 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000357 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
358 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800359}
360
361// Could be made a template, but other toString overloads for std::vector are confused.
362static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
363 std::string s("{ ");
364 for (const auto& e : elements) {
365 s.append(toString(e));
366 s.append(" ");
367 }
368 s.append("}");
369 return s;
370}
371
Glenn Kasten03490092014-05-27 12:30:54 -0700372static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
373
374static void sFastTrackMultiplierInit()
375{
376 char value[PROPERTY_VALUE_MAX];
377 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
378 char *endptr;
379 unsigned long ul = strtoul(value, &endptr, 0);
380 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
381 sFastTrackMultiplier = (int) ul;
382 }
383 }
384}
385
386// ----------------------------------------------------------------------------
387
Eric Laurent81784c32012-11-19 14:55:58 -0800388#ifdef ADD_BATTERY_DATA
389// To collect the amplifier usage
390static void addBatteryData(uint32_t params) {
391 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
392 if (service == NULL) {
393 // it already logged
394 return;
395 }
396
397 service->addBatteryData(params);
398}
399#endif
400
Andy Hung3f0c9022016-01-15 17:49:46 -0800401// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
402struct {
403 // call when you acquire a partial wakelock
404 void acquire(const sp<IBinder> &wakeLockToken) {
405 pthread_mutex_lock(&mLock);
406 if (wakeLockToken.get() == nullptr) {
407 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
408 } else {
409 if (mCount == 0) {
410 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
411 }
412 ++mCount;
413 }
414 pthread_mutex_unlock(&mLock);
415 }
416
417 // call when you release a partial wakelock.
418 void release(const sp<IBinder> &wakeLockToken) {
419 if (wakeLockToken.get() == nullptr) {
420 return;
421 }
422 pthread_mutex_lock(&mLock);
423 if (--mCount < 0) {
424 ALOGE("negative wakelock count");
425 mCount = 0;
426 }
427 pthread_mutex_unlock(&mLock);
428 }
429
430 // retrieves the boottime timebase offset from monotonic.
431 int64_t getBoottimeOffset() {
432 pthread_mutex_lock(&mLock);
433 int64_t boottimeOffset = mBoottimeOffset;
434 pthread_mutex_unlock(&mLock);
435 return boottimeOffset;
436 }
437
438 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
439 // and the selected timebase.
440 // Currently only TIMEBASE_BOOTTIME is allowed.
441 //
442 // This only needs to be called upon acquiring the first partial wakelock
443 // after all other partial wakelocks are released.
444 //
445 // We do an empirical measurement of the offset rather than parsing
446 // /proc/timer_list since the latter is not a formal kernel ABI.
447 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
448 int clockbase;
449 switch (timebase) {
450 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
451 clockbase = SYSTEM_TIME_BOOTTIME;
452 break;
453 default:
454 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
455 break;
456 }
457 // try three times to get the clock offset, choose the one
458 // with the minimum gap in measurements.
459 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700460 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800461 for (int i = 0; i < tries; ++i) {
462 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
463 const nsecs_t tbase = systemTime(clockbase);
464 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
465 const nsecs_t gap = tmono2 - tmono;
466 if (i == 0 || gap < bestGap) {
467 bestGap = gap;
468 measured = tbase - ((tmono + tmono2) >> 1);
469 }
470 }
471
472 // to avoid micro-adjusting, we don't change the timebase
473 // unless it is significantly different.
474 //
475 // Assumption: It probably takes more than toleranceNs to
476 // suspend and resume the device.
477 static int64_t toleranceNs = 10000; // 10 us
478 if (llabs(*offset - measured) > toleranceNs) {
479 ALOGV("Adjusting timebase offset old: %lld new: %lld",
480 (long long)*offset, (long long)measured);
481 *offset = measured;
482 }
483 }
484
485 pthread_mutex_t mLock;
486 int32_t mCount;
487 int64_t mBoottimeOffset;
488} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800489
490// ----------------------------------------------------------------------------
491// CPU Stats
492// ----------------------------------------------------------------------------
493
494class CpuStats {
495public:
496 CpuStats();
497 void sample(const String8 &title);
498#ifdef DEBUG_CPU_USAGE
499private:
500 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700501 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800502
Andy Hung16698b82018-08-01 10:48:38 -0700503 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800504
505 int mCpuNum; // thread's current CPU number
506 int mCpukHz; // frequency of thread's current CPU in kHz
507#endif
508};
509
510CpuStats::CpuStats()
511#ifdef DEBUG_CPU_USAGE
512 : mCpuNum(-1), mCpukHz(-1)
513#endif
514{
515}
516
Glenn Kasten0f11b512014-01-31 16:18:54 -0800517void CpuStats::sample(const String8 &title
518#ifndef DEBUG_CPU_USAGE
519 __unused
520#endif
521 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800522#ifdef DEBUG_CPU_USAGE
523 // get current thread's delta CPU time in wall clock ns
524 double wcNs;
525 bool valid = mCpuUsage.sampleAndEnable(wcNs);
526
527 // record sample for wall clock statistics
528 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700529 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800530 }
531
532 // get the current CPU number
533 int cpuNum = sched_getcpu();
534
535 // get the current CPU frequency in kHz
536 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
537
538 // check if either CPU number or frequency changed
539 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
540 mCpuNum = cpuNum;
541 mCpukHz = cpukHz;
542 // ignore sample for purposes of cycles
543 valid = false;
544 }
545
546 // if no change in CPU number or frequency, then record sample for cycle statistics
547 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700548 const double cycles = wcNs * cpukHz * 0.000001;
549 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800550 }
551
Eric Tan5b13ff82018-07-27 11:20:17 -0700552 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800553 // mCpuUsage.elapsed() is expensive, so don't call it every loop
554 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700555 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800556 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700557 const double perLoop = elapsed / (double) n;
558 const double perLoop100 = perLoop * 0.01;
559 const double perLoop1k = perLoop * 0.001;
560 const double mean = mWcStats.getMean();
561 const double stddev = mWcStats.getStdDev();
562 const double minimum = mWcStats.getMin();
563 const double maximum = mWcStats.getMax();
564 const double meanCycles = mHzStats.getMean();
565 const double stddevCycles = mHzStats.getStdDev();
566 const double minCycles = mHzStats.getMin();
567 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800568 mCpuUsage.resetElapsed();
569 mWcStats.reset();
570 mHzStats.reset();
571 ALOGD("CPU usage for %s over past %.1f secs\n"
572 " (%u mixer loops at %.1f mean ms per loop):\n"
573 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
574 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
575 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000576 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800577 elapsed * .000000001, n, perLoop * .000001,
578 mean * .001,
579 stddev * .001,
580 minimum * .001,
581 maximum * .001,
582 mean / perLoop100,
583 stddev / perLoop100,
584 minimum / perLoop100,
585 maximum / perLoop100,
586 meanCycles / perLoop1k,
587 stddevCycles / perLoop1k,
588 minCycles / perLoop1k,
589 maxCycles / perLoop1k);
590
591 }
592 }
593#endif
594};
595
596// ----------------------------------------------------------------------------
597// ThreadBase
598// ----------------------------------------------------------------------------
599
Glenn Kasten97b7b752014-09-28 13:04:24 -0700600// static
Andy Hung4b17e882023-07-07 13:47:37 -0700601const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700602{
603 switch (type) {
604 case MIXER:
605 return "MIXER";
606 case DIRECT:
607 return "DIRECT";
608 case DUPLICATING:
609 return "DUPLICATING";
610 case RECORD:
611 return "RECORD";
612 case OFFLOAD:
613 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700614 case MMAP_PLAYBACK:
615 return "MMAP_PLAYBACK";
616 case MMAP_CAPTURE:
617 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200618 case SPATIALIZER:
619 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000620 case BIT_PERFECT:
621 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700622 default:
623 return "unknown";
624 }
625}
626
Andy Hung7535ed92023-07-17 17:05:00 -0700627ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700628 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800629 : Thread(false /*canCallJava*/),
630 mType(type),
Andy Hung7535ed92023-07-17 17:05:00 -0700631 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700632 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
633 isOut),
634 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700635 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800636 // are set by PlaybackThread::readOutputParameters_l() or
637 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700638 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700639 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700640 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800641 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700642 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800643 mSystemReady(systemReady),
644 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
Andy Hungcf10d742020-04-28 15:38:24 -0700646 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700647 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800648}
649
Andy Hung4b17e882023-07-07 13:47:37 -0700650ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800651{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700652 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700653 mConfigEvents.clear();
654
Eric Laurent81784c32012-11-19 14:55:58 -0800655 // do not lock the mutex in destructor
656 releaseWakeLock_l();
657 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800658 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800659 binder->unlinkToDeath(mDeathRecipient);
660 }
Andy Hungd0979812019-02-21 15:51:44 -0800661
662 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800663}
664
Andy Hung4b17e882023-07-07 13:47:37 -0700665status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700666{
667 status_t status = initCheck();
668 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800669 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700670 } else {
671 ALOGE("No working audio driver found.");
672 }
673 return status;
674}
675
Andy Hung4b17e882023-07-07 13:47:37 -0700676void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800677{
678 ALOGV("ThreadBase::exit");
679 // do any cleanup required for exit to succeed
680 preExit();
681 {
682 // This lock prevents the following race in thread (uniprocessor for illustration):
683 // if (!exitPending()) {
684 // // context switch from here to exit()
685 // // exit() calls requestExit(), what exitPending() observes
686 // // exit() calls signal(), which is dropped since no waiters
687 // // context switch back from exit() to here
688 // mWaitWorkCV.wait(...);
689 // // now thread is hung
690 // }
Andy Hungb17d24b2023-08-29 14:26:09 -0700691 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800692 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -0700693 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800694 }
695 // When Thread::requestExitAndWait is made virtual and this method is renamed to
696 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hungef2096d2024-03-21 19:43:05 -0700697
698 // For TimeCheck: track waiting on the thread join of getTid().
699 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
700
Eric Laurent81784c32012-11-19 14:55:58 -0800701 requestExitAndWait();
702}
703
Andy Hung4b17e882023-07-07 13:47:37 -0700704status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800705{
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000706 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hungf8635b62023-08-31 16:13:39 -0700707 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800708
Eric Laurent10351942014-05-08 18:49:52 -0700709 return sendSetParameterConfigEvent_l(keyValuePairs);
710}
711
712// sendConfigEvent_l() must be called with ThreadBase::mLock held
713// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung4b17e882023-07-07 13:47:37 -0700714status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700715NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700716{
717 status_t status = NO_ERROR;
718
Eric Laurent72e3f392015-05-20 14:43:50 -0700719 if (event->mRequiresSystemReady && !mSystemReady) {
720 event->mWaitStatus = false;
721 mPendingConfigEvents.add(event);
722 return status;
723 }
Eric Laurent10351942014-05-08 18:49:52 -0700724 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700725 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungb17d24b2023-08-29 14:26:09 -0700726 mWaitWorkCV.notify_one();
727 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700728 {
Andy Hungb17d24b2023-08-29 14:26:09 -0700729 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700730 while (event->mWaitStatus) {
Andy Hung5529c132024-01-25 17:02:30 -0800731 if (event->mCondition.wait_for(
732 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
733 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700734 event->mStatus = TIMED_OUT;
735 event->mWaitStatus = false;
736 }
737 }
738 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800739 }
Andy Hungb17d24b2023-08-29 14:26:09 -0700740 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800741 return status;
742}
743
Andy Hung4b17e882023-07-07 13:47:37 -0700744void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700745 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800746{
Andy Hungf8635b62023-08-31 16:13:39 -0700747 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700748 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800749}
750
Andy Hungb17d24b2023-08-29 14:26:09 -0700751// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700752void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700753 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800754{
Andy Hungd0979812019-02-21 15:51:44 -0800755 // The audio statistics history is exponentially weighted to forget events
756 // about five or more seconds in the past. In order to have
757 // crisper statistics for mediametrics, we reset the statistics on
758 // an IoConfigEvent, to reflect different properties for a new device.
759 mIoJitterMs.reset();
760 mLatencyMs.reset();
761 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000762 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100763 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800764
Eric Laurent09f1ed22019-04-24 17:45:17 -0700765 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700766 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800767}
768
Andy Hung4b17e882023-07-07 13:47:37 -0700769void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700770{
Andy Hungf8635b62023-08-31 16:13:39 -0700771 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800772 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700773}
774
Andy Hungb17d24b2023-08-29 14:26:09 -0700775// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700776void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800777 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800778{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800779 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700780 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800781}
782
Andy Hungb17d24b2023-08-29 14:26:09 -0700783// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700784status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800785{
Andy Hung2ddee192015-12-18 17:34:44 -0800786 sp<ConfigEvent> configEvent;
787 AudioParameter param(keyValuePair);
788 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700789 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800790 setMasterMono_l(value != 0);
791 if (param.size() == 1) {
792 return NO_ERROR; // should be a solo parameter - we don't pass down
793 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700794 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800795 configEvent = new SetParameterConfigEvent(param.toString());
796 } else {
797 configEvent = new SetParameterConfigEvent(keyValuePair);
798 }
Eric Laurent10351942014-05-08 18:49:52 -0700799 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700800}
801
Andy Hung4b17e882023-07-07 13:47:37 -0700802status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700803 const struct audio_patch *patch,
804 audio_patch_handle_t *handle)
805{
Andy Hungf8635b62023-08-31 16:13:39 -0700806 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700807 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
808 status_t status = sendConfigEvent_l(configEvent);
809 if (status == NO_ERROR) {
810 CreateAudioPatchConfigEventData *data =
811 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
812 *handle = data->mHandle;
813 }
814 return status;
815}
816
Andy Hung4b17e882023-07-07 13:47:37 -0700817status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700818 const audio_patch_handle_t handle)
819{
Andy Hungf8635b62023-08-31 16:13:39 -0700820 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700821 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
822 return sendConfigEvent_l(configEvent);
823}
824
Andy Hung4b17e882023-07-07 13:47:37 -0700825status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700826 const DeviceDescriptorBaseVector& outDevices)
827{
828 if (type() != RECORD) {
829 // The update out device operation is only for record thread.
830 return INVALID_OPERATION;
831 }
Andy Hungf8635b62023-08-31 16:13:39 -0700832 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700833 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
834 return sendConfigEvent_l(configEvent);
835}
836
Andy Hung4b17e882023-07-07 13:47:37 -0700837void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200838{
839 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
840 sp<ConfigEvent> configEvent =
841 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
842 sendConfigEvent_l(configEvent);
843}
Eric Laurent1c333e22014-05-20 10:48:17 -0700844
Andy Hung4b17e882023-07-07 13:47:37 -0700845void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200846{
Andy Hungf8635b62023-08-31 16:13:39 -0700847 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200848 sendCheckOutputStageEffectsEvent_l();
849}
850
Andy Hung4b17e882023-07-07 13:47:37 -0700851void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200852{
853 sp<ConfigEvent> configEvent =
854 (ConfigEvent *)new CheckOutputStageEffectsEvent();
855 sendConfigEvent_l(configEvent);
856}
857
Andy Hung4b17e882023-07-07 13:47:37 -0700858void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200859{
860 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
861 sendConfigEvent_l(configEvent);
862}
863
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700864// post condition: mConfigEvents.isEmpty()
Andy Hung4b17e882023-07-07 13:47:37 -0700865void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700866{
Eric Laurent10351942014-05-08 18:49:52 -0700867 bool configChanged = false;
868
Eric Laurent81784c32012-11-19 14:55:58 -0800869 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700870 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700871 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800872 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700873 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700874 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700875 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
876 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800877 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700878 true /*asynchronous*/);
879 if (err != 0) {
880 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700881 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700882 }
883 } break;
884 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700885 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hung94dfbb42023-09-06 19:41:47 -0700886 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700887 } break;
888 case CFG_EVENT_SET_PARAMETER: {
889 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
890 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
891 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700892 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000893 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700894 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700895 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700896 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700897 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700898 CreateAudioPatchConfigEventData *data =
899 (CreateAudioPatchConfigEventData *)event->mData.get();
900 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700901 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200902 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700903 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
904 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
905 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700906 } break;
907 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700908 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700909 ReleaseAudioPatchConfigEventData *data =
910 (ReleaseAudioPatchConfigEventData *)event->mData.get();
911 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700912 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200913 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700914 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
915 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
916 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
917 } break;
918 case CFG_EVENT_UPDATE_OUT_DEVICE: {
919 UpdateOutDevicesConfigEventData *data =
920 (UpdateOutDevicesConfigEventData *)event->mData.get();
921 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700922 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200923 case CFG_EVENT_RESIZE_BUFFER: {
924 ResizeBufferConfigEventData *data =
925 (ResizeBufferConfigEventData *)event->mData.get();
926 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
927 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200928
929 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
930 setCheckOutputStageEffects();
931 } break;
932
Eric Laurent68a40a82022-05-03 18:15:04 +0200933 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
934 onHalLatencyModesChanged_l();
935 } break;
936
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700937 default:
Eric Laurent10351942014-05-08 18:49:52 -0700938 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700939 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800940 }
Eric Laurent10351942014-05-08 18:49:52 -0700941 {
Andy Hungf8635b62023-08-31 16:13:39 -0700942 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700943 if (event->mWaitStatus) {
944 event->mWaitStatus = false;
Andy Hungb17d24b2023-08-29 14:26:09 -0700945 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700946 }
947 }
948 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
949 }
950
951 if (configChanged) {
952 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800953 }
Eric Laurent81784c32012-11-19 14:55:58 -0800954}
955
Marco Nelissenb2208842014-02-07 14:00:50 -0800956String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
957 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700958 const audio_channel_representation_t representation =
959 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700960
961 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800962 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700963 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
964 if (output) {
965 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
966 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
967 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700968 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700969 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
971 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
972 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
973 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
974 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
975 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
978 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
979 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
980 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700981 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
982 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
983 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
984 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
985 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
986 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
987 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700988 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700989 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
990 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700991 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
992 } else {
993 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
994 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
995 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
996 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
997 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
998 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
999 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1000 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1001 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1002 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1003 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1004 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001005 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1006 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1007 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001008 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001009 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1010 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001011 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1012 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1013 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1014 }
1015 const int len = s.length();
1016 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001017 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001018 s.unlockBuffer(len - 2); // remove trailing ", "
1019 }
1020 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001021 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001022 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1023 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1024 return s;
1025 default:
1026 s.appendFormat("unknown mask, representation:%d bits:%#x",
1027 representation, audio_channel_mask_get_bits(mask));
1028 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001029 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001030}
1031
Andy Hung4b17e882023-07-07 13:47:37 -07001032void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001033NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001034{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001035 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1036 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1037
Andy Hungb17d24b2023-08-29 14:26:09 -07001038 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001039 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001040 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001041 }
1042
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001043 dumpBase_l(fd, args);
1044 dumpInternals_l(fd, args);
1045 dumpTracks_l(fd, args);
1046 dumpEffectChains_l(fd, args);
1047
1048 if (locked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001049 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001050 }
1051
1052 dprintf(fd, " Local log:\n");
1053 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001054
1055 // --all does the statistics
1056 bool dumpAll = false;
1057 for (const auto &arg : args) {
1058 if (arg == String16("--all")) {
1059 dumpAll = true;
1060 }
1061 }
1062 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001063 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001064 if (!sched.empty()) {
1065 (void)write(fd, sched.c_str(), sched.size());
1066 }
1067 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001068}
1069
Andy Hung4b17e882023-07-07 13:47:37 -07001070void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001071{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001072 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001073 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001074 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001075 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung409572b2023-07-19 12:47:35 -07001076 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1077 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001078 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001079 dprintf(fd, " Channel count: %u\n", mChannelCount);
1080 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001081 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung409572b2023-07-19 12:47:35 -07001082 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1083 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001084 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001085 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001086 size_t numConfig = mConfigEvents.size();
1087 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001088 const size_t SIZE = 256;
1089 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001090 for (size_t i = 0; i < numConfig; i++) {
1091 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001092 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001093 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001094 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001095 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001096 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001097 }
Andy Hung293558a2017-03-21 12:19:20 -07001098 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001099 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001100 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001101 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001102 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001103 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001104
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001105 // Dump timestamp statistics for the Thread types that support it.
1106 if (mType == RECORD
1107 || mType == MIXER
1108 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001109 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001110 || mType == OFFLOAD
1111 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001112 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hung94dfbb42023-09-06 19:41:47 -07001113 dprintf(fd, " Timestamp corrected: %s\n",
1114 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001115 }
1116
Andy Hung446f4df2019-02-21 12:26:41 -08001117 if (mLastIoBeginNs > 0) { // MMAP may not set this
1118 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1119 isOutput() ? "write" : "read",
1120 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1121 }
1122
1123 if (mProcessTimeMs.getN() > 0) {
1124 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1125 }
1126
1127 if (mIoJitterMs.getN() > 0) {
1128 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1129 isOutput() ? "write" : "read",
1130 mIoJitterMs.toString().c_str());
1131 }
1132
Andy Hunge6c37112019-02-26 17:38:10 -08001133 if (mLatencyMs.getN() > 0) {
1134 dprintf(fd, " Threadloop %s latency stats: %s\n",
1135 isOutput() ? "write" : "read",
1136 mLatencyMs.toString().c_str());
1137 }
Robert Wu06db0a32021-08-10 19:05:34 +00001138
1139 if (mMonopipePipeDepthStats.getN() > 0) {
1140 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1141 isOutput() ? "write" : "read",
1142 mMonopipePipeDepthStats.toString().c_str());
1143 }
Eric Laurent81784c32012-11-19 14:55:58 -08001144}
1145
Andy Hung4b17e882023-07-07 13:47:37 -07001146void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001147{
1148 const size_t SIZE = 256;
1149 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001150
Marco Nelissenb2208842014-02-07 14:00:50 -08001151 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001152 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001153 write(fd, buffer, strlen(buffer));
1154
Marco Nelissenb2208842014-02-07 14:00:50 -08001155 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001156 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001157 if (chain != 0) {
1158 chain->dump(fd, args);
1159 }
1160 }
1161}
1162
Andy Hung4b17e882023-07-07 13:47:37 -07001163void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001164{
Andy Hungf8635b62023-08-31 16:13:39 -07001165 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001166 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001167}
1168
Andy Hung4b17e882023-07-07 13:47:37 -07001169String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001170{
1171 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001172 case MIXER:
1173 return String16("AudioMix");
1174 case DIRECT:
1175 return String16("AudioDirectOut");
1176 case DUPLICATING:
1177 return String16("AudioDup");
1178 case RECORD:
1179 return String16("AudioIn");
1180 case OFFLOAD:
1181 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001182 case MMAP_PLAYBACK:
1183 return String16("MmapPlayback");
1184 case MMAP_CAPTURE:
1185 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001186 case SPATIALIZER:
1187 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001188 default:
1189 ALOG_ASSERT(false);
1190 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001191 }
1192}
1193
Andy Hung4b17e882023-07-07 13:47:37 -07001194void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001195{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001196 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001197 if (mPowerManager != 0) {
1198 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001199 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001200 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1201 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001202 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001203 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001204 {} /* workSource */,
1205 {} /* historyTag */);
1206 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001207 mWakeLockToken = binder;
1208 }
Chris Ye6597d732020-02-28 22:38:25 -08001209 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001210 }
Wei Jia3f273d12015-11-24 09:06:49 -08001211
Andy Hung3f0c9022016-01-15 17:49:46 -08001212 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001213 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1214 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001215}
1216
Andy Hung4b17e882023-07-07 13:47:37 -07001217void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001218{
Andy Hungf8635b62023-08-31 16:13:39 -07001219 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001220 releaseWakeLock_l();
1221}
1222
Andy Hung4b17e882023-07-07 13:47:37 -07001223void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001224{
Andy Hung3f0c9022016-01-15 17:49:46 -08001225 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001226 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001227 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001228 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001229 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001230 }
1231 mWakeLockToken.clear();
1232 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001233}
1234
Andy Hung4b17e882023-07-07 13:47:37 -07001235void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001236 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001237 // use checkService() to avoid blocking if power service is not up yet
1238 sp<IBinder> binder =
1239 defaultServiceManager()->checkService(String16("power"));
1240 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001241 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001242 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001243 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001244 binder->linkToDeath(mDeathRecipient);
1245 }
1246 }
1247}
1248
Andy Hung4b17e882023-07-07 13:47:37 -07001249void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001250 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001251
1252#if !LOG_NDEBUG
1253 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001254 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001255 s << uid << " ";
1256 }
1257 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1258#endif
1259
Andy Hung438e7572015-12-14 15:51:17 -08001260 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1261 if (mSystemReady) {
1262 ALOGE("no wake lock to update, but system ready!");
1263 } else {
1264 ALOGW("no wake lock to update, system not ready yet");
1265 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001266 return;
1267 }
1268 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001269 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001270 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1271 mWakeLockToken, uidsAsInt);
1272 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001273 }
1274}
1275
Andy Hung4b17e882023-07-07 13:47:37 -07001276void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001277{
Andy Hungf8635b62023-08-31 16:13:39 -07001278 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001279 releaseWakeLock_l();
1280 mPowerManager.clear();
1281}
1282
Andy Hung4b17e882023-07-07 13:47:37 -07001283void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001284 const DeviceDescriptorBaseVector& outDevices __unused)
1285{
1286 ALOGE("%s should only be called in RecordThread", __func__);
1287}
1288
Andy Hung4b17e882023-07-07 13:47:37 -07001289void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001290{
1291 ALOGE("%s should only be called in RecordThread", __func__);
1292}
1293
Andy Hung4b17e882023-07-07 13:47:37 -07001294void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001295{
1296 sp<ThreadBase> thread = mThread.promote();
1297 if (thread != 0) {
1298 thread->clearPowerManager();
1299 }
1300 ALOGW("power manager service died !!!");
1301}
1302
Andy Hung4b17e882023-07-07 13:47:37 -07001303void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001304 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001305{
Andy Hung116bc262023-06-20 18:56:17 -07001306 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001307 if (chain != 0) {
1308 if (type != NULL) {
1309 chain->setEffectSuspended_l(type, suspend);
1310 } else {
1311 chain->setEffectSuspendedAll_l(suspend);
1312 }
1313 }
1314
1315 updateSuspendedSessions_l(type, suspend, sessionId);
1316}
1317
Andy Hung4b17e882023-07-07 13:47:37 -07001318void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001319{
1320 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1321 if (index < 0) {
1322 return;
1323 }
1324
1325 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1326 mSuspendedSessions.valueAt(index);
1327
1328 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001329 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001330 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001331 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001332 chain->setEffectSuspendedAll_l(true);
1333 } else {
1334 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1335 desc->mType.timeLow);
1336 chain->setEffectSuspended_l(&desc->mType, true);
1337 }
1338 }
1339 }
1340}
1341
Andy Hung4b17e882023-07-07 13:47:37 -07001342void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001343 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001344 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001345{
1346 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1347
1348 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1349
1350 if (suspend) {
1351 if (index >= 0) {
1352 sessionEffects = mSuspendedSessions.valueAt(index);
1353 } else {
1354 mSuspendedSessions.add(sessionId, sessionEffects);
1355 }
1356 } else {
1357 if (index < 0) {
1358 return;
1359 }
1360 sessionEffects = mSuspendedSessions.valueAt(index);
1361 }
1362
1363
Andy Hung116bc262023-06-20 18:56:17 -07001364 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001365 if (type != NULL) {
1366 key = type->timeLow;
1367 }
1368 index = sessionEffects.indexOfKey(key);
1369
1370 sp<SuspendedSessionDesc> desc;
1371 if (suspend) {
1372 if (index >= 0) {
1373 desc = sessionEffects.valueAt(index);
1374 } else {
1375 desc = new SuspendedSessionDesc();
1376 if (type != NULL) {
1377 desc->mType = *type;
1378 }
1379 sessionEffects.add(key, desc);
1380 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1381 }
1382 desc->mRefCount++;
1383 } else {
1384 if (index < 0) {
1385 return;
1386 }
1387 desc = sessionEffects.valueAt(index);
1388 if (--desc->mRefCount == 0) {
1389 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1390 sessionEffects.removeItemsAt(index);
1391 if (sessionEffects.isEmpty()) {
1392 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1393 sessionId);
1394 mSuspendedSessions.removeItem(sessionId);
1395 }
1396 }
1397 }
1398 if (!sessionEffects.isEmpty()) {
1399 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1400 }
1401}
1402
Andy Hung4b17e882023-07-07 13:47:37 -07001403void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001404 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001405 bool threadLocked)
1406NO_THREAD_SAFETY_ANALYSIS // manual locking
1407{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001408 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001409 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001410 }
Eric Laurent81784c32012-11-19 14:55:58 -08001411
Eric Laurent81784c32012-11-19 14:55:58 -08001412 if (mType != RECORD) {
1413 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1414 // another session. This gives the priority to well behaved effect control panels
1415 // and applications not using global effects.
1416 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1417 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001418 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001419 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1420 }
1421 }
1422
Eric Laurent6b446ce2019-12-13 10:56:31 -08001423 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001424 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001425 }
1426}
1427
Andy Hungb17d24b2023-08-29 14:26:09 -07001428// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001429status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001430 const effect_descriptor_t *desc, audio_session_t sessionId)
1431{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001432 // No global output effect sessions on record threads
1433 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1434 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001435 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1436 desc->name, mThreadName);
1437 return BAD_VALUE;
1438 }
1439 // only pre processing effects on record thread
1440 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1441 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1442 desc->name, mThreadName);
1443 return BAD_VALUE;
1444 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001445
1446 // always allow effects without processing load or latency
1447 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1448 return NO_ERROR;
1449 }
1450
Eric Laurent4c415062016-06-17 16:14:16 -07001451 audio_input_flags_t flags = mInput->flags;
1452 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1453 if (flags & AUDIO_INPUT_FLAG_RAW) {
1454 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1455 desc->name, mThreadName);
1456 return BAD_VALUE;
1457 }
1458 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1459 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1460 desc->name, mThreadName);
1461 return BAD_VALUE;
1462 }
1463 }
jiabineb3bda02020-06-30 14:07:03 -07001464
Andy Hung116bc262023-06-20 18:56:17 -07001465 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001466 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1467 return BAD_VALUE;
1468 }
Eric Laurent4c415062016-06-17 16:14:16 -07001469 return NO_ERROR;
1470}
1471
Andy Hungb17d24b2023-08-29 14:26:09 -07001472// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001473status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001474 const effect_descriptor_t *desc, audio_session_t sessionId)
1475{
1476 // no preprocessing on playback threads
1477 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001478 ALOGW("%s: pre processing effect %s created on playback"
1479 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001480 return BAD_VALUE;
1481 }
1482
Eric Laurent3e4de772017-07-16 16:55:08 -07001483 // always allow effects without processing load or latency
1484 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1485 return NO_ERROR;
1486 }
1487
Andy Hung116bc262023-06-20 18:56:17 -07001488 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001489 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1490 __func__);
1491 return BAD_VALUE;
1492 }
1493
Eric Laurent4eb45d02023-12-20 12:07:17 +01001494 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001495 && mType != SPATIALIZER) {
1496 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1497 __func__, mType);
1498 return BAD_VALUE;
1499 }
1500
Eric Laurent4c415062016-06-17 16:14:16 -07001501 switch (mType) {
1502 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001503 audio_output_flags_t flags = mOutput->flags;
1504 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1505 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1506 // global effects are applied only to non fast tracks if they are SW
1507 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1508 break;
1509 }
1510 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
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 output stage session",
1514 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001515 return BAD_VALUE;
1516 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001517 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1518 // only post processing on output stage session
1519 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001520 ALOGW("%s: non post processing effect %s not allowed on device session",
1521 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001522 return BAD_VALUE;
1523 }
Eric Laurent4c415062016-06-17 16:14:16 -07001524 } else {
1525 // no restriction on effects applied on non fast tracks
1526 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1527 break;
1528 }
1529 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001530
Eric Laurent4c415062016-06-17 16:14:16 -07001531 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001532 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001533 return BAD_VALUE;
1534 }
1535 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001536 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1537 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001538 return BAD_VALUE;
1539 }
1540 }
1541 } break;
1542 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001543 // nothing actionable on offload threads, if the effect:
1544 // - is offloadable: the effect can be created
1545 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1546 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001547 break;
1548 case DIRECT:
1549 // Reject any effect on Direct output threads for now, since the format of
1550 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001551 ALOGW("%s: effect %s on DIRECT output thread %s",
1552 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001553 return BAD_VALUE;
1554 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001555 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001556 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1557 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001558 return BAD_VALUE;
1559 }
1560 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001561 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1562 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001563 return BAD_VALUE;
1564 }
1565 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001566 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1567 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001568 return BAD_VALUE;
1569 }
1570 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001571 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001572 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1573 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1574 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1575 // are supported and added after the spatializer.
1576 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1577 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1578 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001579 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001580 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1581 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001582 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001583 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1584 break;
1585 }
1586 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1587 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1588 __func__, desc->name);
1589 return BAD_VALUE;
1590 }
1591 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1592 // only post processing on output stage session
1593 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1594 ALOGW("%s: non post processing effect %s not allowed on device session",
1595 __func__, desc->name);
1596 return BAD_VALUE;
1597 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001598 }
1599 break;
jiabinc658e452022-10-21 20:52:21 +00001600 case BIT_PERFECT:
1601 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1602 // Allow HW accelerated effects of tunnel type
1603 break;
1604 }
1605 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1606 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1607 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1608 // 3) there is any bit-perfect track with the given session id.
1609 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1610 sessionId == AUDIO_SESSION_DEVICE) {
1611 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1612 __func__, desc->name, mThreadName);
1613 return BAD_VALUE;
1614 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1615 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1616 __func__, desc->name, sessionId);
1617 return BAD_VALUE;
1618 }
1619 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001620 default:
1621 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1622 }
1623
1624 return NO_ERROR;
1625}
1626
Andy Hungb17d24b2023-08-29 14:26:09 -07001627// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001628sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001629 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001630 const sp<IEffectClient>& effectClient,
1631 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001632 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001633 effect_descriptor_t *desc,
1634 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001636 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001637 bool probe,
1638 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001639{
Andy Hung116bc262023-06-20 18:56:17 -07001640 sp<IAfEffectModule> effect;
1641 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001642 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001643 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001644 bool chainCreated = false;
1645 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001646 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001647
1648 lStatus = initCheck();
1649 if (lStatus != NO_ERROR) {
1650 ALOGW("createEffect_l() Audio driver not initialized.");
1651 goto Exit;
1652 }
1653
Eric Laurent81784c32012-11-19 14:55:58 -08001654 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1655
Andy Hungb17d24b2023-08-29 14:26:09 -07001656 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07001657 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001658
Eric Laurent4c415062016-06-17 16:14:16 -07001659 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001660 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001661 goto Exit;
1662 }
1663
Eric Laurent81784c32012-11-19 14:55:58 -08001664 // check for existing effect chain with the requested audio session
1665 chain = getEffectChain_l(sessionId);
1666 if (chain == 0) {
1667 // create a new chain for this session
1668 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001669 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001670 addEffectChain_l(chain);
1671 chain->setStrategy(getStrategyForSession_l(sessionId));
1672 chainCreated = true;
1673 } else {
1674 effect = chain->getEffectFromDesc_l(desc);
1675 }
1676
1677 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1678
1679 if (effect == 0) {
Andy Hung7535ed92023-07-17 17:05:00 -07001680 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001681 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001682 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001683 if (lStatus != NO_ERROR) {
1684 goto Exit;
1685 }
1686 effectCreated = true;
1687
jiabinc52b1ff2019-10-31 17:20:42 -07001688 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001689 effect->setDevices(outDeviceTypeAddrs());
1690 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001691 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001692 effect->setAudioSource(mAudioSource);
1693 }
jiabin1319f5a2021-03-30 22:21:24 +00001694 if (effect->isHapticGenerator()) {
1695 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1696 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001697 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung7535ed92023-07-17 17:05:00 -07001698 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001699 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001700 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001701 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001702 }
1703 }
Eric Laurent81784c32012-11-19 14:55:58 -08001704 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001705 handle = IAfEffectHandle::create(
1706 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001707 lStatus = handle->initCheck();
1708 if (lStatus == OK) {
1709 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001710 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001711 }
Eric Laurent81784c32012-11-19 14:55:58 -08001712 if (enabled != NULL) {
1713 *enabled = (int)effect->isEnabled();
1714 }
1715 }
1716
1717Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001718 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hungf8635b62023-08-31 16:13:39 -07001719 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001720 if (effectCreated) {
1721 chain->removeEffect_l(effect);
1722 }
Eric Laurent81784c32012-11-19 14:55:58 -08001723 if (chainCreated) {
1724 removeEffectChain_l(chain);
1725 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001726 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001727 }
1728
Glenn Kasten9156ef32013-08-06 15:39:08 -07001729 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001730 return handle;
1731}
1732
Andy Hung4b17e882023-07-07 13:47:37 -07001733void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001734 bool unpinIfLast)
1735{
1736 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001737 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001738 {
Andy Hungf8635b62023-08-31 16:13:39 -07001739 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001740 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001741 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001742 return;
1743 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001744 effect = effectBase->asEffectModule();
1745 if (effect == nullptr) {
1746 return;
1747 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001748 // restore suspended effects if the disconnected handle was enabled and the last one.
1749 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1750 if (remove) {
1751 removeEffect_l(effect, true);
1752 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001753 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001754 }
1755 if (remove) {
Andy Hung7535ed92023-07-17 17:05:00 -07001756 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001757 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001758 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001759 }
1760 }
1761}
1762
Andy Hung4b17e882023-07-07 13:47:37 -07001763void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001764 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001765 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001766 broadcast_l();
1767 }
1768 if (!effect->isOffloadable()) {
1769 if (mType == ThreadBase::OFFLOAD) {
1770 PlaybackThread *t = (PlaybackThread *)this;
1771 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1772 }
1773 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung7535ed92023-07-17 17:05:00 -07001774 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001775 }
1776 }
1777}
1778
Andy Hung4b17e882023-07-07 13:47:37 -07001779void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001780 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001781 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001782 broadcast_l();
1783 }
1784}
1785
Andy Hung4b17e882023-07-07 13:47:37 -07001786sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001787 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001788{
Andy Hungf8635b62023-08-31 16:13:39 -07001789 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001790 return getEffect_l(sessionId, effectId);
1791}
1792
Andy Hung4b17e882023-07-07 13:47:37 -07001793sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001794 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001795{
Andy Hung116bc262023-06-20 18:56:17 -07001796 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001797 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1798}
1799
Andy Hung4b17e882023-07-07 13:47:37 -07001800std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001801{
Andy Hung116bc262023-06-20 18:56:17 -07001802 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001803 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001804}
1805
Andy Hungf8635b62023-08-31 16:13:39 -07001806// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1807// ThreadBase::mutex() held
1808status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001809{
1810 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001811 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001812 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001813 bool chainCreated = false;
1814
Eric Laurent5baf2af2013-09-12 17:37:00 -07001815 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hungf8635b62023-08-31 16:13:39 -07001816 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1817 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001818
Eric Laurent81784c32012-11-19 14:55:58 -08001819 if (chain == 0) {
1820 // create a new chain for this session
Andy Hungf8635b62023-08-31 16:13:39 -07001821 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001822 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001823 addEffectChain_l(chain);
1824 chain->setStrategy(getStrategyForSession_l(sessionId));
1825 chainCreated = true;
1826 }
Andy Hungf8635b62023-08-31 16:13:39 -07001827 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001828
1829 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hungf8635b62023-08-31 16:13:39 -07001830 ALOGW("%s: %p effect %s already present in chain %p",
1831 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001832 return BAD_VALUE;
1833 }
1834
Shunkai Yaod125e402024-01-20 03:19:06 +00001835 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001836
Eric Laurent81784c32012-11-19 14:55:58 -08001837 status_t status = chain->addEffect_l(effect);
1838 if (status != NO_ERROR) {
1839 if (chainCreated) {
1840 removeEffectChain_l(chain);
1841 }
1842 return status;
1843 }
1844
jiabin8f278ee2019-11-11 12:16:27 -08001845 effect->setDevices(outDeviceTypeAddrs());
1846 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001847 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001848 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001849
Eric Laurent81784c32012-11-19 14:55:58 -08001850 return NO_ERROR;
1851}
1852
Andy Hung4b17e882023-07-07 13:47:37 -07001853void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001854
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001855 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001856 effect_descriptor_t desc = effect->desc();
1857 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1858 detachAuxEffect_l(effect->id());
1859 }
1860
Andy Hung116bc262023-06-20 18:56:17 -07001861 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001862 if (chain != 0) {
1863 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001864 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001865 removeEffectChain_l(chain);
1866 }
1867 } else {
1868 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1869 }
1870}
1871
Shunkai Yaof4847652024-01-12 00:25:20 +00001872void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1873 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001874{
1875 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001876 for (const auto& effectChain : effectChains) {
1877 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001878 }
1879}
1880
Shunkai Yaof4847652024-01-12 00:25:20 +00001881void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1882 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001883{
Shunkai Yaof4847652024-01-12 00:25:20 +00001884 for (const auto& effectChain : effectChains) {
1885 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001886 }
1887}
1888
Andy Hung4b17e882023-07-07 13:47:37 -07001889sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001890{
Andy Hungf8635b62023-08-31 16:13:39 -07001891 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001892 return getEffectChain_l(sessionId);
1893}
1894
Andy Hung4b17e882023-07-07 13:47:37 -07001895sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001896 const
Eric Laurent81784c32012-11-19 14:55:58 -08001897{
1898 size_t size = mEffectChains.size();
1899 for (size_t i = 0; i < size; i++) {
1900 if (mEffectChains[i]->sessionId() == sessionId) {
1901 return mEffectChains[i];
1902 }
1903 }
1904 return 0;
1905}
1906
Andy Hung4b17e882023-07-07 13:47:37 -07001907void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001908{
Andy Hungf8635b62023-08-31 16:13:39 -07001909 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001910 size_t size = mEffectChains.size();
1911 for (size_t i = 0; i < size; i++) {
1912 mEffectChains[i]->setMode_l(mode);
1913 }
1914}
1915
Andy Hung4b17e882023-07-07 13:47:37 -07001916void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001917{
1918 config->type = AUDIO_PORT_TYPE_MIX;
1919 config->ext.mix.handle = mId;
1920 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001921 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001922 config->channel_mask = mChannelMask;
1923 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1924 AUDIO_PORT_CONFIG_FORMAT;
1925}
1926
Andy Hung4b17e882023-07-07 13:47:37 -07001927void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001928{
Andy Hungf8635b62023-08-31 16:13:39 -07001929 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001930 if (mSystemReady) {
1931 return;
1932 }
1933 mSystemReady = true;
1934
1935 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1936 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1937 }
1938 mPendingConfigEvents.clear();
1939}
1940
Andy Hungdae27702016-10-31 14:01:16 -07001941template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001942ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001943 ssize_t index = mActiveTracks.indexOf(track);
1944 if (index >= 0) {
1945 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1946 return index;
1947 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001948 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001949 mActiveTracksGeneration++;
1950 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001951 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001952 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001953 return mActiveTracks.add(track);
1954}
1955
1956template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001957ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001958 ssize_t index = mActiveTracks.remove(track);
1959 if (index < 0) {
1960 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1961 return index;
1962 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001963 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001964 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001965 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001966 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001967 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001968#ifdef TEE_SINK
1969 track->dumpTee(-1 /* fd */, "_REMOVE");
1970#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001971 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001972 return index;
1973}
1974
1975template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001976void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001977 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001978 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001979 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001980 }
1981 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001982 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001983 mActiveTracks.clear();
1984 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001985}
1986
1987template <typename T>
Andy Hung94dfbb42023-09-06 19:41:47 -07001988void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001989 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001990 // Updates ActiveTracks client uids to the thread wakelock.
1991 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1992 thread->updateWakeLockUids_l(getWakeLockUids());
1993 mLastActiveTracksGeneration = mActiveTracksGeneration;
1994 }
Andy Hungdae27702016-10-31 14:01:16 -07001995}
Eric Laurent83b88082014-06-20 18:31:16 -07001996
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001997template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001998bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001999 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002000 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002001
2002 for (const sp<T> &track : mActiveTracks) {
2003 // Do not short-circuit as all hasChanged states must be reset
2004 // as all the metadata are going to be sent
2005 hasChanged |= track->readAndClearHasChanged();
2006 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002007 return hasChanged;
2008}
2009
2010template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002011void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002012 const char *funcName, const sp<T> &track) const {
2013 if (mLocalLog != nullptr) {
2014 String8 result;
2015 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002016 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002017 }
2018}
2019
Andy Hung4b17e882023-07-07 13:47:37 -07002020void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002021{
2022 // Thread could be blocked waiting for async
2023 // so signal it to handle state changes immediately
2024 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2025 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2026 mSignalPending = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07002027 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002028}
2029
Andy Hungd0979812019-02-21 15:51:44 -08002030// Call only from threadLoop() or when it is idle.
2031// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07002032void ThreadBase::sendStatistics(bool force)
Andy Hung94dfbb42023-09-06 19:41:47 -07002033NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002034{
2035 // Do not log if we have no stats.
2036 // We choose the timestamp verifier because it is the most likely item to be present.
2037 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2038 if (nstats == 0) {
2039 return;
2040 }
2041
2042 // Don't log more frequently than once per 12 hours.
2043 // We use BOOTTIME to include suspend time.
2044 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2045 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2046 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2047 return;
2048 }
2049
2050 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2051 mLastRecordedTimeNs = timeNs;
2052
Ray Essickf27e9872019-12-07 06:28:46 -08002053 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002054
2055#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2056
2057 // thread configuration
2058 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2059 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2060 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2061 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2062 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2063 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2064 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hung94dfbb42023-09-06 19:41:47 -07002065 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2066 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002067
2068 // thread statistics
2069 if (mIoJitterMs.getN() > 0) {
2070 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2071 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2072 }
2073 if (mProcessTimeMs.getN() > 0) {
2074 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2075 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2076 }
2077 const auto tsjitter = mTimestampVerifier.getJitterMs();
2078 if (tsjitter.getN() > 0) {
2079 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2080 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2081 }
2082 if (mLatencyMs.getN() > 0) {
2083 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2084 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2085 }
Robert Wu06db0a32021-08-10 19:05:34 +00002086 if (mMonopipePipeDepthStats.getN() > 0) {
2087 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2088 mMonopipePipeDepthStats.getMean());
2089 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2090 mMonopipePipeDepthStats.getStdDev());
2091 }
Andy Hungd0979812019-02-21 15:51:44 -08002092
2093 item->selfrecord();
2094}
2095
Andy Hung4b17e882023-07-07 13:47:37 -07002096product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002097{
Andy Hung7535ed92023-07-17 17:05:00 -07002098 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002099 return PRODUCT_STRATEGY_NONE;
2100 }
2101 return AudioSystem::getStrategyForStream(stream);
2102}
2103
Andy Hungb17d24b2023-08-29 14:26:09 -07002104// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002105void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002106 const sp<audio_utils::MelProcessor>& /*processor*/)
2107{
2108 // Do nothing
2109 ALOGW("%s: ThreadBase does not support CSD", __func__);
2110}
2111
Andy Hungb17d24b2023-08-29 14:26:09 -07002112// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002113void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002114{
2115 // Do nothing
2116 ALOGW("%s: ThreadBase does not support CSD", __func__);
2117}
2118
Eric Laurent81784c32012-11-19 14:55:58 -08002119// ----------------------------------------------------------------------------
2120// Playback
2121// ----------------------------------------------------------------------------
2122
Andy Hung7535ed92023-07-17 17:05:00 -07002123PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002124 AudioStreamOut* output,
2125 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002126 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002127 bool systemReady,
2128 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002129 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002130 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002131 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002132 mMixerBuffer(NULL),
2133 mMixerBufferSize(0),
2134 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2135 mMixerBufferValid(false),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002136 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002137 mEffectBuffer(NULL),
2138 mEffectBufferSize(0),
2139 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2140 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002141 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002142 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002143 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002144 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002145 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002146 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002147 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002148 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002149 mMixerStatus(MIXER_IDLE),
2150 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hungd58c4732023-07-20 21:31:38 -07002151 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002152 mBytesRemaining(0),
2153 mCurrentWriteLength(0),
2154 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002155 mWriteAckSequence(0),
2156 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002157 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002158 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002159 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002160 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002161 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002162 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002163 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002164{
Glenn Kastend7dca052015-03-05 16:05:54 -08002165 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002166 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002167
Andy Hungb17d24b2023-08-29 14:26:09 -07002168 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002169 // it would be safer to explicitly pass initial masterVolume/masterMute as
2170 // parameter.
2171 //
2172 // If the HAL we are using has support for master volume or master mute,
2173 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2174 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002175 mMasterVolume = afThreadCallback->masterVolume_l();
2176 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002177 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002178 if (mOutput->audioHwDev->canSetMasterVolume()) {
2179 mMasterVolume = 1.0;
2180 }
2181
2182 if (mOutput->audioHwDev->canSetMasterMute()) {
2183 mMasterMute = false;
2184 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002185 mIsMsdDevice = strcmp(
2186 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002187 }
2188
Eric Laurentf1f22e72021-07-13 14:04:14 +02002189 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2190 mMixerChannelMask = mixerConfig->channel_mask;
2191 }
2192
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002193 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002194
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002195 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002196 && mMixerChannelMask != mChannelMask) {
2197 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2198 mChannelMask, mMixerChannelMask);
2199 }
2200
Andy Hungc8fddf32018-08-08 18:32:37 -07002201 // TODO: We may also match on address as well as device type for
2202 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002203 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002204 // TODO: This property should be ensure that only contains one single device type.
2205 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2206 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002207 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2208 : AUDIO_DEVICE_NONE));
2209 }
2210
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002211 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2212 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002213 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002214 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002215 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002216 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002217 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2218 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002219 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2220 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002221}
2222
Andy Hung4b17e882023-07-07 13:47:37 -07002223PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002224{
Andy Hung7535ed92023-07-17 17:05:00 -07002225 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002226 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002227 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002228 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002229 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002230}
2231
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002232// Thread virtuals
2233
Andy Hung4b17e882023-07-07 13:47:37 -07002234void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002235{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002236 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002237 ALOGE("The stream is not open yet"); // This should not happen.
2238 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002239 // Callbacks take strong or weak pointers as a parameter.
2240 // Since PlaybackThread passes itself as a callback handler, it can only
2241 // be done outside of the constructor. Creating weak and especially strong
2242 // pointers to a refcounted object in its own constructor is strongly
2243 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2244 // Even if a function takes a weak pointer, it is possible that it will
2245 // need to convert it to a strong pointer down the line.
2246 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2247 mOutput->stream->setCallback(this) == OK) {
2248 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002249 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002250 }
2251
jiabinf6eb4c32020-02-25 14:06:25 -08002252 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002253 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002254 }
2255 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002256 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002257 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002258}
2259
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002260// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002261void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002262{
2263 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002264 status_t result = mOutput->stream->exit();
2265 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002266}
2267
Andy Hung4b17e882023-07-07 13:47:37 -07002268void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002269{
Eric Laurent81784c32012-11-19 14:55:58 -08002270 String8 result;
2271
Marco Nelissenb2208842014-02-07 14:00:50 -08002272 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002273 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2274 const stream_type_t *st = &mStreamTypes[i];
2275 if (i > 0) {
2276 result.appendFormat(", ");
2277 }
2278 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2279 if (st->mute) {
2280 result.append("M");
2281 }
2282 }
2283 result.append("\n");
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002284 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002285 result.clear();
2286
Eric Laurent81784c32012-11-19 14:55:58 -08002287 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2288 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002289 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002290 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002291
2292 size_t numtracks = mTracks.size();
2293 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002294 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002295 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002296 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002297 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002298 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002299 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002300 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002301 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002302 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002303 if (track != 0) {
2304 bool active = mActiveTracks.indexOf(track) >= 0;
2305 if (active) {
2306 numactiveseen++;
2307 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002308 result.append(prefix);
2309 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002310 }
2311 }
2312 } else {
2313 result.append("\n");
2314 }
2315 if (numactiveseen != numactive) {
2316 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002317 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002318 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002319 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002320 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002321 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002322 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002323 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002324 result.append(prefix);
2325 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002326 }
2327 }
2328 }
2329
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002330 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002331}
2332
Andy Hung4b17e882023-07-07 13:47:37 -07002333void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002334{
Andy Hung04cb8f72020-03-20 13:44:33 -07002335 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002336 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002337 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2338 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002339 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2340 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2341 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2342 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002343 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002344 dprintf(fd, " Total writes: %d\n", mNumWrites);
2345 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2346 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung160664b2023-09-15 18:19:28 -07002347 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002348 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002349 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002350 AudioStreamOut *output = mOutput;
2351 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002352 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002353 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002354 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2355 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2356 if (mPipeSink.get() != nullptr) {
2357 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2358 }
2359 if (output != nullptr) {
2360 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002361 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002362 }
Eric Laurent81784c32012-11-19 14:55:58 -08002363}
2364
Andy Hungb17d24b2023-08-29 14:26:09 -07002365// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002366sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002367 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002368 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002369 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002370 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002371 audio_format_t format,
2372 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002373 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002374 size_t *pNotificationFrameCount,
2375 uint32_t notificationsPerBuffer,
2376 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002377 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002378 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002379 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002380 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002381 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002382 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002383 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002384 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002385 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002386 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002387 bool isBitPerfect,
2388 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002389{
Glenn Kasten74935e42013-12-19 08:56:45 -08002390 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002391 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002392 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002393 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002394 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002395 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002396 uint32_t sampleRate;
2397
2398 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2399 lStatus = BAD_VALUE;
2400 goto Exit;
2401 }
Eric Laurent21da6472017-11-09 16:29:26 -08002402
2403 if (*pSampleRate == 0) {
2404 *pSampleRate = mSampleRate;
2405 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002406 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002407
2408 // special case for FAST flag considered OK if fast mixer is present
2409 if (hasFastMixer()) {
2410 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2411 }
2412
2413 // Check if requested flags are compatible with output stream flags
2414 if ((*flags & outputFlags) != *flags) {
2415 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2416 *flags, outputFlags);
2417 *flags = (audio_output_flags_t)(*flags & outputFlags);
2418 }
Eric Laurent81784c32012-11-19 14:55:58 -08002419
jiabinc658e452022-10-21 20:52:21 +00002420 if (isBitPerfect) {
Andy Hung160664b2023-09-15 18:19:28 -07002421 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002422 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002423 if (chain.get() != nullptr) {
2424 // Bit-perfect is required according to the configuration and preferred mixer
2425 // attributes, but it is not in the output flag from the client's request. Explicitly
2426 // adding bit-perfect flag to check the compatibility
2427 audio_output_flags_t flagsToCheck =
2428 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2429 chain->checkOutputFlagCompatibility(&flagsToCheck);
2430 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2431 ALOGE("%s cannot create track as there is data-processing effect attached to "
2432 "given session id(%d)", __func__, sessionId);
2433 lStatus = BAD_VALUE;
2434 goto Exit;
2435 }
2436 *flags = flagsToCheck;
2437 }
2438 }
2439
Eric Laurent81784c32012-11-19 14:55:58 -08002440 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002441 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002442 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002443 // PCM data
2444 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002445 // TODO: extract as a data library function that checks that a computationally
2446 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002447 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002448 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2449 (channelMask == AUDIO_CHANNEL_OUT_MONO
2450 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002451 // hardware sample rate
2452 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002453 // normal mixer has an associated fast mixer
2454 hasFastMixer() &&
2455 // there are sufficient fast track slots available
2456 (mFastTrackAvailMask != 0)
2457 // FIXME test that MixerThread for this fast track has a capable output HAL
2458 // FIXME add a permission test also?
2459 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002460 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2461 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002462 // read the fast track multiplier property the first time it is needed
2463 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2464 if (ok != 0) {
2465 ALOGE("%s pthread_once failed: %d", __func__, ok);
2466 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002467 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002468 }
Eric Laurent4c415062016-06-17 16:14:16 -07002469
2470 // check compatibility with audio effects.
Andy Hungb17d24b2023-08-29 14:26:09 -07002471 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002472 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002473 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002474 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002475 AUDIO_SESSION_OUTPUT_STAGE,
2476 AUDIO_SESSION_OUTPUT_MIX,
2477 sessionId,
2478 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002479 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002480 if (chain.get() != nullptr) {
2481 audio_output_flags_t old = *flags;
2482 chain->checkOutputFlagCompatibility(flags);
2483 if (old != *flags) {
2484 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2485 (int)session, (int)old, (int)*flags);
2486 }
Eric Laurent4c415062016-06-17 16:14:16 -07002487 }
2488 }
2489 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002490 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002491 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2492 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002493 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002494 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002495 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002496 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002497 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002498 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002499 audio_is_linear_pcm(format), channelMask, sampleRate,
2500 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002501 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002502 }
2503 }
Eric Laurent21da6472017-11-09 16:29:26 -08002504
2505 if (!audio_has_proportional_frames(format)) {
2506 if (sharedBuffer != 0) {
2507 // Same comment as below about ignoring frameCount parameter for set()
2508 frameCount = sharedBuffer->size();
2509 } else if (frameCount == 0) {
2510 frameCount = mNormalFrameCount;
2511 }
2512 if (notificationFrameCount != frameCount) {
2513 notificationFrameCount = frameCount;
2514 }
2515 } else if (sharedBuffer != 0) {
2516 // FIXME: Ensure client side memory buffers need
2517 // not have additional alignment beyond sample
2518 // (e.g. 16 bit stereo accessed as 32 bit frame).
2519 size_t alignment = audio_bytes_per_sample(format);
2520 if (alignment & 1) {
2521 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2522 alignment = 1;
2523 }
2524 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2525 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2526 if (channelCount > 1) {
2527 // More than 2 channels does not require stronger alignment than stereo
2528 alignment <<= 1;
2529 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002530 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002531 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002532 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002533 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002534 goto Exit;
2535 }
Eric Laurent21da6472017-11-09 16:29:26 -08002536
2537 // When initializing a shared buffer AudioTrack via constructors,
2538 // there's no frameCount parameter.
2539 // But when initializing a shared buffer AudioTrack via set(),
2540 // there _is_ a frameCount parameter. We silently ignore it.
2541 frameCount = sharedBuffer->size() / frameSize;
2542 } else {
2543 size_t minFrameCount = 0;
2544 // For fast tracks we try to respect the application's request for notifications per buffer.
2545 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2546 if (notificationsPerBuffer > 0) {
2547 // Avoid possible arithmetic overflow during multiplication.
2548 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2549 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2550 notificationsPerBuffer, mFrameCount);
2551 } else {
2552 minFrameCount = mFrameCount * notificationsPerBuffer;
2553 }
2554 }
2555 } else {
2556 // For normal PCM streaming tracks, update minimum frame count.
2557 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2558 // cover audio hardware latency.
2559 // This is probably too conservative, but legacy application code may depend on it.
2560 // If you change this calculation, also review the start threshold which is related.
2561 uint32_t latencyMs = latency_l();
2562 if (latencyMs == 0) {
2563 ALOGE("Error when retrieving output stream latency");
2564 lStatus = UNKNOWN_ERROR;
2565 goto Exit;
2566 }
2567
2568 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2569 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2570
Eric Laurent81784c32012-11-19 14:55:58 -08002571 }
Eric Laurent21da6472017-11-09 16:29:26 -08002572 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002573 frameCount = minFrameCount;
2574 }
Eric Laurent81784c32012-11-19 14:55:58 -08002575 }
Eric Laurent21da6472017-11-09 16:29:26 -08002576
2577 // Make sure that application is notified with sufficient margin before underrun.
2578 // The client can divide the AudioTrack buffer into sub-buffers,
2579 // and expresses its desire to server as the notification frame count.
2580 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2581 size_t maxNotificationFrames;
2582 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2583 // notify every HAL buffer, regardless of the size of the track buffer
2584 maxNotificationFrames = mFrameCount;
2585 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002586 // Triple buffer the notification period for a triple buffered mixer period;
2587 // otherwise, double buffering for the notification period is fine.
2588 //
2589 // TODO: This should be moved to AudioTrack to modify the notification period
2590 // on AudioTrack::setBufferSizeInFrames() changes.
2591 const int nBuffering =
2592 (uint64_t{frameCount} * mSampleRate)
2593 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2594
Eric Laurent21da6472017-11-09 16:29:26 -08002595 maxNotificationFrames = frameCount / nBuffering;
2596 // If client requested a fast track but this was denied, then use the smaller maximum.
2597 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2598 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2599 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2600 maxNotificationFrames = maxNotificationFramesFastDenied;
2601 }
2602 }
2603 }
2604 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2605 if (notificationFrameCount == 0) {
2606 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2607 maxNotificationFrames, frameCount);
2608 } else {
2609 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2610 notificationFrameCount, maxNotificationFrames, frameCount);
2611 }
2612 notificationFrameCount = maxNotificationFrames;
2613 }
2614 }
2615
Glenn Kasten74935e42013-12-19 08:56:45 -08002616 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002617 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002618
Glenn Kastenc3df8382014-03-13 15:05:25 -07002619 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002620 case BIT_PERFECT:
2621 if (isBitPerfect) {
2622 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2623 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2624 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2625 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2626 mChannelMask);
2627 lStatus = BAD_VALUE;
2628 goto Exit;
2629 }
2630 }
2631 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002632
2633 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002634 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002635 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002636 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2637 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002638 sampleRate, format, channelMask, mOutput, mFormat);
2639 lStatus = BAD_VALUE;
2640 goto Exit;
2641 }
2642 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002643 break;
2644
2645 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002647 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2648 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002649 sampleRate, format, channelMask, mOutput, mFormat);
2650 lStatus = BAD_VALUE;
2651 goto Exit;
2652 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002653 break;
2654
2655 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002656 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002657 ALOGE("createTrack_l() Bad parameter: format %#x \""
2658 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 format, mOutput, mFormat);
2660 lStatus = BAD_VALUE;
2661 goto Exit;
2662 }
Andy Hungcd044842014-08-07 11:04:34 -07002663 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002664 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2665 lStatus = BAD_VALUE;
2666 goto Exit;
2667 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002668 break;
2669
Eric Laurent81784c32012-11-19 14:55:58 -08002670 }
2671
2672 lStatus = initCheck();
2673 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002674 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002675 goto Exit;
2676 }
2677
Andy Hungb17d24b2023-08-29 14:26:09 -07002678 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002679 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002680
2681 // all tracks in same audio session must share the same routing strategy otherwise
2682 // conflicts will happen when tracks are moved from one output to another by audio policy
2683 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002684 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002685 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002686 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002687 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002688 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002689 if (sessionId == t->sessionId() && strategy != actual) {
2690 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2691 strategy, actual);
2692 lStatus = BAD_VALUE;
2693 goto Exit;
2694 }
2695 }
2696 }
2697
Deeraj Soman2b515232024-05-14 12:58:24 +05302698 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2699 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002700 // dynamic audio policy.
2701 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302702 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002703 audio_output_flags_t trackFlags = *flags;
2704 if (mType == DIRECT) {
2705 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302706 } else if (mType == OFFLOAD) {
2707 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2708 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002709 }
jiabin94ed47c2023-07-27 23:34:20 +00002710 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002711
Andy Hung11e74242023-06-26 19:20:57 -07002712 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002713 channelMask, frameCount,
2714 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002715 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002716 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002717 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002718
Glenn Kasten03003332013-08-06 15:40:54 -07002719 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2720 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002721 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002722 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002723 goto Exit;
2724 }
2725 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002726 {
Andy Hungf8635b62023-08-31 16:13:39 -07002727 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002728 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002729 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002730 }
2731 }
Eric Laurent81784c32012-11-19 14:55:58 -08002732
Andy Hung116bc262023-06-20 18:56:17 -07002733 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002734 if (chain != 0) {
2735 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2736 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002737 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002738 chain->incTrackCnt();
2739 }
2740
Eric Laurent05067782016-06-01 18:27:28 -07002741 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002742 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2743 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2744 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002745 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002746 }
2747 }
2748
2749 lStatus = NO_ERROR;
2750
2751Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002752 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002753 return track;
2754}
2755
Andy Hung1bc088a2018-02-09 15:57:31 -08002756template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002757ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002758{
Andy Hungc0691382018-09-12 18:01:57 -07002759 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002760 const ssize_t index = mTracks.remove(track);
2761 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002762 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002763 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002764 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002765 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002766 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002767 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002768 }
2769 return index;
2770}
2771
Andy Hung4b17e882023-07-07 13:47:37 -07002772uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002773{
2774 return latency;
2775}
2776
Andy Hung4b17e882023-07-07 13:47:37 -07002777uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002778{
Andy Hungf8635b62023-08-31 16:13:39 -07002779 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002780 return latency_l();
2781}
Andy Hung4b17e882023-07-07 13:47:37 -07002782uint32_t PlaybackThread::latency_l() const
Andy Hung94dfbb42023-09-06 19:41:47 -07002783NO_THREAD_SAFETY_ANALYSIS
2784// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002785{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002786 uint32_t latency;
2787 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2788 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002789 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002790 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002791}
2792
Andy Hung4b17e882023-07-07 13:47:37 -07002793void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002794{
Andy Hungf8635b62023-08-31 16:13:39 -07002795 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002796 // Don't apply master volume in SW if our HAL can do it for us.
2797 if (mOutput && mOutput->audioHwDev &&
2798 mOutput->audioHwDev->canSetMasterVolume()) {
2799 mMasterVolume = 1.0;
2800 } else {
2801 mMasterVolume = value;
2802 }
2803}
2804
Andy Hung4b17e882023-07-07 13:47:37 -07002805void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002806{
2807 mMasterBalance.store(balance);
2808}
2809
Andy Hung4b17e882023-07-07 13:47:37 -07002810void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002811{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002812 if (isDuplicating()) {
2813 return;
2814 }
Andy Hungf8635b62023-08-31 16:13:39 -07002815 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002816 // Don't apply master mute in SW if our HAL can do it for us.
2817 if (mOutput && mOutput->audioHwDev &&
2818 mOutput->audioHwDev->canSetMasterMute()) {
2819 mMasterMute = false;
2820 } else {
2821 mMasterMute = muted;
2822 }
2823}
2824
Andy Hung4b17e882023-07-07 13:47:37 -07002825void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002826{
Andy Hungf8635b62023-08-31 16:13:39 -07002827 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002828 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002829 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002830}
2831
Andy Hung4b17e882023-07-07 13:47:37 -07002832void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002833{
Andy Hungf8635b62023-08-31 16:13:39 -07002834 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002835 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002836 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002837}
2838
Andy Hung4b17e882023-07-07 13:47:37 -07002839float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002840{
Andy Hungf8635b62023-08-31 16:13:39 -07002841 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002842 return mStreamTypes[stream].volume;
2843}
2844
Andy Hung4b17e882023-07-07 13:47:37 -07002845void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002846{
2847 mOutput->stream->setVolume(left, right);
2848}
2849
Andy Hungb17d24b2023-08-29 14:26:09 -07002850// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002851status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002852{
2853 status_t status = ALREADY_EXISTS;
2854
Eric Laurent81784c32012-11-19 14:55:58 -08002855 if (mActiveTracks.indexOf(track) < 0) {
2856 // the track is newly added, make sure it fills up all its
2857 // buffers before playing. This is to ensure the client will
2858 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002859 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002860 IAfTrackBase::track_state state = track->state();
Andy Hunga7187712023-12-05 17:28:17 -08002861 // Because the track is not on the ActiveTracks,
2862 // at this point, only the TrackHandle will be adding the track.
Andy Hungb17d24b2023-08-29 14:26:09 -07002863 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002864 status = AudioSystem::startOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002865 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002867 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 if (status == NO_ERROR) {
Andy Hungb17d24b2023-08-29 14:26:09 -07002869 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002870 AudioSystem::stopOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002871 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872 }
2873 return INVALID_OPERATION;
2874 }
2875 // abort if start is rejected by audio policy manager
2876 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002877 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2878 // current playback thread is reopened, which may happen when clients set preferred
2879 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2880 // immediately.
2881 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 }
2883#ifdef ADD_BATTERY_DATA
2884 // to track the speaker usage
2885 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2886#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002887 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002888 }
2889
Eric Laurent51716182016-02-29 18:00:56 -08002890 // set retry count for buffer fill
2891 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002892 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002893 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002894 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002895 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002896 }
Andy Hung11e74242023-06-26 19:20:57 -07002897 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002898 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002899 track->retryCount() = kMaxTrackStartupRetries;
2900 track->fillingStatus() =
2901 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002902 }
2903
Andy Hung116bc262023-06-20 18:56:17 -07002904 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002905 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2906 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2907 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002908 // Unlock due to VibratorService will lock for this call and will
2909 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungb17d24b2023-08-29 14:26:09 -07002910 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002911 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002912 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002913 std::optional<media::AudioVibratorInfo> vibratorInfo;
2914 {
2915 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2916 // used to play this track.
Andy Hungf8635b62023-08-31 16:13:39 -07002917 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung7535ed92023-07-17 17:05:00 -07002918 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002919 }
Andy Hungb17d24b2023-08-29 14:26:09 -07002920 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002921 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002922 if (vibratorInfo) {
2923 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2924 }
2925
jiabin57303cc2018-12-18 15:45:57 -08002926 // Haptic playback should be enabled by vibrator service.
2927 if (track->getHapticPlaybackEnabled()) {
2928 // Disable haptic playback of all active track to ensure only
2929 // one track playing haptic if current track should play haptic.
2930 for (const auto &t : mActiveTracks) {
2931 t->setHapticPlaybackEnabled(false);
2932 }
jiabin245cdd92018-12-07 17:55:15 -08002933 }
jiabine70bc7f2020-06-30 22:07:55 -07002934
2935 // Set haptic intensity for effect
2936 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002937 // TODO(b/324559333): Add adaptive haptics scaling support for the HapticGenerator.
2938 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002939 }
jiabin245cdd92018-12-07 17:55:15 -08002940 }
2941
Andy Hung11e74242023-06-26 19:20:57 -07002942 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002943 track->resetPresentationComplete();
Andy Hunga7187712023-12-05 17:28:17 -08002944
2945 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2946 // all key changes are complete. It is possible that the threadLoop will begin
2947 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002948 mActiveTracks.add(track);
Andy Hunga7187712023-12-05 17:28:17 -08002949
Eric Laurentd0107bc2013-06-11 14:38:48 -07002950 if (chain != 0) {
2951 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2952 track->sessionId());
2953 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002954 }
2955
Andy Hungc2b11cb2020-04-22 09:04:01 -07002956 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002957 status = NO_ERROR;
2958 }
2959
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002960 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002961 return status;
2962}
2963
Andy Hung4b17e882023-07-07 13:47:37 -07002964bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002965{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002966 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002967 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002968 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002969 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002971 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002972 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002973 if (track->isPausePending()) {
2974 track->pauseAck();
2975 }
Andy Hung11e74242023-06-26 19:20:57 -07002976 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002977 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002978
2979 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002980}
2981
Andy Hung4b17e882023-07-07 13:47:37 -07002982void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002983{
2984 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002985
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002986 String8 result;
2987 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002988 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002989
Eric Laurent81784c32012-11-19 14:55:58 -08002990 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002991 {
Andy Hungf8635b62023-08-31 16:13:39 -07002992 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002993 mAudioTrackCallbacks.erase(track);
2994 }
Eric Laurent81784c32012-11-19 14:55:58 -08002995 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002996 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002997 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002998 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2999 mFastTrackAvailMask |= 1 << index;
3000 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07003001 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003002 }
Andy Hung116bc262023-06-20 18:56:17 -07003003 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003004 if (chain != 0) {
3005 chain->decTrackCnt();
3006 }
3007}
3008
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003009std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3010{
3011 std::set<int32_t> result;
3012 for (const auto& t : mTracks) {
3013 if (t->isExternalTrack()) {
3014 result.insert(t->portId());
3015 }
3016 }
3017 return result;
3018}
3019
3020std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3021{
3022 audio_utils::lock_guard _l(mutex());
3023 return getTrackPortIds_l();
3024}
3025
Andy Hung4b17e882023-07-07 13:47:37 -07003026String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003027{
Andy Hungf8635b62023-08-31 16:13:39 -07003028 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003029 String8 out_s8;
3030 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3031 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003032 }
Andy Hung920f6572022-10-06 12:09:49 -07003033 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003034}
3035
Andy Hung4b17e882023-07-07 13:47:37 -07003036status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hungf8635b62023-08-31 16:13:39 -07003037 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003038 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003039 return NO_INIT;
3040 }
3041 return mOutput->stream->selectPresentation(presentationId, programId);
3042}
3043
Andy Hung94dfbb42023-09-06 19:41:47 -07003044void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003045 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003046 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003047 sp<AudioIoDescriptor> desc;
3048 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003049 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003050 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003051 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003052 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003053 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3054 mSampleRate, mFormat, mChannelMask,
3055 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3056 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003057 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003058 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003059 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003060 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003061 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003062 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003063 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003064 break;
3065 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003066 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003067}
3068
Andy Hung4b17e882023-07-07 13:47:37 -07003069void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003070{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003071 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003072}
3073
Andy Hung4b17e882023-07-07 13:47:37 -07003074void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003075{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003076 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003077}
3078
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003079void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003080{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003081 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003082}
3083
Andy Hung4b17e882023-07-07 13:47:37 -07003084void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003085 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003086{
Andy Hung4b17e882023-07-07 13:47:37 -07003087 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003088 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07003089 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003090 if (playbackThread == nullptr) {
3091 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3092 return;
3093 }
3094
jiabinf6eb4c32020-02-25 14:06:25 -08003095 audio_utils::metadata::Data metadata =
3096 audio_utils::metadata::dataFromByteString(metadataBs);
3097 if (metadata.empty()) {
3098 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3099 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3100 (int)metadataBs.size());
3101 return;
3102 }
3103
3104 audio_utils::metadata::ByteString metaDataStr =
3105 audio_utils::metadata::byteStringFromData(metadata);
3106 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hungf8635b62023-08-31 16:13:39 -07003107 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003108 for (const auto& callbackPair : mAudioTrackCallbacks) {
3109 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003110 }
3111 }).detach();
3112}
3113
Andy Hung4b17e882023-07-07 13:47:37 -07003114void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003115{
Andy Hungf8635b62023-08-31 16:13:39 -07003116 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003117 // reject out of sequence requests
3118 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3119 mWriteAckSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003120 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003121 }
3122}
3123
Andy Hung4b17e882023-07-07 13:47:37 -07003124void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003125{
Andy Hungf8635b62023-08-31 16:13:39 -07003126 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003127 // reject out of sequence requests
3128 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003129 // Register discontinuity when HW drain is completed because that can cause
3130 // the timestamp frame position to reset to 0 for direct and offload threads.
3131 // (Out of sequence requests are ignored, since the discontinuity would be handled
3132 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003133 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003134 mDrainSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003135 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003136 }
3137}
3138
Andy Hung4b17e882023-07-07 13:47:37 -07003139void PlaybackThread::readOutputParameters_l()
Andy Hungf8635b62023-08-31 16:13:39 -07003140NO_THREAD_SAFETY_ANALYSIS
3141// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003142{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003143 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003144 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3145 mSampleRate = audioConfig.sample_rate;
3146 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003147 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003148 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003149 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003150 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003151 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3152 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003153 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003154
3155 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3156 mMixerChannelMask = mChannelMask;
3157 }
3158
Andy Hunge5412692014-05-16 11:25:07 -07003159 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003160 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003161
Eric Laurentf1f22e72021-07-13 14:04:14 +02003162 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3163
Phil Burkca5e6142015-07-14 09:42:29 -07003164 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003165 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003166 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003167 // Get format from the shim, which will be different than the HAL format
3168 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003169 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003170 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003171 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003172 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003173 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003174 LOG_FATAL("HAL format %#x not supported for mixed output",
3175 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003176 }
Phil Burk062e67a2015-02-11 13:40:50 -08003177 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003178 result = mOutput->stream->getBufferSize(&mBufferSize);
3179 LOG_ALWAYS_FATAL_IF(result != OK,
3180 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003181 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003182 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003183 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003184 mFrameCount);
3185 }
3186
Eric Laurentd1f69b02014-12-15 14:33:13 -08003187 mHwSupportsPause = false;
3188 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003189 bool supportsPause = false, supportsResume = false;
3190 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3191 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003192 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003193 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003194 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003195 } else if (supportsResume) {
3196 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003197 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003198 }
3199 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003200 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3201 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3202 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003203
Andy Hungfbfc3952015-01-15 13:33:51 -08003204 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3205 // For best precision, we use float instead of the associated output
3206 // device format (typically PCM 16 bit).
3207
3208 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3209 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3210 mBufferSize = mFrameSize * mFrameCount;
3211
3212 // TODO: We currently use the associated output device channel mask and sample rate.
3213 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3214 // (if a valid mask) to avoid premature downmix.
3215 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3216 // instead of the output device sample rate to avoid loss of high frequency information.
3217 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3218 }
3219
Andy Hung09a50072014-02-27 14:30:47 -08003220 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003221 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003222 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003223 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3224 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003225 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3226 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003227
Eric Laurent81784c32012-11-19 14:55:58 -08003228 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3229 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3230 maxNormalFrameCount = maxNormalFrameCount & ~15;
3231 if (maxNormalFrameCount < minNormalFrameCount) {
3232 maxNormalFrameCount = minNormalFrameCount;
3233 }
3234 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3235 if (multiplier <= 1.0) {
3236 multiplier = 1.0;
3237 } else if (multiplier <= 2.0) {
3238 if (2 * mFrameCount <= maxNormalFrameCount) {
3239 multiplier = 2.0;
3240 } else {
3241 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3242 }
3243 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003244 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003245 }
3246 }
3247 mNormalFrameCount = multiplier * mFrameCount;
3248 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003249 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003250 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3251 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003252 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3253 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003254
Andy Hung08fb1742015-05-31 23:22:10 -07003255 // Check if we want to throttle the processing to no more than 2x normal rate
3256 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003257 mThreadThrottleTimeMs = 0;
3258 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003259 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3260
Andy Hung010a1a12014-03-13 13:57:33 -07003261 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3262 // Originally this was int16_t[] array, need to remove legacy implications.
3263 free(mSinkBuffer);
3264 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003265
Andy Hung5b10a202014-03-13 13:59:29 -07003266 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3267 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3268 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003269 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003270
Andy Hung69aed5f2014-02-25 17:24:40 -08003271 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3272 // drives the output.
3273 free(mMixerBuffer);
3274 mMixerBuffer = NULL;
3275 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003276 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003277 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003278 * audio_bytes_per_sample(mMixerBufferFormat);
3279 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3280 }
Andy Hung98ef9782014-03-04 14:46:50 -08003281 free(mEffectBuffer);
3282 mEffectBuffer = NULL;
3283 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003284 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003285 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003286 * audio_bytes_per_sample(mEffectBufferFormat);
3287 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3288 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003289
Eric Laurentb62d0362021-10-26 17:40:18 +02003290 if (mType == SPATIALIZER) {
3291 free(mPostSpatializerBuffer);
3292 mPostSpatializerBuffer = nullptr;
3293 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3294 * audio_bytes_per_sample(mEffectBufferFormat);
3295 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3296 }
3297
Mikhail Naganov55773032020-10-01 15:08:13 -07003298 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3299 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003300 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3301 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003302 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003303
Eric Laurent81784c32012-11-19 14:55:58 -08003304 // force reconfiguration of effect chains and engines to take new buffer size and audio
3305 // parameters into account
Andy Hungb17d24b2023-08-29 14:26:09 -07003306 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003307 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3308 // matter.
Andy Hungf8635b62023-08-31 16:13:39 -07003309 // create a copy of mEffectChains as calling moveEffectChain_ll()
3310 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003311 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003312 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hungf8635b62023-08-31 16:13:39 -07003313 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003314 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003315 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003316
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003317 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003318 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003319 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07003320 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003321 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3322 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3323 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3324 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3325 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3326 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3327 (int32_t)mHapticChannelMask)
3328 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3329 (int32_t)mHapticChannelCount)
3330 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -07003331 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003332 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3333 (int32_t)mFrameCount) // sic - added HAL
3334 ;
3335 uint32_t latencyMs;
3336 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3337 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3338 }
3339 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003340}
3341
Andy Hung4b17e882023-07-07 13:47:37 -07003342ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003343{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003344 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003345 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003346 }
3347 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003348 static const bool stereo_spatialization_property =
3349 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3350 const bool stereo_spatialization_enabled =
3351 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3352 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003353 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3354 for (const sp<IAfTrack>& track : mActiveTracks) {
3355 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3356 allSessionsMetadata[track->sessionId()];
3357 auto backInserter = std::back_inserter(sessionMetadata);
3358 // No track is invalid as this is called after prepareTrack_l in the same
3359 // critical section
3360 track->copyMetadataTo(backInserter);
3361 }
3362 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3363 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3364 metadata.tracks.insert(metadata.tracks.end(),
3365 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3366 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3367 chain->sendMetadata_l(sessionTrackMetadata, {});
3368 }
3369 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3370 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3371 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3372 }
3373 }
3374 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3375 chain->sendMetadata_l(metadata.tracks, {});
3376 }
3377 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3378 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3379 }
3380 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3381 chain->sendMetadata_l(metadata.tracks, {});
3382 }
3383 } else {
3384 auto backInserter = std::back_inserter(metadata.tracks);
3385 for (const sp<IAfTrack>& track : mActiveTracks) {
3386 // No track is invalid as this is called after prepareTrack_l in the same
3387 // critical section
3388 track->copyMetadataTo(backInserter);
3389 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003390 }
Kevin Rocard12381092018-04-11 09:19:59 -07003391 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003392 MetadataUpdate change;
3393 change.playbackMetadataUpdate = metadata.tracks;
3394 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003395}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003396
Andy Hung4b17e882023-07-07 13:47:37 -07003397void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003398 const StreamOutHalInterface::SourceMetadata& metadata)
3399{
3400 mOutput->stream->updateSourceMetadata(metadata);
3401};
3402
Andy Hung4b17e882023-07-07 13:47:37 -07003403status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003404 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003405{
3406 if (halFrames == NULL || dspFrames == NULL) {
3407 return BAD_VALUE;
3408 }
Andy Hungf8635b62023-08-31 16:13:39 -07003409 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003410 if (initCheck() != NO_ERROR) {
3411 return INVALID_OPERATION;
3412 }
Andy Hung818e7a32016-02-16 18:08:07 -08003413 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003414 *halFrames = framesWritten;
3415
3416 if (isSuspended()) {
3417 // return an estimation of rendered frames when the output is suspended
3418 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003419 *dspFrames = (uint32_t)
3420 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003421 return NO_ERROR;
3422 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003423 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003424 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003425 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003426 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003427 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003428 }
3429}
3430
Andy Hung4b17e882023-07-07 13:47:37 -07003431product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003432{
3433 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3434 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3435 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003436 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003437 }
3438 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003439 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003440 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003441 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003442 }
3443 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003444 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003445}
3446
3447
Andy Hung4b17e882023-07-07 13:47:37 -07003448AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003449{
Andy Hungf8635b62023-08-31 16:13:39 -07003450 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003451 return mOutput;
3452}
3453
Andy Hung4b17e882023-07-07 13:47:37 -07003454AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003455{
Andy Hungf8635b62023-08-31 16:13:39 -07003456 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003457 AudioStreamOut *output = mOutput;
3458 mOutput = NULL;
3459 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3460 // must push a NULL and wait for ack
3461 mOutputSink.clear();
3462 mPipeSink.clear();
3463 mNormalSink.clear();
3464 return output;
3465}
3466
Andy Hungb17d24b2023-08-29 14:26:09 -07003467// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003468sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003469{
3470 if (mOutput == NULL) {
3471 return NULL;
3472 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003473 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003474}
3475
Andy Hung4b17e882023-07-07 13:47:37 -07003476uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003477{
3478 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3479}
3480
Andy Hung4b17e882023-07-07 13:47:37 -07003481status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003482{
3483 if (!isValidSyncEvent(event)) {
3484 return BAD_VALUE;
3485 }
3486
Andy Hungf8635b62023-08-31 16:13:39 -07003487 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003488
3489 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003490 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003491 if (event->triggerSession() == track->sessionId()) {
3492 (void) track->setSyncEvent(event);
3493 return NO_ERROR;
3494 }
3495 }
3496
3497 return NAME_NOT_FOUND;
3498}
3499
Andy Hung4b17e882023-07-07 13:47:37 -07003500bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003501{
3502 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3503}
3504
Andy Hung4b17e882023-07-07 13:47:37 -07003505void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003506 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003507{
Andy Hungfe726a62018-09-27 15:17:25 -07003508 // Miscellaneous track cleanup when removed from the active list,
3509 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003511 for (const auto& track : tracksToRemove) {
3512 if (track->isExternalTrack()) {
3513 // to track the speaker usage
3514 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003515 }
3516 }
Andy Hungfe726a62018-09-27 15:17:25 -07003517#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003518}
3519
Andy Hung4b17e882023-07-07 13:47:37 -07003520void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003521{
3522 if (!mMasterMute) {
3523 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003524 if (mOutDeviceTypeAddrs.empty()) {
3525 ALOGD("ro.audio.silent is ignored since no output device is set");
3526 return;
3527 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003528 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003529 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3530 return;
3531 }
Eric Laurent81784c32012-11-19 14:55:58 -08003532 if (property_get("ro.audio.silent", value, "0") > 0) {
3533 char *endptr;
3534 unsigned long ul = strtoul(value, &endptr, 0);
3535 if (*endptr == '\0' && ul != 0) {
3536 ALOGD("Silence is golden");
3537 // The setprop command will not allow a property to be changed after
3538 // the first time it is set, so we don't have to worry about un-muting.
3539 setMasterMute_l(true);
3540 }
3541 }
3542 }
3543}
3544
3545// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003546ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003547{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003548 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003549 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003550 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003551 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003552
3553 // If an NBAIO sink is present, use it to write the normal mixer's submix
3554 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003555
Andy Hung010a1a12014-03-13 13:57:33 -07003556 const size_t count = mBytesRemaining / mFrameSize;
3557
Simon Wilson2d590962012-11-29 15:18:50 -08003558 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003559 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003560 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003561 if (screenState != mScreenState) {
3562 mScreenState = screenState;
3563 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3564 if (pipe != NULL) {
3565 pipe->setAvgFrames((mScreenState & 1) ?
3566 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3567 }
3568 }
Andy Hung010a1a12014-03-13 13:57:33 -07003569 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003570 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003571
Eric Laurent81784c32012-11-19 14:55:58 -08003572 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003573 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003574
Andy Hung8946a282018-04-19 20:04:56 -07003575#ifdef TEE_SINK
3576 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3577#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003578 } else {
3579 bytesWritten = framesWritten;
3580 }
3581 // otherwise use the HAL / AudioStreamOut directly
3582 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003583 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003584
Eric Laurentbfb1b832013-01-07 09:53:42 -08003585 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003586 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3587 mWriteAckSequence += 2;
3588 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003589 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003590 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003592 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003593 // FIXME We should have an implementation of timestamps for direct output threads.
3594 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003595 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003596 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003597
Eric Laurentbfb1b832013-01-07 09:53:42 -08003598 if (mUseAsyncWrite &&
3599 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3600 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003601 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003602 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003603 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003604 }
Eric Laurent81784c32012-11-19 14:55:58 -08003605 }
3606
Eric Laurent81784c32012-11-19 14:55:58 -08003607 mNumWrites++;
3608 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003609 if (mStandby) {
3610 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003611 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003612 mStandby = false;
3613 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614 return bytesWritten;
3615}
3616
Andy Hungb17d24b2023-08-29 14:26:09 -07003617// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003618void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003619 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003620{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003621 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003622 if (outputSink != nullptr) {
3623 outputSink->startMelComputation(processor);
3624 }
Vlad Popab042ee62022-10-20 18:05:00 +02003625}
3626
Andy Hungb17d24b2023-08-29 14:26:09 -07003627// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003628void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003629{
3630 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003631 if (outputSink != nullptr) {
3632 outputSink->stopMelComputation();
3633 }
Vlad Popab042ee62022-10-20 18:05:00 +02003634}
3635
Andy Hung4b17e882023-07-07 13:47:37 -07003636void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003637{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003638 bool supportsDrain = false;
3639 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003640 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3641 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003642 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3643 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003644 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003645 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003646 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003647 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003648 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 }
3650}
3651
Andy Hung4b17e882023-07-07 13:47:37 -07003652void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003653{
Eric Laurent275e8e92014-11-30 15:14:47 -08003654 {
Andy Hungf8635b62023-08-31 16:13:39 -07003655 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003656 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003657 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003658 track->invalidate();
3659 }
Andy Hungdae27702016-10-31 14:01:16 -07003660 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3661 // After we exit there are no more track changes sent to BatteryNotifier
3662 // because that requires an active threadLoop.
3663 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3664 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003665 }
Eric Laurent81784c32012-11-19 14:55:58 -08003666}
3667
3668/*
3669The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003670 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003671 - mActiveSleepTimeUs from activeSleepTimeUs()
3672 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003673 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3674 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003675 - maxPeriod from frame count and sample rate (MIXER only)
3676
3677The parameters that affect these derived values are:
3678 - frame count
3679 - frame size
3680 - sample rate
3681 - device type: A2DP or not
3682 - device latency
3683 - format: PCM or not
3684 - active sleep time
3685 - idle sleep time
3686*/
3687
Andy Hung4b17e882023-07-07 13:47:37 -07003688void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003689{
Andy Hung25c2dac2014-02-27 14:56:00 -08003690 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003691 mActiveSleepTimeUs = activeSleepTimeUs();
3692 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003693
Andy Hungd58c4732023-07-20 21:31:38 -07003694 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003695
Eric Laurent42537be2016-01-08 17:16:42 -08003696 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3697 // truncating audio when going to standby.
Andy Hung94dfbb42023-09-06 19:41:47 -07003698 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003699 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3700 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3701 }
3702 }
Eric Laurent81784c32012-11-19 14:55:58 -08003703}
3704
Andy Hung4b17e882023-07-07 13:47:37 -07003705bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003706{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003707 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003708 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003709 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003710 size_t size = mTracks.size();
3711 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003712 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003713 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003714 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003715 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003716 }
3717 }
Eric Laurent13084622016-05-17 10:51:49 -07003718 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003719}
3720
Andy Hung4b17e882023-07-07 13:47:37 -07003721void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003722{
Andy Hungf8635b62023-08-31 16:13:39 -07003723 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003724 invalidateTracks_l(streamType);
3725}
3726
Andy Hung4b17e882023-07-07 13:47:37 -07003727void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07003728 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003729 invalidateTracks_l(portIds);
3730}
3731
Andy Hung4b17e882023-07-07 13:47:37 -07003732bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003733 bool trackMatch = false;
3734 const size_t size = mTracks.size();
3735 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003736 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003737 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3738 t->invalidate();
3739 portIds.erase(t->portId());
3740 trackMatch = true;
3741 }
3742 if (portIds.empty()) {
3743 break;
3744 }
3745 }
3746 return trackMatch;
3747}
3748
jiabinf042b9b2021-05-07 23:46:28 +00003749// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003750IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003751 audio_port_handle_t trackPortId) {
3752 for (size_t i = 0; i < mTracks.size(); i++) {
3753 if (mTracks[i]->portId() == trackPortId) {
3754 return mTracks[i].get();
3755 }
3756 }
3757 return nullptr;
3758}
3759
Andy Hung4b17e882023-07-07 13:47:37 -07003760status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003761{
Glenn Kastend848eb42016-03-08 13:42:11 -08003762 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003763 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003764 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003765
Andy Hungd3639922022-04-28 18:00:49 -07003766 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003767 if (!audio_is_global_session(session)) {
3768 // player sessions on a spatializer output will use a dedicated input buffer and
3769 // will either output multi channel to mEffectBuffer if the track is spatilaized
3770 // or stereo to mPostSpatializerBuffer if not spatialized.
3771 uint32_t channelMask;
3772 bool isSessionSpatialized =
3773 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3774 if (isSessionSpatialized) {
3775 channelMask = mMixerChannelMask;
3776 } else {
3777 channelMask = mChannelMask;
3778 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003779 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003780 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003781 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003782 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003783 &halInBuffer);
3784 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003785
Andy Hung7535ed92023-07-17 17:05:00 -07003786 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003787 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3788 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3789 &halOutBuffer);
3790 if (result != OK) return result;
3791
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003792 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003793
Mikhail Naganov022b9952017-01-04 16:36:51 -08003794 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3795 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003796 } else {
3797 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3798 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3799 // mPostSpatializerBuffer as output buffer
3800 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003801 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003802 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3803 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003804 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003805 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3806 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003807
Eric Laurentb62d0362021-10-26 17:40:18 +02003808 if (session == AUDIO_SESSION_DEVICE) {
3809 halInBuffer = halOutBuffer;
3810 }
3811 }
3812 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003813 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003814 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3815 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3816 &halInBuffer);
3817 if (result != OK) return result;
3818 halOutBuffer = halInBuffer;
3819 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3820 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003821 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003822 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003823 // Only one effect chain can be present in direct output thread and it uses
3824 // the sink buffer as input
3825 if (mType != DIRECT) {
3826 size_t numSamples = mNormalFrameCount
3827 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3828 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003829 const status_t allocateStatus =
3830 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003831 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003832 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003833 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003834
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003835 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003836 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3837 buffer, session);
3838 }
3839 }
3840 }
3841
3842 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003843 // Attach all tracks with same session ID to this chain.
3844 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003845 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003846 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003847 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3848 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003849 track->setMainBuffer(buffer);
3850 chain->incTrackCnt();
3851 }
3852 }
3853
3854 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003855 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003856 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003857 ALOGV("addEffectChain_l() activating track %p on session %d",
3858 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003859 chain->incActiveTrackCnt();
3860 }
3861 }
3862 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003863
Eric Laurentaaa44472014-09-12 17:41:50 -07003864 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003865 chain->setInBuffer(halInBuffer);
3866 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003867 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3868 // chains list in order to be processed last as it contains output device effects.
3869 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3870 // processing effects specific to an output stream before effects applied to all streams
3871 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003872 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3873 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003874 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003875 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003876 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003877 // Effect chain for other sessions are inserted at beginning of effect
3878 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003879 // sessions is not important.
3880 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003881 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3882 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003883 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003884 size_t size = mEffectChains.size();
3885 size_t i = 0;
3886 for (i = 0; i < size; i++) {
3887 if (mEffectChains[i]->sessionId() < session) {
3888 break;
3889 }
3890 }
3891 mEffectChains.insertAt(chain, i);
3892 checkSuspendOnAddEffectChain_l(chain);
3893
3894 return NO_ERROR;
3895}
3896
Andy Hung4b17e882023-07-07 13:47:37 -07003897size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003898{
Glenn Kastend848eb42016-03-08 13:42:11 -08003899 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003900
3901 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3902
3903 for (size_t i = 0; i < mEffectChains.size(); i++) {
3904 if (chain == mEffectChains[i]) {
3905 mEffectChains.removeAt(i);
3906 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003907 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003908 if (session == track->sessionId()) {
3909 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3910 chain.get(), session);
3911 chain->decActiveTrackCnt();
3912 }
3913 }
3914
3915 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003916 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003917 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003918 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003919 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003920 chain->decTrackCnt();
3921 }
3922 }
3923 break;
3924 }
3925 }
3926 return mEffectChains.size();
3927}
3928
Andy Hung4b17e882023-07-07 13:47:37 -07003929status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003930 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003931{
Andy Hungf8635b62023-08-31 16:13:39 -07003932 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003933 return attachAuxEffect_l(track, EffectId);
3934}
3935
Andy Hung4b17e882023-07-07 13:47:37 -07003936status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003937 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003938{
3939 status_t status = NO_ERROR;
3940
3941 if (EffectId == 0) {
3942 track->setAuxBuffer(0, NULL);
3943 } else {
3944 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003945 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003946 if (effect != 0) {
3947 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3948 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3949 } else {
3950 status = INVALID_OPERATION;
3951 }
3952 } else {
3953 status = BAD_VALUE;
3954 }
3955 }
3956 return status;
3957}
3958
Andy Hung4b17e882023-07-07 13:47:37 -07003959void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003960{
3961 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003962 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003963 if (track->auxEffectId() == effectId) {
3964 attachAuxEffect_l(track, 0);
3965 }
3966 }
3967}
3968
Andy Hung4b17e882023-07-07 13:47:37 -07003969bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003970NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003971{
Andy Hung78d8d952023-05-30 18:10:23 -07003972 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003973
Andy Hung45a38f22023-10-03 10:49:34 -07003974 if (mType == SPATIALIZER) {
3975 const pid_t tid = getTid();
3976 if (tid == -1) { // odd: we are here, we must be a running thread.
3977 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3978 } else {
3979 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3980 if (priorityBoost > 0) {
3981 stream()->setHalThreadPriority(priorityBoost);
3982 }
3983 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003984 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3985 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3986 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3987 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3988 // only on ARC.
3989 const pid_t tid = getTid();
3990 if (tid == -1) {
3991 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
3992 } else {
3993 const status_t status = requestPriority(getpid(),
3994 tid,
3995 kPriorityPlaybackThreadArc,
3996 false /* isForApp */,
3997 true /* asynchronous */);
3998 if (status != OK) {
3999 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4000 status);
4001 } else {
4002 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4003 }
4004 }
Andy Hung45a38f22023-10-03 10:49:34 -07004005 }
4006
Andy Hung11e74242023-06-26 19:20:57 -07004007 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004008
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004009 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004010 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004011
4012 // MIXER
4013 nsecs_t lastWarning = 0;
4014
4015 // DUPLICATING
4016 // FIXME could this be made local to while loop?
4017 writeFrames = 0;
4018
4019 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004020 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004021
Andy Hungd3639922022-04-28 18:00:49 -07004022 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004023 sleepTimeShift = 0;
4024 }
4025
4026 CpuStats cpuStats;
4027 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4028
4029 acquireWakeLock();
4030
Glenn Kasteneef598c2017-04-03 14:41:13 -07004031 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4032 // thread associated with this PlaybackThread.
4033 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4034 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004035 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4036 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004037 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004038 const char *logString = NULL;
4039
rago1bb90822017-05-02 18:31:48 -07004040 // Estimated time for next buffer to be written to hal. This is used only on
4041 // suspended mode (for now) to help schedule the wait time until next iteration.
4042 nsecs_t timeLoopNextNs = 0;
4043
Eric Laurent664539d2013-09-23 18:24:31 -07004044 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004045
Andy Hung2dbffc22018-08-08 18:50:41 -07004046 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004047
Eric Laurentb3f315a2021-07-13 15:09:05 +02004048 sendCheckOutputStageEffectsEvent();
4049
Andy Hung446f4df2019-02-21 12:26:41 -08004050 // loopCount is used for statistics and diagnostics.
4051 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004052 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004053 // Log merge requests are performed during AudioFlinger binder transactions, but
4054 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07004055 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004056
Eric Laurent81784c32012-11-19 14:55:58 -08004057 cpuStats.sample(myName);
4058
Andy Hung116bc262023-06-20 18:56:17 -07004059 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004060 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004061 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07004062 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004063
Andy Hung2dbffc22018-08-08 18:50:41 -07004064 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4065 //
Andy Hungb17d24b2023-08-29 14:26:09 -07004066 // Note: we access outDeviceTypes() outside of mutex().
Andy Hung94dfbb42023-09-06 19:41:47 -07004067 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004068 // Here, we try for the AF lock, but do not block on it as the latency
4069 // is more informational.
Andy Hung85a07452023-08-28 18:36:53 -07004070 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd25fe392023-07-13 16:52:46 -07004071 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004072 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004073 status_t status = INVALID_OPERATION;
4074 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07004075 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07004076 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004077 && swPatches.size() > 0) {
4078 status = swPatches[0].getLatencyMs_l(&latencyMs);
4079 downstreamPatchHandle = swPatches[0].getPatchHandle();
4080 }
4081 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004082 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004083 lastDownstreamPatchHandle = downstreamPatchHandle;
4084 }
4085 if (status == OK) {
4086 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004087 // latency of 5 seconds).
4088 const double minLatency = 0., maxLatency = 5000.;
4089 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004090 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004091 } else {
4092 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004093 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004094 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004095 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004096 }
Andy Hung7535ed92023-07-17 17:05:00 -07004097 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004098 }
4099 } else {
4100 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4101 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004102 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004103 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4104 }
4105 }
4106
Eric Laurentb3f315a2021-07-13 15:09:05 +02004107 if (mCheckOutputStageEffects.exchange(false)) {
4108 checkOutputStageEffects();
4109 }
4110
Vlad Popa7e81cea2023-01-19 16:34:16 +01004111 MetadataUpdate metadataUpdate;
Andy Hungb17d24b2023-08-29 14:26:09 -07004112 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004113
Andy Hungb17d24b2023-08-29 14:26:09 -07004114 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004115
Eric Laurent021cf962014-05-13 10:18:14 -07004116 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004117 if (mCheckOutputStageEffects.load()) {
4118 continue;
4119 }
Eric Laurent10351942014-05-08 18:49:52 -07004120
Andy Hungb17d24b2023-08-29 14:26:09 -07004121 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004122 if (logString != NULL) {
4123 mNBLogWriter->logTimestamp();
4124 mNBLogWriter->log(logString);
4125 logString = NULL;
4126 }
4127
Dean Wheatley12473e92021-03-18 23:00:55 +11004128 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004129
Eric Laurent81784c32012-11-19 14:55:58 -08004130 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004131 if (mSignalPending) {
4132 // A signal was raised while we were unlocked
4133 mSignalPending = false;
4134 } else if (waitingAsyncCallback_l()) {
4135 if (exitPending()) {
4136 break;
4137 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004138 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004139 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004140 releaseWakeLock_l();
4141 released = true;
4142 }
Andy Hung10cbff12017-02-21 17:30:14 -08004143
4144 const int64_t waitNs = computeWaitTimeNs_l();
4145 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungb17d24b2023-08-29 14:26:09 -07004146 std::cv_status cvstatus =
4147 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4148 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004149 mSignalPending = true; // if timeout recheck everything
4150 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004151 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004152 if (released) {
4153 acquireWakeLock_l();
4154 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004155 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4156 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004157
4158 continue;
4159 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004160 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004161 isSuspended()) {
4162 // put audio hardware into standby after short delay
4163 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004164
4165 threadLoop_standby();
4166
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004167 // This is where we go into standby
4168 if (!mStandby) {
4169 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004170 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004171 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004172 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004173 }
Andy Hungd0979812019-02-21 15:51:44 -08004174 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004175 }
4176
Eric Tan39ec8d62018-07-24 09:49:29 -07004177 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004178 // we're about to wait, flush the binder command buffer
4179 IPCThreadState::self()->flushCommands();
4180
4181 clearOutputTracks();
4182
4183 if (exitPending()) {
4184 break;
4185 }
4186
4187 releaseWakeLock_l();
4188 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004189 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -07004190 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004191 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004192 acquireWakeLock_l();
4193
4194 mMixerStatus = MIXER_IDLE;
4195 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4196 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004197 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004198 checkSilentMode_l();
4199
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004200 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4201 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004202 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004203 sleepTimeShift = 0;
4204 }
4205
4206 continue;
4207 }
4208 }
Eric Laurent81784c32012-11-19 14:55:58 -08004209 // mMixerStatusIgnoringFastTracks is also updated internally
4210 mMixerStatus = prepareTracks_l(&tracksToRemove);
4211
Andy Hung94dfbb42023-09-06 19:41:47 -07004212 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004213
Vlad Popa7e81cea2023-01-19 16:34:16 +01004214 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004215
Andy Hungf302e812024-01-26 11:55:15 -08004216 // Acquire a local copy of active tracks with lock (release w/o lock).
4217 //
4218 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4219 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4220 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4221 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4222
4223 setHalLatencyMode_l();
4224
4225 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4226 // so this is done before we lock our effect chains.
4227 for (const auto& track : mActiveTracks) {
4228 track->updateTeePatches_l();
4229 }
4230
4231 // signal actual start of output stream when the render position reported by
4232 // the kernel starts moving.
4233 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4234 && (mKernelPositionOnStandby
4235 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4236 mHalStarted = true;
4237 mWaitHalStartCV.notify_all();
4238 }
4239
Eric Laurent81784c32012-11-19 14:55:58 -08004240 // prevent any changes in effect chain list and in each effect chain
4241 // during mixing and effect process as the audio buffers could be deleted
4242 // or modified if an effect is created or deleted
4243 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004244
4245 // Determine which session to pick up haptic data.
4246 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004247 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004248 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004249 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004250 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004251 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004252 if (effectChain != nullptr
4253 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004254 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004255 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004256 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004257 break;
4258 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004259 if (activeHapticSessionId == AUDIO_SESSION_NONE
4260 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004261 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004262 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004263 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004264 }
4265 }
4266 }
Andy Hungb17d24b2023-08-29 14:26:09 -07004267 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004268
Eric Laurentbfb1b832013-01-07 09:53:42 -08004269 if (mBytesRemaining == 0) {
4270 mCurrentWriteLength = 0;
4271 if (mMixerStatus == MIXER_TRACKS_READY) {
4272 // threadLoop_mix() sets mCurrentWriteLength
4273 threadLoop_mix();
4274 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4275 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004276 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004277 // must be written to HAL
4278 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004279 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004280 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004281
4282 // Tally underrun frames as we are inserting 0s here.
4283 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004284 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004285 && !track->isStopped()
4286 && !track->isPaused()
4287 && !track->isTerminated()) {
4288 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4289 __func__, track->id(), track->getTrackStateAsString(),
4290 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004291 track->audioTrackServerProxy()->tallyUnderrunFrames(
4292 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004293 }
4294 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004295 }
4296 }
Andy Hung98ef9782014-03-04 14:46:50 -08004297 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004298 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004299 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004300 // or mSinkBuffer (if there are no effects and there is no data already copied to
4301 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004302 //
4303 // This is done pre-effects computation; if effects change to
4304 // support higher precision, this needs to move.
4305 //
4306 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004307 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004308 uint32_t mixerChannelCount = mEffectBufferValid ?
4309 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004310 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004311 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4312 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4313
David Li88ee0902022-06-22 10:01:21 +08004314 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4315 // do these processes after effects are applied.
4316 if (!mEffectBufferValid) {
4317 // mono blend occurs for mixer threads only (not direct or offloaded)
4318 // and is handled here if we're going directly to the sink.
4319 if (requireMonoBlend()) {
4320 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4321 mNormalFrameCount, true /*limit*/);
4322 }
Andy Hung2ddee192015-12-18 17:34:44 -08004323
David Li88ee0902022-06-22 10:01:21 +08004324 if (!hasFastMixer()) {
4325 // Balance must take effect after mono conversion.
4326 // We do it here if there is no FastMixer.
4327 // mBalance detects zero balance within the class for speed
4328 // (not needed here).
4329 mBalance.setBalance(mMasterBalance.load());
4330 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4331 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004332 }
4333
Andy Hung98ef9782014-03-04 14:46:50 -08004334 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004335 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004336
4337 // If we're going directly to the sink and there are haptic channels,
4338 // we should adjust channels as the sample data is partially interleaved
4339 // in this case.
4340 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4341 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4342 mChannelCount + mHapticChannelCount,
4343 audio_bytes_per_sample(format),
4344 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4345 }
Andy Hung98ef9782014-03-04 14:46:50 -08004346 }
4347
Eric Laurentbfb1b832013-01-07 09:53:42 -08004348 mBytesRemaining = mCurrentWriteLength;
4349 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004350 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4351 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4352 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4353 mBytesWritten += mBytesRemaining;
4354 mFramesWritten += framesRemaining;
4355 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 mBytesRemaining = 0;
4357 }
Eric Laurent81784c32012-11-19 14:55:58 -08004358
Eric Laurentbfb1b832013-01-07 09:53:42 -08004359 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004360 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004361 for (size_t i = 0; i < effectChains.size(); i ++) {
4362 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004363 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004364 if (activeHapticSessionId != AUDIO_SESSION_NONE
4365 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004366 // Haptic data is active in this case, copy it directly from
4367 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004368 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4369 audio_channel_count_from_out_mask(mMixerChannelMask) :
4370 mChannelCount;
4371 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4372 hapticSessionChannelCount = mChannelCount;
4373 }
4374
jiabin47affe52019-04-04 18:02:07 -07004375 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004376 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004377 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004378 memcpy_by_audio_format(
4379 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004380 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004381 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004382 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004383 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004384 }
Eric Laurent81784c32012-11-19 14:55:58 -08004385 }
4386 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004387 // Process effect chains for offloaded thread even if no audio
4388 // was read from audio track: process only updates effect state
4389 // and thus does have to be synchronized with audio writes but may have
4390 // to be called while waiting for async write callback
4391 if (mType == OFFLOAD) {
4392 for (size_t i = 0; i < effectChains.size(); i ++) {
4393 effectChains[i]->process_l();
4394 }
4395 }
Eric Laurent81784c32012-11-19 14:55:58 -08004396
Andy Hung98ef9782014-03-04 14:46:50 -08004397 // Only if the Effects buffer is enabled and there is data in the
4398 // Effects buffer (buffer valid), we need to
4399 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004400 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004401 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004402 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004403 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004404 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004405 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004406 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004407 }
4408
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004409 if (!hasFastMixer()) {
4410 // Balance must take effect after mono conversion.
4411 // We do it here if there is no FastMixer.
4412 // mBalance detects zero balance within the class for speed (not needed here).
4413 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004414 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004415 }
4416
Eric Laurentb62d0362021-10-26 17:40:18 +02004417 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4418 // mPostSpatializerBuffer if the haptics track is spatialized.
4419 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4420 // For other thread types, the haptics channels are already in mEffectBuffer.
4421 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4422 const size_t srcBufferSize = mNormalFrameCount *
4423 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4424 mEffectBufferFormat);
4425 const size_t dstBufferSize = mNormalFrameCount
4426 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4427
4428 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4429 mEffectBufferFormat,
4430 (uint8_t*)mEffectBuffer + srcBufferSize,
4431 mEffectBufferFormat,
4432 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004433 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004434 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4435 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4436 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4437 // Clamp PCM float values more than this distance from 0 to insulate
4438 // a HAL which doesn't handle NaN correctly.
4439 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4440 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4441 static_cast<const float*>(effectBuffer),
4442 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4443 } else {
4444 memcpy_by_audio_format(mSinkBuffer, mFormat,
4445 effectBuffer, mEffectBufferFormat, framesToCopy);
4446 }
jiabin245cdd92018-12-07 17:55:15 -08004447 // The sample data is partially interleaved when haptic channels exist,
4448 // we need to adjust channels here.
4449 if (mHapticChannelCount > 0) {
4450 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4451 mChannelCount + mHapticChannelCount,
4452 audio_bytes_per_sample(mFormat),
4453 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4454 }
Andy Hung98ef9782014-03-04 14:46:50 -08004455 }
4456
Eric Laurent81784c32012-11-19 14:55:58 -08004457 // enable changes in effect chain
4458 unlockEffectChains(effectChains);
4459
Vlad Popafce10862023-02-03 10:37:07 +01004460 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004461 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004462 metadataUpdate.playbackMetadataUpdate);
4463 }
4464
Eric Laurentbfb1b832013-01-07 09:53:42 -08004465 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004466 // mSleepTimeUs == 0 means we must write to audio hardware
4467 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004468 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004469 // writePeriodNs is updated >= 0 when ret > 0.
4470 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004472 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004473 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004474 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004475 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004476 if (ret < 0) {
4477 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004478 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479 mBytesWritten += ret;
4480 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004481 const int64_t frames = ret / mFrameSize;
4482 mFramesWritten += frames;
4483
4484 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4485 // process information relating to write time.
4486 if (audio_has_proportional_frames(mFormat)) {
4487 // we are in a continuous mixing cycle
4488 if (mMixerStatus == MIXER_TRACKS_READY &&
4489 loopCount == lastLoopCountWritten + 1) {
4490
4491 const double jitterMs =
4492 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4493 {frames, writePeriodNs},
4494 {0, 0} /* lastTimestamp */, mSampleRate);
4495 const double processMs =
4496 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4497
Andy Hungf8635b62023-08-31 16:13:39 -07004498 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004499 mIoJitterMs.add(jitterMs);
4500 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004501
4502 if (mPipeSink.get() != nullptr) {
4503 // Using the Monopipe availableToWrite, we estimate the current
4504 // buffer size.
4505 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4506 const ssize_t
4507 availableToWrite = mPipeSink->availableToWrite();
4508 const size_t pipeFrames = monoPipe->maxFrames();
4509 const size_t
4510 remainingFrames = pipeFrames - max(availableToWrite, 0);
4511 mMonopipePipeDepthStats.add(remainingFrames);
4512 }
Andy Hung446f4df2019-02-21 12:26:41 -08004513 }
4514
4515 // write blocked detection
4516 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004517 if ((mType == MIXER || mType == SPATIALIZER)
4518 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004519 mNumDelayedWrites++;
4520 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4521 ATRACE_NAME("underrun");
4522 ALOGW("write blocked for %lld msecs, "
4523 "%d delayed writes, thread %d",
4524 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4525 mNumDelayedWrites, mId);
4526 lastWarning = lastIoEndNs;
4527 }
4528 }
4529 }
4530 // update timing info.
4531 mLastIoBeginNs = lastIoBeginNs;
4532 mLastIoEndNs = lastIoEndNs;
4533 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004534 }
4535 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4536 (mMixerStatus == MIXER_DRAIN_ALL)) {
4537 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004538 }
Andy Hungd3639922022-04-28 18:00:49 -07004539 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004540
4541 if (mThreadThrottle
4542 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004543 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004544 // Limit MixerThread data processing to no more than twice the
4545 // expected processing rate.
4546 //
4547 // This helps prevent underruns with NuPlayer and other applications
4548 // which may set up buffers that are close to the minimum size, or use
4549 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4550 //
4551 // The throttle smooths out sudden large data drains from the device,
4552 // e.g. when it comes out of standby, which often causes problems with
4553 // (1) mixer threads without a fast mixer (which has its own warm-up)
4554 // (2) minimum buffer sized tracks (even if the track is full,
4555 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004556 //
4557 // Total time spent in last processing cycle equals time spent in
4558 // 1. threadLoop_write, as well as time spent in
4559 // 2. threadLoop_mix (significant for heavy mixing, especially
4560 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004561
Andy Hung446f4df2019-02-21 12:26:41 -08004562 // it's OK if deltaMs is an overestimate.
4563
4564 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004565
Ivan Lozanoea04d392017-11-07 14:37:07 -08004566 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004567 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004568 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004569
Andy Hung08fb1742015-05-31 23:22:10 -07004570 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004571 // notify of throttle start on verbose log
4572 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4573 "mixer(%p) throttle begin:"
4574 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004575 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004576 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004577 // Throttle must be attributed to the previous mixer loop's write time
4578 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004579 // This also ensures proper timing statistics.
4580 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004581 } else {
4582 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4583 if (diff > 0) {
4584 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004585 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004586 ALOGD_IF(!isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004587 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004588 !isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004589 outDeviceTypes_l(),
4590 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004591 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004592 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4593 }
Andy Hung08fb1742015-05-31 23:22:10 -07004594 }
4595 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004596 }
Eric Laurent81784c32012-11-19 14:55:58 -08004597
Eric Laurentbfb1b832013-01-07 09:53:42 -08004598 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004599 ATRACE_BEGIN("sleep");
Andy Hungb17d24b2023-08-29 14:26:09 -07004600 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004601 // suspended requires accurate metering of sleep time.
4602 if (isSuspended()) {
4603 // advance by expected sleepTime
4604 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4605 const nsecs_t nowNs = systemTime();
4606
4607 // compute expected next time vs current time.
4608 // (negative deltas are treated as delays).
4609 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4610 if (deltaNs < -kMaxNextBufferDelayNs) {
4611 // Delays longer than the max allowed trigger a reset.
4612 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4613 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4614 timeLoopNextNs = nowNs + deltaNs;
4615 } else if (deltaNs < 0) {
4616 // Delays within the max delay allowed: zero the delta/sleepTime
4617 // to help the system catch up in the next iteration(s)
4618 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4619 deltaNs = 0;
4620 }
4621 // update sleep time (which is >= 0)
4622 mSleepTimeUs = deltaNs / 1000;
4623 }
Eric Laurente93cc032016-05-05 10:15:10 -07004624 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004625 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004626 }
Glenn Kastene7754022014-10-31 12:11:26 -07004627 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004628 }
Eric Laurent81784c32012-11-19 14:55:58 -08004629 }
4630
4631 // Finally let go of removed track(s), without the lock held
4632 // since we can't guarantee the destructors won't acquire that
4633 // same lock. This will also mutate and push a new fast mixer state.
4634 threadLoop_removeTracks(tracksToRemove);
4635 tracksToRemove.clear();
4636
4637 // FIXME I don't understand the need for this here;
4638 // it was in the original code but maybe the
4639 // assignment in saveOutputTracks() makes this unnecessary?
4640 clearOutputTracks();
4641
4642 // Effect chains will be actually deleted here if they were removed from
4643 // mEffectChains list during mixing or effects processing
4644 effectChains.clear();
4645
4646 // FIXME Note that the above .clear() is no longer necessary since effectChains
4647 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004648
4649 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004650 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004651 mThreadloopExecutor.process(); // process any remaining deferred actions.
4652 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004653
Eric Laurentbfb1b832013-01-07 09:53:42 -08004654 threadLoop_exit();
4655
Eric Laurentcf817a22014-08-04 20:36:31 -07004656 if (!mStandby) {
4657 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004658 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004659 }
4660
4661 releaseWakeLock();
4662
4663 ALOGV("Thread %p type %d exiting", this, mType);
4664 return false;
4665}
4666
Andy Hung4b17e882023-07-07 13:47:37 -07004667void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004668{
Dean Wheatley12473e92021-03-18 23:00:55 +11004669 if (mStandby) {
4670 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4671 return;
4672 } else if (mHwPaused) {
4673 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4674 return;
4675 }
4676
4677 // Gather the framesReleased counters for all active tracks,
4678 // and associate with the sink frames written out. We need
4679 // this to convert the sink timestamp to the track timestamp.
4680 bool kernelLocationUpdate = false;
4681 ExtendedTimestamp timestamp; // use private copy to fetch
4682
4683 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4684 // HAL may be draining some small duration buffered data for fade out.
4685 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4686 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4687 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4688 mSampleRate);
4689
Andy Hung94dfbb42023-09-06 19:41:47 -07004690 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004691 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4692 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4693 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4694 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4695 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4696 = correctedTimestamp.mFrames;
4697 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4698 = correctedTimestamp.mTimeNs;
4699 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4700 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4701 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4702
4703 // Note: Downstream latency only added if timestamp correction enabled.
4704 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4705 const int64_t newPosition =
4706 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4707 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4708 // prevent retrograde
4709 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4710 newPosition,
4711 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4712 - mSuspendedFrames));
4713 }
4714 }
4715
4716 // We always fetch the timestamp here because often the downstream
4717 // sink will block while writing.
4718
4719 // We keep track of the last valid kernel position in case we are in underrun
4720 // and the normal mixer period is the same as the fast mixer period, or there
4721 // is some error from the HAL.
4722 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4723 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4724 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4725 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4726 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4727
4728 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4729 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4730 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4731 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4732 }
4733
4734 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4735 kernelLocationUpdate = true;
4736 } else {
4737 ALOGVV("getTimestamp error - no valid kernel position");
4738 }
4739
4740 // copy over kernel info
4741 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4742 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4743 + mSuspendedFrames; // add frames discarded when suspended
4744 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4745 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4746 } else {
4747 mTimestampVerifier.error();
4748 }
4749
4750 // mFramesWritten for non-offloaded tracks are contiguous
4751 // even after standby() is called. This is useful for the track frame
4752 // to sink frame mapping.
4753 bool serverLocationUpdate = false;
4754 if (mFramesWritten != mLastFramesWritten) {
4755 serverLocationUpdate = true;
4756 mLastFramesWritten = mFramesWritten;
4757 }
4758 // Only update timestamps if there is a meaningful change.
4759 // Either the kernel timestamp must be valid or we have written something.
4760 if (kernelLocationUpdate || serverLocationUpdate) {
4761 if (serverLocationUpdate) {
4762 // use the time before we called the HAL write - it is a bit more accurate
4763 // to when the server last read data than the current time here.
4764 //
4765 // If we haven't written anything, mLastIoBeginNs will be -1
4766 // and we use systemTime().
4767 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4768 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung160664b2023-09-15 18:19:28 -07004769 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004770 }
4771
Andy Hung11e74242023-06-26 19:20:57 -07004772 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004773 if (!t->isFastTrack()) {
4774 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004775 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004776 mFramesWritten,
4777 mSampleRate,
4778 mTimestamp);
4779 }
4780 }
4781 }
4782
4783 if (audio_has_proportional_frames(mFormat)) {
4784 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4785 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4786 mLatencyMs.add(latencyMs);
4787 }
4788 }
4789#if 0
4790 // logFormat example
4791 if (z % 100 == 0) {
4792 timespec ts;
4793 clock_gettime(CLOCK_MONOTONIC, &ts);
4794 LOGT("This is an integer %d, this is a float %f, this is my "
4795 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4796 LOGT("A deceptive null-terminated string %\0");
4797 }
4798 ++z;
4799#endif
4800}
4801
Andy Hungb17d24b2023-08-29 14:26:09 -07004802// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07004803void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungb17d24b2023-08-29 14:26:09 -07004804NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004805{
Andy Hunga7187712023-12-05 17:28:17 -08004806 if (tracksToRemove.empty()) return;
4807
4808 // Block all incoming TrackHandle requests until we are finished with the release.
4809 setThreadBusy_l(true);
4810
Andy Hungfe726a62018-09-27 15:17:25 -07004811 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004812 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004813 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004814 if (chain != 0) {
4815 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4816 __func__, track->id(), chain.get(), track->sessionId());
4817 chain->decActiveTrackCnt();
4818 }
Andy Hunga7187712023-12-05 17:28:17 -08004819
Andy Hungfe726a62018-09-27 15:17:25 -07004820 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hunga7187712023-12-05 17:28:17 -08004821 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004822 if (track->isExternalTrack()) {
Andy Hunga7187712023-12-05 17:28:17 -08004823 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004824 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004825 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004826 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004827 }
Andy Hunga7187712023-12-05 17:28:17 -08004828 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004829 }
jiabineb3bda02020-06-30 14:07:03 -07004830 if (mHapticChannelCount > 0 &&
4831 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4832 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004833 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004834 // Unlock due to VibratorService will lock for this call and will
4835 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004836 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungb17d24b2023-08-29 14:26:09 -07004837 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004838
4839 // When the track is stop, set the haptic intensity as MUTE
4840 // for the HapticGenerator effect.
4841 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004842 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004843 }
jiabin245cdd92018-12-07 17:55:15 -08004844 }
Andy Hunga7187712023-12-05 17:28:17 -08004845
4846 // Under lock, the track is removed from the active tracks list.
4847 //
4848 // Once the track is no longer active, the TrackHandle may directly
4849 // modify it as the threadLoop() is no longer responsible for its maintenance.
4850 // Do not modify the track from threadLoop after the mutex is unlocked
4851 // if it is not active.
4852 mActiveTracks.remove(track);
4853
4854 if (track->isTerminated()) {
4855 // remove from our tracks vector
4856 removeTrack_l(track);
4857 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004858 }
Andy Hunga7187712023-12-05 17:28:17 -08004859
4860 // Allow incoming TrackHandle requests. We still hold the mutex,
4861 // so pending TrackHandle requests will occur after we unlock it.
4862 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004863}
Eric Laurent81784c32012-11-19 14:55:58 -08004864
Andy Hung4b17e882023-07-07 13:47:37 -07004865status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004866{
4867 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004868 ExtendedTimestamp ets;
4869 status_t status = mNormalSink->getTimestamp(ets);
4870 if (status == NO_ERROR) {
4871 status = ets.getBestTimestamp(&timestamp);
4872 }
4873 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004874 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004875 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004876 collectTimestamps_l();
4877 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4878 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004879 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004880 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4881 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4882 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4883 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4884 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004885 }
4886 return INVALID_OPERATION;
4887}
Eric Laurent1c333e22014-05-20 10:48:17 -07004888
Eric Laurenteab90452019-06-24 15:17:46 -07004889// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4890// still applied by the mixer.
4891// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4892// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4893// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004894status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004895{
4896 status_t result = NO_ERROR;
4897 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4898 if (*volume != mLeftVolFloat) {
4899 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004900 // HAL can return INVALID_OPERATION if operation is not supported.
4901 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004902 "Error when setting output stream volume: %d", result);
4903 if (result == NO_ERROR) {
4904 mLeftVolFloat = *volume;
4905 }
4906 }
4907 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4908 // remove stream volume contribution from software volume.
4909 if (mLeftVolFloat == *volume) {
4910 *volume = 1.0f;
4911 }
4912 }
4913 return result;
4914}
4915
Andy Hung4b17e882023-07-07 13:47:37 -07004916status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004917 audio_patch_handle_t *handle)
4918{
Andy Hungf60abce2016-08-26 11:37:54 -07004919 status_t status;
4920 if (property_get_bool("af.patch_park", false /* default_value */)) {
4921 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4922 // or if HAL does not properly lock against access.
4923 AutoPark<FastMixer> park(mFastMixer);
4924 status = PlaybackThread::createAudioPatch_l(patch, handle);
4925 } else {
4926 status = PlaybackThread::createAudioPatch_l(patch, handle);
4927 }
Eric Laurentb0463942022-12-20 16:31:10 +01004928
4929 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004930 return status;
4931}
4932
Andy Hung4b17e882023-07-07 13:47:37 -07004933status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004934 audio_patch_handle_t *handle)
4935{
4936 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004937
4938 // store new device and send to effects
4939 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004940 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004941 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004942 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4943 && !mOutput->audioHwDev->supportsAudioPatches(),
4944 "Enumerated device type(%#x) must not be used "
4945 "as it does not support audio patches",
4946 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004947 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004948 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4949 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004950 }
4951
François Gaffie0c280aa2018-07-25 10:02:15 +02004952 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004953#ifdef ADD_BATTERY_DATA
4954 // when changing the audio output device, call addBatteryData to notify
4955 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004956 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004957 uint32_t params = 0;
4958 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004959 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004960 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004961 }
4962
Eric Laurent054d9d32015-04-24 08:48:48 -07004963 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004964 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004965 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4966 }
4967
4968 if (params != 0) {
4969 addBatteryData(params);
4970 }
4971 }
4972#endif
4973
4974 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004975 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004976 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004977
jiabinc52b1ff2019-10-31 17:20:42 -07004978 // mPatch.num_sinks is not set when the thread is created so that
4979 // the first patch creation triggers an ioConfigChanged callback
4980 bool configChanged = (mPatch.num_sinks == 0) ||
4981 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004982 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004983 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004984 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004985
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004986 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004987 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4988 status = hwDevice->createAudioPatch(patch->num_sources,
4989 patch->sources,
4990 patch->num_sinks,
4991 patch->sinks,
4992 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004993 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004994 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004995 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004996 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004997 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004998
4999 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005000 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005001 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005002 // also dispatch to active AudioTracks for MediaMetrics
5003 for (const auto &track : mActiveTracks) {
5004 track->logEndInterval();
5005 track->logBeginInterval(patchSinksAsString);
5006 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005007
Eric Laurente8726fe2015-06-26 09:39:24 -07005008 if (configChanged) {
5009 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5010 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005011 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005012 mActiveTracks.setHasChanged();
5013
Eric Laurent1c333e22014-05-20 10:48:17 -07005014 return status;
5015}
5016
Andy Hung4b17e882023-07-07 13:47:37 -07005017status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005018{
Andy Hungf60abce2016-08-26 11:37:54 -07005019 status_t status;
5020 if (property_get_bool("af.patch_park", false /* default_value */)) {
5021 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5022 // or if HAL does not properly lock against access.
5023 AutoPark<FastMixer> park(mFastMixer);
5024 status = PlaybackThread::releaseAudioPatch_l(handle);
5025 } else {
5026 status = PlaybackThread::releaseAudioPatch_l(handle);
5027 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005028 return status;
5029}
5030
Andy Hung4b17e882023-07-07 13:47:37 -07005031status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005032{
5033 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005034
jiabinc52b1ff2019-10-31 17:20:42 -07005035 mPatch = audio_patch{};
5036 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005037
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005038 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005039 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5040 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005041 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005042 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005043 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005044 // Force meteadata update after a route change
5045 mActiveTracks.setHasChanged();
5046
Eric Laurent1c333e22014-05-20 10:48:17 -07005047 return status;
5048}
5049
Andy Hung4b17e882023-07-07 13:47:37 -07005050void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005051{
Andy Hungf8635b62023-08-31 16:13:39 -07005052 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005053 mTracks.add(track);
5054}
5055
Andy Hung4b17e882023-07-07 13:47:37 -07005056void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005057{
Andy Hungf8635b62023-08-31 16:13:39 -07005058 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005059 destroyTrack_l(track);
5060}
5061
Andy Hung4b17e882023-07-07 13:47:37 -07005062void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005063{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005064 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005065 config->role = AUDIO_PORT_ROLE_SOURCE;
5066 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5067 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005068 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5069 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5070 config->flags.output = mOutput->flags;
5071 }
Eric Laurent83b88082014-06-20 18:31:16 -07005072}
5073
Eric Laurent81784c32012-11-19 14:55:58 -08005074// ----------------------------------------------------------------------------
5075
Andy Hung4b17e882023-07-07 13:47:37 -07005076/* static */
5077sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07005078 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07005079 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07005080 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07005081}
5082
Andy Hung7535ed92023-07-17 17:05:00 -07005083MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005084 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07005085 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005086 // mAudioMixer below
5087 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005088 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005089 mFastMixerFutex(0),
5090 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005091 // mOutputSink below
5092 // mPipeSink below
5093 // mNormalSink below
5094{
jiabinc52b1ff2019-10-31 17:20:42 -07005095 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005096 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005097 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005098 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5099 mNormalFrameCount);
5100 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5101
Andy Hungfbfc3952015-01-15 13:33:51 -08005102 if (type == DUPLICATING) {
5103 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5104 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5105 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung7de02c92024-06-25 17:07:58 -07005106 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5107 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005108 return;
5109 }
Eric Laurent81784c32012-11-19 14:55:58 -08005110 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005111 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005112 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005113 const NBAIO_Format offers[1] = {Format_from_SR_C(
5114 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005115#if !LOG_NDEBUG
5116 ssize_t index =
5117#else
5118 (void)
5119#endif
5120 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005121 ALOG_ASSERT(index == 0);
5122
5123 // initialize fast mixer depending on configuration
5124 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005125 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005126 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005127 } else {
5128 switch (kUseFastMixer) {
5129 case FastMixer_Never:
5130 initFastMixer = false;
5131 break;
5132 case FastMixer_Always:
5133 initFastMixer = true;
5134 break;
5135 case FastMixer_Static:
5136 case FastMixer_Dynamic:
5137 initFastMixer = mFrameCount < mNormalFrameCount;
5138 break;
5139 }
5140 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5141 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5142 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005143 }
5144 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005145 audio_format_t fastMixerFormat;
5146 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5147 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5148 } else {
5149 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5150 }
5151 if (mFormat != fastMixerFormat) {
5152 // change our Sink format to accept our intermediate precision
5153 mFormat = fastMixerFormat;
5154 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005155 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005156 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5157 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5158 }
Eric Laurent81784c32012-11-19 14:55:58 -08005159
5160 // create a MonoPipe to connect our submix to FastMixer
5161 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005162
Andy Hung1258c1a2014-05-23 21:22:17 -07005163 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005164 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005165 format.mFormat = fastMixerFormat;
5166 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5167
Eric Laurent81784c32012-11-19 14:55:58 -08005168 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5169 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5170 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5171 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005172 const NBAIO_Format offersFast[1] = {format};
5173 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005174#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005175 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005176#else
5177 (void)
5178#endif
Andy Hung920f6572022-10-06 12:09:49 -07005179 monoPipe->negotiate(offersFast, std::size(offersFast),
5180 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005181 ALOG_ASSERT(index == 0);
5182 monoPipe->setAvgFrames((mScreenState & 1) ?
5183 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5184 mPipeSink = monoPipe;
5185
Eric Laurent81784c32012-11-19 14:55:58 -08005186 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005187 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005188 FastMixerStateQueue *sq = mFastMixer->sq();
5189#ifdef STATE_QUEUE_DUMP
5190 sq->setObserverDump(&mStateQueueObserverDump);
5191 sq->setMutatorDump(&mStateQueueMutatorDump);
5192#endif
5193 FastMixerState *state = sq->begin();
5194 FastTrack *fastTrack = &state->mFastTracks[0];
5195 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5196 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5197 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005198 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5199 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5200 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005201 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005202 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005203 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005204 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005205 fastTrack->mGeneration++;
5206 state->mFastTracksGen++;
5207 state->mTrackMask = 1;
5208 // fast mixer will use the HAL output sink
5209 state->mOutputSink = mOutputSink.get();
5210 state->mOutputSinkGen++;
5211 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005212 // specify sink channel mask when haptic channel mask present as it can not
5213 // be calculated directly from channel count
5214 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005215 ? AUDIO_CHANNEL_NONE
5216 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005217 state->mCommand = FastMixerState::COLD_IDLE;
5218 // already done in constructor initialization list
5219 //mFastMixerFutex = 0;
5220 state->mColdFutexAddr = &mFastMixerFutex;
5221 state->mColdGen++;
5222 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005223 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005224 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005225 sq->end();
5226 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5227
Eric Tan0513b5d2018-09-17 10:32:48 -07005228 NBLog::thread_info_t info;
5229 info.id = mId;
5230 info.type = NBLog::FASTMIXER;
5231 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5232
Eric Laurent81784c32012-11-19 14:55:58 -08005233 // start the fast mixer
5234 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5235 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005236 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005237 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005238
5239#ifdef AUDIO_WATCHDOG
5240 // create and start the watchdog
5241 mAudioWatchdog = new AudioWatchdog();
5242 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5243 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5244 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005245 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005246#endif
Andy Hung8946a282018-04-19 20:04:56 -07005247 } else {
5248#ifdef TEE_SINK
5249 // Only use the MixerThread tee if there is no FastMixer.
5250 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5251 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5252#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005253 }
5254
5255 switch (kUseFastMixer) {
5256 case FastMixer_Never:
5257 case FastMixer_Dynamic:
5258 mNormalSink = mOutputSink;
5259 break;
5260 case FastMixer_Always:
5261 mNormalSink = mPipeSink;
5262 break;
5263 case FastMixer_Static:
5264 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5265 break;
5266 }
Andy Hung7de02c92024-06-25 17:07:58 -07005267 // setMasterBalance needs to be called after the FastMixer
5268 // (if any) is set up, in order to deliver the balance settings to it.
5269 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005270}
5271
Andy Hung4b17e882023-07-07 13:47:37 -07005272MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005273{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005274 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005275 FastMixerStateQueue *sq = mFastMixer->sq();
5276 FastMixerState *state = sq->begin();
5277 if (state->mCommand == FastMixerState::COLD_IDLE) {
5278 int32_t old = android_atomic_inc(&mFastMixerFutex);
5279 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005280 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005281 }
5282 }
5283 state->mCommand = FastMixerState::EXIT;
5284 sq->end();
5285 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5286 mFastMixer->join();
5287 // Though the fast mixer thread has exited, it's state queue is still valid.
5288 // We'll use that extract the final state which contains one remaining fast track
5289 // corresponding to our sub-mix.
5290 state = sq->begin();
5291 ALOG_ASSERT(state->mTrackMask == 1);
5292 FastTrack *fastTrack = &state->mFastTracks[0];
5293 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5294 delete fastTrack->mBufferProvider;
5295 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005296 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005297#ifdef AUDIO_WATCHDOG
5298 if (mAudioWatchdog != 0) {
5299 mAudioWatchdog->requestExit();
5300 mAudioWatchdog->requestExitAndWait();
5301 mAudioWatchdog.clear();
5302 }
5303#endif
5304 }
Andy Hung7535ed92023-07-17 17:05:00 -07005305 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005306 delete mAudioMixer;
5307}
5308
Andy Hung4b17e882023-07-07 13:47:37 -07005309void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005310 PlaybackThread::onFirstRef();
5311
Andy Hungf8635b62023-08-31 16:13:39 -07005312 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005313 if (mOutput != nullptr && mOutput->stream != nullptr) {
5314 status_t status = mOutput->stream->setLatencyModeCallback(this);
5315 if (status != INVALID_OPERATION) {
5316 updateHalSupportedLatencyModes_l();
5317 }
5318 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5319 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5320 mBluetoothLatencyModesEnabled.store(
5321 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5322 }
5323}
Eric Laurent81784c32012-11-19 14:55:58 -08005324
Andy Hung4b17e882023-07-07 13:47:37 -07005325uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005326{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005327 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005328 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5329 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5330 }
5331 return latency;
5332}
5333
Andy Hung4b17e882023-07-07 13:47:37 -07005334ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005335{
5336 // FIXME we should only do one push per cycle; confirm this is true
5337 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005338 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005339 FastMixerStateQueue *sq = mFastMixer->sq();
5340 FastMixerState *state = sq->begin();
5341 if (state->mCommand != FastMixerState::MIX_WRITE &&
5342 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5343 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005344
5345 // FIXME workaround for first HAL write being CPU bound on some devices
5346 ATRACE_BEGIN("write");
5347 mOutput->write((char *)mSinkBuffer, 0);
5348 ATRACE_END();
5349
Eric Laurent81784c32012-11-19 14:55:58 -08005350 int32_t old = android_atomic_inc(&mFastMixerFutex);
5351 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005352 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005353 }
5354#ifdef AUDIO_WATCHDOG
5355 if (mAudioWatchdog != 0) {
5356 mAudioWatchdog->resume();
5357 }
5358#endif
5359 }
5360 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005361#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005362 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005363 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005364#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005365 sq->end();
5366 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5367 if (kUseFastMixer == FastMixer_Dynamic) {
5368 mNormalSink = mPipeSink;
5369 }
5370 } else {
5371 sq->end(false /*didModify*/);
5372 }
5373 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005374 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005375}
5376
Andy Hung4b17e882023-07-07 13:47:37 -07005377void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005378{
5379 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005380 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005381 FastMixerStateQueue *sq = mFastMixer->sq();
5382 FastMixerState *state = sq->begin();
5383 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005384 // Report any frames trapped in the Monopipe
5385 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5386 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5387 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5388 "monoPipeWritten:%lld monoPipeLeft:%lld",
5389 (long long)mFramesWritten, (long long)mSuspendedFrames,
5390 (long long)mPipeSink->framesWritten(), pipeFrames);
5391 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5392
Eric Laurent81784c32012-11-19 14:55:58 -08005393 state->mCommand = FastMixerState::COLD_IDLE;
5394 state->mColdFutexAddr = &mFastMixerFutex;
5395 state->mColdGen++;
5396 mFastMixerFutex = 0;
5397 sq->end();
5398 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5399 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5400 if (kUseFastMixer == FastMixer_Dynamic) {
5401 mNormalSink = mOutputSink;
5402 }
5403#ifdef AUDIO_WATCHDOG
5404 if (mAudioWatchdog != 0) {
5405 mAudioWatchdog->pause();
5406 }
5407#endif
5408 } else {
5409 sq->end(false /*didModify*/);
5410 }
5411 }
5412 PlaybackThread::threadLoop_standby();
5413}
5414
Andy Hung4b17e882023-07-07 13:47:37 -07005415bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416{
5417 return false;
5418}
5419
Andy Hung4b17e882023-07-07 13:47:37 -07005420bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005421{
5422 return !mStandby;
5423}
5424
Andy Hung4b17e882023-07-07 13:47:37 -07005425bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005426{
Andy Hungf8635b62023-08-31 16:13:39 -07005427 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005428 return waitingAsyncCallback_l();
5429}
5430
Eric Laurent81784c32012-11-19 14:55:58 -08005431// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005432void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005433{
Andy Hung160664b2023-09-15 18:19:28 -07005434 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5435 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005436 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005438 // discard any pending drain or write ack by incrementing sequence
5439 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5440 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005442 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5443 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005444 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005445 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005446 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005447}
5448
Andy Hung4b17e882023-07-07 13:47:37 -07005449void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005450{
5451 ALOGV("signal playback thread");
5452 broadcast_l();
5453}
5454
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005455void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005456{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005457 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005458 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5459 invalidateTracks((audio_stream_type_t)i);
5460 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005461 if (isHardError) {
5462 mAfThreadCallback->onHardError(allTrackPortIds);
5463 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005464}
5465
Andy Hung4b17e882023-07-07 13:47:37 -07005466void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005467{
Eric Laurent81784c32012-11-19 14:55:58 -08005468 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005469 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005470 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005471 // increase sleep time progressively when application underrun condition clears.
5472 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5473 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5474 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005475 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005476 sleepTimeShift--;
5477 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005478 mSleepTimeUs = 0;
5479 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005480 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005481
Eric Laurent81784c32012-11-19 14:55:58 -08005482}
5483
Andy Hung4b17e882023-07-07 13:47:37 -07005484void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005485{
5486 // If no tracks are ready, sleep once for the duration of an output
5487 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005488 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005489 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005490 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5491 // Using the Monopipe availableToWrite, we estimate the
5492 // sleep time to retry for more data (before we underrun).
5493 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5494 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5495 const size_t pipeFrames = monoPipe->maxFrames();
5496 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5497 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5498 const size_t framesDelay = std::min(
5499 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5500 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5501 pipeFrames, framesLeft, framesDelay);
5502 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5503 } else {
5504 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5505 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5506 mSleepTimeUs = kMinThreadSleepTimeUs;
5507 }
5508 // reduce sleep time in case of consecutive application underruns to avoid
5509 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5510 // duration we would end up writing less data than needed by the audio HAL if
5511 // the condition persists.
5512 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5513 sleepTimeShift++;
5514 }
Eric Laurent81784c32012-11-19 14:55:58 -08005515 }
5516 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005517 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005518 }
5519 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005520 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5521 // before effects processing or output.
5522 if (mMixerBufferValid) {
5523 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005524 if (mType == SPATIALIZER) {
5525 memset(mSinkBuffer, 0, mSinkBufferSize);
5526 }
Andy Hung98ef9782014-03-04 14:46:50 -08005527 } else {
5528 memset(mSinkBuffer, 0, mSinkBufferSize);
5529 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005530 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005531 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5532 "anticipated start");
5533 }
5534 // TODO add standby time extension fct of effect tail
5535}
5536
Andy Hungb17d24b2023-08-29 14:26:09 -07005537// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07005538PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005539 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005540{
Andy Hungc0691382018-09-12 18:01:57 -07005541 // clean up deleted track ids in AudioMixer before allocating new tracks
5542 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5543 // for each trackId, destroy it in the AudioMixer
5544 if (mAudioMixer->exists(trackId)) {
5545 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005546 }
5547 });
Andy Hungc0691382018-09-12 18:01:57 -07005548 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005549
5550 mixer_state mixerStatus = MIXER_IDLE;
5551 // find out which tracks need to be processed
5552 size_t count = mActiveTracks.size();
5553 size_t mixedTracks = 0;
5554 size_t tracksWithEffect = 0;
5555 // counts only _active_ fast tracks
5556 size_t fastTracks = 0;
5557 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5558
5559 float masterVolume = mMasterVolume;
5560 bool masterMute = mMasterMute;
5561
5562 if (masterMute) {
5563 masterVolume = 0;
5564 }
5565 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005566 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005567 if (chain != 0) {
5568 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005569 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005570 masterVolume = (float)((v + (1 << 23)) >> 24);
5571 chain.clear();
5572 }
5573
5574 // prepare a new state to push
5575 FastMixerStateQueue *sq = NULL;
5576 FastMixerState *state = NULL;
5577 bool didModify = false;
5578 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005579 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005580 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005581 sq = mFastMixer->sq();
5582 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005583 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005584 }
5585
Andy Hung69aed5f2014-02-25 17:24:40 -08005586 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005587 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005588
Andy Hungbd3b2b02018-05-21 10:53:11 -07005589 // DeferredOperations handles statistics after setting mixerStatus.
5590 class DeferredOperations {
5591 public:
Andy Hungea840382020-05-05 21:50:17 -07005592 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5593 : mMixerStatus(mixerStatus)
5594 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005595
5596 // when leaving scope, tally frames properly.
5597 ~DeferredOperations() {
5598 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5599 // because that is when the underrun occurs.
5600 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005601 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005602 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005603 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005604 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005605 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005606 }
5607 }
Andy Hungea840382020-05-05 21:50:17 -07005608 // send the max underrun frames for this mixer period
5609 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005610 }
5611
5612 // tallyUnderrunFrames() is called to update the track counters
5613 // with the number of underrun frames for a particular mixer period.
5614 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005615 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005616 mUnderrunFrames.emplace_back(track, underrunFrames);
5617 }
5618
5619 private:
5620 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005621 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005622 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005623 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005624 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005625
jiabin245cdd92018-12-07 17:55:15 -08005626 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005627 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005628 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005629
5630 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005631 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005632
5633 // process fast tracks
5634 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005635 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5636 "%s(%d): FastTrack(%d) present without FastMixer",
5637 __func__, id(), track->id());
5638
jiabin245cdd92018-12-07 17:55:15 -08005639 if (track->getHapticPlaybackEnabled()) {
5640 noFastHapticTrack = false;
5641 }
Eric Laurent81784c32012-11-19 14:55:58 -08005642
5643 // It's theoretically possible (though unlikely) for a fast track to be created
5644 // and then removed within the same normal mix cycle. This is not a problem, as
5645 // the track never becomes active so it's fast mixer slot is never touched.
5646 // The converse, of removing an (active) track and then creating a new track
5647 // at the identical fast mixer slot within the same normal mix cycle,
5648 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005649 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005650 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005651 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5652 FastTrack *fastTrack = &state->mFastTracks[j];
5653
5654 // Determine whether the track is currently in underrun condition,
5655 // and whether it had a recent underrun.
5656 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5657 FastTrackUnderruns underruns = ftDump->mUnderruns;
5658 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005659 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005660 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005661 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005662 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005663 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005664 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005665 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005666 // don't count underruns that occur while stopping or pausing
5667 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005668 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005669 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5670 recentUnderruns > 0) {
5671 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005672 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005673 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005674 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005675 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005676
5677 // This is similar to the state machine for normal tracks,
5678 // with a few modifications for fast tracks.
5679 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005680 switch (track->state()) {
5681 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005682 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005683 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005684 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005685 }
5686 break;
Andy Hung11e74242023-06-26 19:20:57 -07005687 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005688 // ramp down is not yet implemented
5689 track->setPaused();
5690 break;
Andy Hung11e74242023-06-26 19:20:57 -07005691 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005692 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005693 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005694 break;
Andy Hung11e74242023-06-26 19:20:57 -07005695 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005696 if (recentFull > 0 || recentPartial > 0) {
5697 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005698 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005699 }
5700 if (recentUnderruns == 0) {
5701 // no recent underruns: stay active
5702 break;
5703 }
5704 // there has recently been an underrun of some kind
5705 if (track->sharedBuffer() == 0) {
5706 // were any of the recent underruns "empty" (no frames available)?
5707 if (recentEmpty == 0) {
5708 // no, then ignore the partial underruns as they are allowed indefinitely
5709 break;
5710 }
5711 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005712 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005713 break;
5714 }
5715 // indicate to client process that the track was disabled because of underrun;
5716 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005717 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005718 // remove from active list, but state remains ACTIVE [confusing but true]
5719 isActive = false;
5720 break;
5721 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005722 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005723 case IAfTrackBase::STOPPING_2:
5724 case IAfTrackBase::PAUSED:
5725 case IAfTrackBase::STOPPED:
5726 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005727 // Check for presentation complete if track is inactive
5728 // We have consumed all the buffers of this track.
5729 // This would be incomplete if we auto-paused on underrun
5730 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005731 uint32_t latency = 0;
5732 status_t result = mOutput->stream->getLatency(&latency);
5733 ALOGE_IF(result != OK,
5734 "Error when retrieving output stream latency: %d", result);
5735 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005736 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005737 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5738 // track stays in active list until presentation is complete
5739 break;
5740 }
5741 }
5742 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005743 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005744 }
5745 if (track->isStopped()) {
5746 // Can't reset directly, as fast mixer is still polling this track
5747 // track->reset();
5748 // So instead mark this track as needing to be reset after push with ack
5749 resetMask |= 1 << i;
5750 }
5751 isActive = false;
5752 break;
Andy Hung11e74242023-06-26 19:20:57 -07005753 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005754 default:
Andy Hung11e74242023-06-26 19:20:57 -07005755 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005756 }
5757
5758 if (isActive) {
5759 // was it previously inactive?
5760 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005761 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5762 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005763 fastTrack->mBufferProvider = eabp;
5764 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005765 fastTrack->mChannelMask = track->channelMask();
5766 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005767 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005768 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005769 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005770 fastTrack->mGeneration++;
5771 state->mTrackMask |= 1 << j;
5772 didModify = true;
5773 // no acknowledgement required for newly active tracks
5774 }
Andy Hung11e74242023-06-26 19:20:57 -07005775 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005776 float volume;
5777 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5778 volume = 0.f;
5779 } else {
5780 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5781 }
5782
5783 handleVoipVolume_l(&volume);
5784
Eric Laurent81784c32012-11-19 14:55:58 -08005785 // cache the combined master volume and stream type volume for fast mixer; this
5786 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005787 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005788 proxy->framesReleased()).first;
5789 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005790 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005791 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005792 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5793 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5794
Andy Hung7535ed92023-07-17 17:05:00 -07005795 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005796 /*muteState=*/{masterVolume == 0.f,
5797 mStreamTypes[track->streamType()].volume == 0.f,
5798 mStreamTypes[track->streamType()].mute,
5799 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005800 vlf == 0.f && vrf == 0.f,
5801 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005802
5803 vlf *= volume;
5804 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005805
jiabin76d94692022-12-15 21:51:21 +00005806 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005807 ++fastTracks;
5808 } else {
5809 // was it previously active?
5810 if (state->mTrackMask & (1 << j)) {
5811 fastTrack->mBufferProvider = NULL;
5812 fastTrack->mGeneration++;
5813 state->mTrackMask &= ~(1 << j);
5814 didModify = true;
5815 // If any fast tracks were removed, we must wait for acknowledgement
5816 // because we're about to decrement the last sp<> on those tracks.
5817 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5818 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005819 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5820 // AudioTrack may start (which may not be with a start() but with a write()
5821 // after underrun) and immediately paused or released. In that case the
5822 // FastTrack state hasn't had time to update.
5823 // TODO Remove the ALOGW when this theory is confirmed.
5824 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005825 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005826 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005827 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005828 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005829 }
5830 tracksToRemove->add(track);
5831 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005832 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005833 }
jiabin245cdd92018-12-07 17:55:15 -08005834 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5835 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5836 didModify = true;
5837 }
Eric Laurent81784c32012-11-19 14:55:58 -08005838 continue;
5839 }
5840
5841 { // local variable scope to avoid goto warning
5842
5843 audio_track_cblk_t* cblk = track->cblk();
5844
5845 // The first time a track is added we wait
5846 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005847 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005848
5849 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005850 // use the trackId as the AudioMixer name.
5851 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005852 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005853 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005854 track->channelMask(),
5855 track->format(),
5856 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005857 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005858 ALOGW("%s(): AudioMixer cannot create track(%d)"
5859 " mask %#x, format %#x, sessionId %d",
5860 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005861 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005862 tracksToRemove->add(track);
5863 track->invalidate(); // consider it dead.
5864 continue;
5865 }
5866 }
5867
Eric Laurent81784c32012-11-19 14:55:58 -08005868 // make sure that we have enough frames to mix one full buffer.
5869 // enforce this condition only once to enable draining the buffer in case the client
5870 // app does not call stop() and relies on underrun to stop:
5871 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5872 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005873 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005874 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5875 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005876
5877 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005878 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005879 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5880 // add frames already consumed but not yet released by the resampler
5881 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005882 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005883
Eric Laurent81784c32012-11-19 14:55:58 -08005884 uint32_t minFrames = 1;
5885 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5886 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005887 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005888 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005889
5890 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005891 if (ATRACE_ENABLED()) {
5892 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005893 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005894 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005895 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005896 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005897 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005898 !track->isPaused() && !track->isTerminated())
5899 {
Andy Hungc0691382018-09-12 18:01:57 -07005900 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005901
5902 mixedTracks++;
5903
Shunkai Yaof4847652024-01-12 00:25:20 +00005904 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005905 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005906 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005907 if (track->mainBuffer() != mSinkBuffer &&
5908 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005909 if (mEffectBufferEnabled) {
5910 mEffectBufferValid = true; // Later can set directly.
5911 }
Eric Laurent81784c32012-11-19 14:55:58 -08005912 chain = getEffectChain_l(track->sessionId());
5913 // Delegate volume control to effect in track effect chain if needed
5914 if (chain != 0) {
5915 tracksWithEffect++;
5916 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005917 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005918 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005919 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005920 }
5921 }
5922
5923
5924 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005925 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005926 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005927 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5928 if (track->state() == IAfTrackBase::RESUMING) {
5929 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005930 // If a new track is paused immediately after start, do not ramp on resume.
5931 if (cblk->mServer != 0) {
5932 param = AudioMixer::RAMP_VOLUME;
5933 }
Eric Laurent81784c32012-11-19 14:55:58 -08005934 }
Andy Hungc0691382018-09-12 18:01:57 -07005935 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005936 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005937 // FIXME should not make a decision based on mServer
5938 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005939 // If the track is stopped before the first frame was mixed,
5940 // do not apply ramp
5941 param = AudioMixer::RAMP_VOLUME;
5942 }
5943
5944 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005945 uint32_t vl, vr; // in U8.24 integer format
5946 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005947 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005948 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005949 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005950 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005951 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005952 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005953
Eric Laurenteab90452019-06-24 15:17:46 -07005954 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5955 v = 0;
5956 }
5957
5958 handleVoipVolume_l(&v);
5959
5960 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005961 vl = vr = 0;
5962 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005963 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005964 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005965 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005966 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5967 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005968 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005969 if (vlf > GAIN_FLOAT_UNITY) {
5970 ALOGV("Track left volume out of range: %.3g", vlf);
5971 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005972 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005973 if (vrf > GAIN_FLOAT_UNITY) {
5974 ALOGV("Track right volume out of range: %.3g", vrf);
5975 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005976 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005977
Andy Hung7535ed92023-07-17 17:05:00 -07005978 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005979 /*muteState=*/{masterVolume == 0.f,
5980 mStreamTypes[track->streamType()].volume == 0.f,
5981 mStreamTypes[track->streamType()].mute,
5982 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005983 vlf == 0.f && vrf == 0.f,
5984 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005985
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005986 // now apply the master volume and stream type volume and shaper volume
5987 vlf *= v * vh;
5988 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005989 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005990 // then derive vl and vr as U8.24 versions for the effect chain
5991 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5992 vl = (uint32_t) (scaleto8_24 * vlf);
5993 vr = (uint32_t) (scaleto8_24 * vrf);
5994 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005995 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005996 // send level comes from shared memory and so may be corrupt
5997 if (sendLevel > MAX_GAIN_INT) {
5998 ALOGV("Track send level out of range: %04X", sendLevel);
5999 sendLevel = MAX_GAIN_INT;
6000 }
Andy Hung6be49402014-05-30 10:42:03 -07006001 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6002 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006003 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006004
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006005 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006006
Eric Laurent81784c32012-11-19 14:55:58 -08006007 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006008 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006009 // Do not ramp volume if volume is controlled by effect
6010 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006011 // Update remaining floating point volume levels
6012 vlf = (float)vl / (1 << 24);
6013 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07006014 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006015 } else {
6016 // force no volume ramp when volume controller was just disabled or removed
6017 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07006018 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006019 param = AudioMixer::VOLUME;
6020 }
Andy Hung11e74242023-06-26 19:20:57 -07006021 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006022 }
6023
Eric Laurent81784c32012-11-19 14:55:58 -08006024 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07006025 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006026 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006027
Andy Hungc0691382018-09-12 18:01:57 -07006028 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6029 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6030 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006031 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006032 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006033 AudioMixer::TRACK,
6034 AudioMixer::FORMAT, (void *)track->format());
6035 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006036 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006037 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006038 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006039
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006040 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006041 mAudioMixer->setParameter(
6042 trackId,
6043 AudioMixer::TRACK,
6044 AudioMixer::MIXER_CHANNEL_MASK,
6045 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6046 } else {
6047 mAudioMixer->setParameter(
6048 trackId,
6049 AudioMixer::TRACK,
6050 AudioMixer::MIXER_CHANNEL_MASK,
6051 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6052 }
6053
Glenn Kastene3aa6592012-12-04 12:22:46 -08006054 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006055 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006056 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006057 if (reqSampleRate == 0) {
6058 reqSampleRate = mSampleRate;
6059 } else if (reqSampleRate > maxSampleRate) {
6060 reqSampleRate = maxSampleRate;
6061 }
Eric Laurent81784c32012-11-19 14:55:58 -08006062 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006063 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006064 AudioMixer::RESAMPLE,
6065 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006066 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006067
Andy Hung8edb8dc2015-03-26 19:13:55 -07006068 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006069 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006070 AudioMixer::TIMESTRETCH,
6071 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006072 // cast away constness for this generic API.
6073 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006074
Andy Hung69aed5f2014-02-25 17:24:40 -08006075 /*
6076 * Select the appropriate output buffer for the track.
6077 *
Andy Hung98ef9782014-03-04 14:46:50 -08006078 * Tracks with effects go into their own effects chain buffer
6079 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006080 *
6081 * Other tracks can use mMixerBuffer for higher precision
6082 * channel accumulation. If this buffer is enabled
6083 * (mMixerBufferEnabled true), then selected tracks will accumulate
6084 * into it.
6085 *
6086 */
6087 if (mMixerBufferEnabled
6088 && (track->mainBuffer() == mSinkBuffer
6089 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006090 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006091 mAudioMixer->setParameter(
6092 trackId,
6093 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006094 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006095 mAudioMixer->setParameter(
6096 trackId,
6097 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006098 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006099 } else {
6100 mAudioMixer->setParameter(
6101 trackId,
6102 AudioMixer::TRACK,
6103 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6104 mAudioMixer->setParameter(
6105 trackId,
6106 AudioMixer::TRACK,
6107 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6108 // TODO: override track->mainBuffer()?
6109 mMixerBufferValid = true;
6110 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006111 } else {
6112 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006113 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006114 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006115 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006116 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006117 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006118 AudioMixer::TRACK,
6119 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6120 }
Eric Laurent81784c32012-11-19 14:55:58 -08006121 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006122 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006123 AudioMixer::TRACK,
6124 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006125 mAudioMixer->setParameter(
6126 trackId,
6127 AudioMixer::TRACK,
6128 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006129 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006130 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006131 trackId,
6132 AudioMixer::TRACK,
6133 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung11e74242023-06-26 19:20:57 -07006134 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006135 mAudioMixer->setParameter(
6136 trackId,
6137 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07006138 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006139
6140 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006141 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006142
6143 // If one track is ready, set the mixer ready if:
6144 // - the mixer was not ready during previous round OR
6145 // - no other track is not ready
6146 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6147 mixerStatus != MIXER_TRACKS_ENABLED) {
6148 mixerStatus = MIXER_TRACKS_READY;
6149 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006150
6151 // Enable the next few lines to instrument a test for underrun log handling.
6152 // TODO: Remove when we have a better way of testing the underrun log.
6153#if 0
6154 static int i;
6155 if ((++i & 0xf) == 0) {
6156 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6157 }
6158#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006159 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006160 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006161 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006162 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6163 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006164 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006165 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006166 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006167
Eric Laurent81784c32012-11-19 14:55:58 -08006168 // clear effect chain input buffer if an active track underruns to avoid sending
6169 // previous audio buffer again to effects
6170 chain = getEffectChain_l(track->sessionId());
6171 if (chain != 0) {
6172 chain->clearInputBuffer();
6173 }
6174
Andy Hungc0691382018-09-12 18:01:57 -07006175 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006176 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6177 track->isStopped() || track->isPaused()) {
6178 // We have consumed all the buffers of this track.
6179 // Remove it from the list of active tracks.
6180 // TODO: use actual buffer filling status instead of latency when available from
6181 // audio HAL
6182 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006183 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006184 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6185 if (track->isStopped()) {
6186 track->reset();
6187 }
6188 tracksToRemove->add(track);
6189 }
6190 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006191 // No buffers for this track. Give it a few chances to
6192 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07006193 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006194 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6195 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006196 tracksToRemove->add(track);
6197 // indicate to client process that the track was disabled because of underrun;
6198 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006199 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006200 // If one track is not ready, mark the mixer also not ready if:
6201 // - the mixer was ready during previous round OR
6202 // - no other track is ready
6203 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6204 mixerStatus != MIXER_TRACKS_READY) {
6205 mixerStatus = MIXER_TRACKS_ENABLED;
6206 }
6207 }
Andy Hungc0691382018-09-12 18:01:57 -07006208 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006209 }
6210
6211 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006212
6213 }
6214
jiabin245cdd92018-12-07 17:55:15 -08006215 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6216 // When there is no fast track playing haptic and FastMixer exists,
6217 // enabling the first FastTrack, which provides mixed data from normal
6218 // tracks, to play haptic data.
6219 FastTrack *fastTrack = &state->mFastTracks[0];
6220 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6221 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6222 didModify = true;
6223 }
6224 }
6225
Eric Laurent81784c32012-11-19 14:55:58 -08006226 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006227 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006228 if (didModify) {
6229 state->mFastTracksGen++;
6230 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6231 if (kUseFastMixer == FastMixer_Dynamic &&
6232 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6233 state->mCommand = FastMixerState::COLD_IDLE;
6234 state->mColdFutexAddr = &mFastMixerFutex;
6235 state->mColdGen++;
6236 mFastMixerFutex = 0;
6237 if (kUseFastMixer == FastMixer_Dynamic) {
6238 mNormalSink = mOutputSink;
6239 }
6240 // If we go into cold idle, need to wait for acknowledgement
6241 // so that fast mixer stops doing I/O.
6242 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6243 pauseAudioWatchdog = true;
6244 }
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
6246 if (sq != NULL) {
6247 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006248 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6249 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6250 // when bringing the output sink into standby.)
6251 //
6252 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6253 //
6254 // This occurs with BT suspend when we idle the FastMixer with
6255 // active tracks, which may be added or removed.
6256 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006257 }
6258#ifdef AUDIO_WATCHDOG
6259 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6260 mAudioWatchdog->pause();
6261 }
6262#endif
6263
6264 // Now perform the deferred reset on fast tracks that have stopped
6265 while (resetMask != 0) {
6266 size_t i = __builtin_ctz(resetMask);
6267 ALOG_ASSERT(i < count);
6268 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006269 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006270 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6271 track->reset();
6272 }
6273
Andy Hung80d03d22018-04-10 10:32:11 -07006274 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6275 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6276 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6277 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6278 // See also the implementation of destroyTrack_l().
6279 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006280 const int trackId = track->id();
6281 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6282 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006283 }
6284 }
6285
Eric Laurent81784c32012-11-19 14:55:58 -08006286 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006287 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006288
Eric Laurentb3f315a2021-07-13 15:09:05 +02006289 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6290 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006291 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006292 }
6293
6294 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006295 // as long as there are effects we should clear the effects buffer, to avoid
6296 // passing a non-clean buffer to the effect chain
6297 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006298 if (mType == SPATIALIZER) {
6299 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6300 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006301 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006302 // sink or mix buffer must be cleared if all tracks are connected to an
6303 // effect chain as in this case the mixer will not write to the sink or mix buffer
6304 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006305 // always clear sink buffer for spatializer output as the output of the spatializer
6306 // effect will be accumulated into it
6307 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6308 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006309 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006310 if (mMixerBufferValid) {
6311 memset(mMixerBuffer, 0, mMixerBufferSize);
6312 // TODO: In testing, mSinkBuffer below need not be cleared because
6313 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6314 // after mixing.
6315 //
6316 // To enforce this guarantee:
6317 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6318 // (mixedTracks == 0 && fastTracks > 0))
6319 // must imply MIXER_TRACKS_READY.
6320 // Later, we may clear buffers regardless, and skip much of this logic.
6321 }
Andy Hung98ef9782014-03-04 14:46:50 -08006322 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006323 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006324 }
6325
6326 // if any fast tracks, then status is ready
6327 mMixerStatusIgnoringFastTracks = mixerStatus;
6328 if (fastTracks > 0) {
6329 mixerStatus = MIXER_TRACKS_READY;
6330 }
6331 return mixerStatus;
6332}
6333
Andy Hungb17d24b2023-08-29 14:26:09 -07006334// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006335uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006336{
6337 uint32_t trackCount = 0;
6338 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006339 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006340 trackCount++;
6341 }
6342 }
6343 return trackCount;
6344}
6345
Andy Hung4b17e882023-07-07 13:47:37 -07006346bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006347{
Brian Lindahl65e90012022-07-27 18:01:07 +02006348 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6349 // could falsely detect that the frame position has stalled due to underrun because we haven't
6350 // given the Audio HAL enough time to update.
6351 const nsecs_t nowNs = systemTime();
6352 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6353 return mLatchedValue;
6354 }
6355 mPreviousNs = nowNs;
6356 mLatchedValue = false;
6357 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006358 uint64_t position = 0;
6359 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006360 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006361 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006362 if (position != mPreviousPosition) {
6363 mPreviousPosition = position;
6364 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006365 }
6366 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006367 return mLatchedValue;
6368}
6369
Andy Hung4b17e882023-07-07 13:47:37 -07006370void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006371{
6372 mLatchedValue = true;
6373 mPreviousPosition = 0;
6374 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006375}
6376
Andy Hungb17d24b2023-08-29 14:26:09 -07006377// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006378bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006379 audio_channel_mask_t channelMask, audio_format_t format,
6380 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006381{
Andy Hung1bc088a2018-02-09 15:57:31 -08006382 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6383 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006384 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006385 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006386 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006387 ALOGW("%s: invalid format: %#x", __func__, format);
6388 return false;
6389 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006390 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006391 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6392 return false;
6393 }
6394 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006395}
6396
Andy Hungb17d24b2023-08-29 14:26:09 -07006397// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006398bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006399 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006400{
Eric Laurent81784c32012-11-19 14:55:58 -08006401 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006402 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006403
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006404 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006405
Eric Laurent10351942014-05-08 18:49:52 -07006406 AudioParameter param = AudioParameter(keyValuePair);
6407 int value;
6408 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6409 reconfig = true;
6410 }
6411 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006412 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006413 status = BAD_VALUE;
6414 } else {
6415 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006416 reconfig = true;
6417 }
Eric Laurent10351942014-05-08 18:49:52 -07006418 }
6419 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006420 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006421 status = BAD_VALUE;
6422 } else {
6423 // no need to save value, since it's constant
6424 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006425 }
Eric Laurent10351942014-05-08 18:49:52 -07006426 }
6427 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6428 // do not accept frame count changes if tracks are open as the track buffer
6429 // size depends on frame count and correct behavior would not be guaranteed
6430 // if frame count is changed after track creation
6431 if (!mTracks.isEmpty()) {
6432 status = INVALID_OPERATION;
6433 } else {
6434 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006435 }
Eric Laurent10351942014-05-08 18:49:52 -07006436 }
6437 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006438 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006439 }
Eric Laurent81784c32012-11-19 14:55:58 -08006440
Eric Laurent10351942014-05-08 18:49:52 -07006441 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006442 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006443 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006444 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6445 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006446 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006447 mThreadMetrics.logEndInterval();
6448 mThreadSnapshot.onEnd();
6449 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006450 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006451 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006452 }
Eric Laurent10351942014-05-08 18:49:52 -07006453 if (status == NO_ERROR && reconfig) {
6454 readOutputParameters_l();
6455 delete mAudioMixer;
6456 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006457 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006458 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006459 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006460 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006461 track->channelMask(),
6462 track->format(),
6463 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006464 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006465 "%s(): AudioMixer cannot create track(%d)"
6466 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006467 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006468 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006469 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006470 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006471 }
Eric Laurent81784c32012-11-19 14:55:58 -08006472 }
6473
Dean Wheatley68918102021-03-19 22:09:19 +11006474 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006475}
6476
6477
Andy Hung4b17e882023-07-07 13:47:37 -07006478void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006479{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006480 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung160664b2023-09-15 18:19:28 -07006481 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006482 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006483 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006484 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6485 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6486 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006487 if (hasFastMixer()) {
6488 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6489
6490 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6491 // while we are dumping it. It may be inconsistent, but it won't mutate!
6492 // This is a large object so we place it on the heap.
6493 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006494 const std::unique_ptr<FastMixerDumpState> copy =
6495 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006496 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006497
6498#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006499 // Similar for state queue
6500 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6501 observerCopy.dump(fd);
6502 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6503 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006504#endif
6505
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006506#ifdef AUDIO_WATCHDOG
6507 if (mAudioWatchdog != 0) {
6508 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6509 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6510 wdCopy.dump(fd);
6511 }
6512#endif
6513
6514 } else {
6515 dprintf(fd, " No FastMixer\n");
6516 }
Eric Laurent90cea102023-05-15 15:08:27 +02006517
6518 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6519 mBluetoothLatencyModesEnabled ? "" : "not ");
6520 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6521 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6522 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006523}
6524
Andy Hung4b17e882023-07-07 13:47:37 -07006525uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006526{
6527 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6528}
6529
Andy Hung4b17e882023-07-07 13:47:37 -07006530uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006531{
6532 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6533}
6534
Andy Hung4b17e882023-07-07 13:47:37 -07006535void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006536{
6537 PlaybackThread::cacheParameters_l();
6538
6539 // FIXME: Relaxed timing because of a certain device that can't meet latency
6540 // Should be reduced to 2x after the vendor fixes the driver issue
6541 // increase threshold again due to low power audio mode. The way this warning
6542 // threshold is calculated and its usefulness should be reconsidered anyway.
6543 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6544}
6545
Andy Hung4b17e882023-07-07 13:47:37 -07006546void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006547 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006548}
6549
Andy Hung4b17e882023-07-07 13:47:37 -07006550void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006551 // Only handle latency mode if:
6552 // - mBluetoothLatencyModesEnabled is true
6553 // - the HAL supports latency modes
6554 // - the selected device is Bluetooth LE or A2DP
6555 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6556 return;
6557 }
6558 if (mOutDeviceTypeAddrs.size() != 1
6559 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6560 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6561 return;
6562 }
6563
6564 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6565 if (mSupportedLatencyModes.size() == 1) {
6566 // If the HAL only support one latency mode currently, confirm the choice
6567 latencyMode = mSupportedLatencyModes[0];
6568 } else if (mSupportedLatencyModes.size() > 1) {
6569 // Request low latency if:
6570 // - At least one active track is either:
6571 // - a fast track with gaming usage or
6572 // - a track with acessibility usage
6573 for (const auto& track : mActiveTracks) {
6574 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6575 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6576 latencyMode = AUDIO_LATENCY_MODE_LOW;
6577 break;
6578 }
6579 }
6580 }
6581
6582 if (latencyMode != mSetLatencyMode) {
6583 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6584 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6585 __func__, mId, toString(latencyMode).c_str(), status);
6586 if (status == NO_ERROR) {
6587 mSetLatencyMode = latencyMode;
6588 }
6589 }
6590}
6591
Andy Hung4b17e882023-07-07 13:47:37 -07006592void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006593
6594 if (mOutput == nullptr || mOutput->stream == nullptr) {
6595 return;
6596 }
6597 std::vector<audio_latency_mode_t> latencyModes;
6598 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6599 if (status != NO_ERROR) {
6600 latencyModes.clear();
6601 }
6602 if (latencyModes != mSupportedLatencyModes) {
6603 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6604 __func__, mId, status, toString(latencyModes).c_str());
6605 mSupportedLatencyModes.swap(latencyModes);
6606 sendHalLatencyModesChangedEvent_l();
6607 }
6608}
6609
Andy Hung4b17e882023-07-07 13:47:37 -07006610status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006611 std::vector<audio_latency_mode_t>* modes) {
6612 if (modes == nullptr) {
6613 return BAD_VALUE;
6614 }
Andy Hungf8635b62023-08-31 16:13:39 -07006615 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006616 *modes = mSupportedLatencyModes;
6617 return NO_ERROR;
6618}
6619
Andy Hung4b17e882023-07-07 13:47:37 -07006620void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006621 std::vector<audio_latency_mode_t> modes) {
Andy Hungf8635b62023-08-31 16:13:39 -07006622 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006623 if (modes != mSupportedLatencyModes) {
6624 ALOGD("%s: thread(%d) supported latency modes: %s",
6625 __func__, mId, toString(modes).c_str());
6626 mSupportedLatencyModes.swap(modes);
6627 sendHalLatencyModesChangedEvent_l();
6628 }
6629}
6630
Andy Hung4b17e882023-07-07 13:47:37 -07006631status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006632 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6633 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6634 return INVALID_OPERATION;
6635 }
6636 mBluetoothLatencyModesEnabled.store(enabled);
6637 return NO_ERROR;
6638}
6639
Eric Laurent81784c32012-11-19 14:55:58 -08006640// ----------------------------------------------------------------------------
6641
Andy Hung4b17e882023-07-07 13:47:37 -07006642/* static */
6643sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006644 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006645 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6646 const audio_offload_info_t& offloadInfo) {
6647 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006648 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006649}
6650
Andy Hung7535ed92023-07-17 17:05:00 -07006651DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006652 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6653 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006654 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006655 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006656{
Andy Hung7535ed92023-07-17 17:05:00 -07006657 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006658}
6659
Andy Hung4b17e882023-07-07 13:47:37 -07006660DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006661{
6662}
6663
Andy Hung4b17e882023-07-07 13:47:37 -07006664void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006665{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006666 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006667 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6668 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6669}
6670
Andy Hung4b17e882023-07-07 13:47:37 -07006671void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006672{
Andy Hungf8635b62023-08-31 16:13:39 -07006673 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006674 if (mMasterBalance != balance) {
6675 mMasterBalance.store(balance);
6676 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6677 broadcast_l();
6678 }
6679}
6680
Andy Hung4b17e882023-07-07 13:47:37 -07006681void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006682{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006683 float left, right;
6684
Andy Hung333ab962019-05-28 20:23:35 -07006685 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006686 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006687
Andy Hung398ffa22022-12-13 19:19:53 -08006688 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6689 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6690
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006691 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6692 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006693
6694 const int64_t volumeShaperFrames =
6695 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6696 const auto [shaperVolume, shaperActive] =
6697 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006698 mVolumeShaperActive = shaperActive;
6699
Vlad Popae2f5aef2022-07-25 16:00:20 +02006700 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6701 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6702 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6703
6704 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6705
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006706 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006707 left = right = 0;
6708 } else {
6709 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006710 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006711
Glenn Kastenc56f3422014-03-21 17:53:17 -07006712 if (left > GAIN_FLOAT_UNITY) {
6713 left = GAIN_FLOAT_UNITY;
6714 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006715 if (right > GAIN_FLOAT_UNITY) {
6716 right = GAIN_FLOAT_UNITY;
6717 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006718 left *= v;
6719 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006720 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006721 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6722 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6723 right *= mMasterBalanceRight;
6724 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006725 }
6726
Andy Hung7535ed92023-07-17 17:05:00 -07006727 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006728 /*muteState=*/{mMasterMute,
6729 mStreamTypes[track->streamType()].volume == 0.f,
6730 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006731 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006732 clientVolumeMute,
6733 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006734
Eric Laurentbfb1b832013-01-07 09:53:42 -08006735 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006736 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006737 if (left != mLeftVolFloat || right != mRightVolFloat) {
6738 mLeftVolFloat = left;
6739 mRightVolFloat = right;
6740
Eric Laurentbfb1b832013-01-07 09:53:42 -08006741 // Delegate volume control to effect in track effect chain if needed
6742 // only one effect chain can be present on DirectOutputThread, so if
6743 // there is one, the track is connected to it
6744 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006745 // if effect chain exists, volume is handled by it.
6746 // Convert volumes from float to 8.24
6747 uint32_t vl = (uint32_t)(left * (1 << 24));
6748 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006749 // Direct/Offload effect chains set output volume in setVolume().
6750 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006751 } else {
6752 // otherwise we directly set the volume.
6753 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006754 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006755 }
6756 }
6757}
6758
Andy Hung4b17e882023-07-07 13:47:37 -07006759void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006760{
Andy Hung11e74242023-06-26 19:20:57 -07006761 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6762 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006763
Eric Laurent0f0631e2015-07-06 18:01:25 -07006764 if (previousTrack != 0 && latestTrack != 0) {
6765 if (mType == DIRECT) {
6766 if (previousTrack.get() != latestTrack.get()) {
6767 mFlushPending = true;
6768 }
6769 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006770 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6771 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006772 mFlushPending = true;
6773 }
6774 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006775 } else if (previousTrack == 0) {
6776 // there could be an old track added back during track transition for direct
6777 // output, so always issues flush to flush data of the previous track if it
6778 // was already destroyed with HAL paused, then flush can resume the playback
6779 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006780 }
6781 PlaybackThread::onAddNewTrack_l();
6782}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006783
Andy Hung4b17e882023-07-07 13:47:37 -07006784PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006785 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006786)
6787{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006788 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006789 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006790 bool doHwPause = false;
6791 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006792
6793 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006794 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006795 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006796 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006797 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006798 continue;
6799 }
6800
Andy Hung11e74242023-06-26 19:20:57 -07006801 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006802#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006803 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006804#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006805 // Only consider last track started for volume and mixer state control.
6806 // In theory an older track could underrun and restart after the new one starts
6807 // but as we only care about the transition phase between two tracks on a
6808 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006809 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006810 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006811
Kuowei Li23666472021-01-20 10:23:25 +08006812 if (track->isPausePending()) {
6813 track->pauseAck();
6814 // It is possible a track might have been flushed or stopped.
6815 // Other operations such as flush pending might occur on the next prepare.
6816 if (track->isPausing()) {
6817 track->setPaused();
6818 }
6819 // Always perform pause, as an immediate flush will change
6820 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006821 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006822 doHwPause = true;
6823 mHwPaused = true;
6824 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006825 } else if (track->isFlushPending()) {
6826 track->flushAck();
6827 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006828 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006829 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006830 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006831 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006832 if (last) {
6833 mLeftVolFloat = mRightVolFloat = -1.0;
6834 if (mHwPaused) {
6835 doHwResume = true;
6836 mHwPaused = false;
6837 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006838 }
6839 }
6840
Eric Laurent81784c32012-11-19 14:55:58 -08006841 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006842 // for all its buffers to be filled before processing it.
6843 // Allow draining the buffer in case the client
6844 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006845 // hence the test on (track->retryCount() > 1).
6846 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006847 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6848 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006849 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006850
6851 // target retry count that we will use is based on the time we wait for retries.
6852 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6853 // the retry threshold is when we accept any size for PCM data. This is slightly
6854 // smaller than the retry count so we can push small bits of data without a glitch.
6855 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006856 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006857 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006858 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006859 minFrames = mNormalFrameCount;
6860 } else {
6861 minFrames = 1;
6862 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006863
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006864 const size_t framesReady = track->framesReady();
6865 const int trackId = track->id();
6866 if (ATRACE_ENABLED()) {
6867 std::string traceName("nRdy");
6868 traceName += std::to_string(trackId);
6869 ATRACE_INT(traceName.c_str(), framesReady);
6870 }
6871 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006872 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006873 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006874 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006875
Andy Hung11e74242023-06-26 19:20:57 -07006876 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6877 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006878 if (last) {
6879 // make sure processVolume_l() will apply new volume even if 0
6880 mLeftVolFloat = mRightVolFloat = -1.0;
6881 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006882 if (!mHwSupportsPause) {
6883 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006884 }
6885 }
6886
6887 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006888 processVolume_l(track, last);
6889 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006890 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006891 if (previousTrack != 0) {
6892 if (track != previousTrack.get()) {
6893 // Flush any data still being written from last track
6894 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006895 // Invalidate previous track to force a seek when resuming.
6896 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006897 }
6898 }
6899 mPreviousTrack = track;
6900
Eric Laurentd595b7c2013-04-03 17:27:56 -07006901 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006902 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006903 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006904 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006905 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006906 doHwResume = true;
6907 mHwPaused = false;
6908 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006909 }
Eric Laurent81784c32012-11-19 14:55:58 -08006910 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006911 // clear effect chain input buffer if the last active track started underruns
6912 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006913 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006914 mEffectChains[0]->clearInputBuffer();
6915 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006916 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006917 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006918 if (last && mHwPaused) {
6919 doHwResume = true;
6920 mHwPaused = false;
6921 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006922 }
6923 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6924 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006925 // We have consumed all the buffers of this track.
6926 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006927 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006928 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006929 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006930 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006931 if (presComplete) {
6932 mOutput->presentationComplete();
6933 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006934 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006935 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006936 }
Eric Laurent81784c32012-11-19 14:55:58 -08006937 if (track->isStopped()) {
6938 track->reset();
6939 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006940 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006941 }
6942 } else {
6943 // No buffers for this track. Give it a few chances to
6944 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006945 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006946 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006947 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006948 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006949 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006950 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006951 } else {
6952 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6953 tracksToRemove->add(track);
6954 // indicate to client process that the track was disabled because of
6955 // underrun; it will then automatically call start() when data is available
6956 track->disable();
6957 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6958 // unlike mixerthread, HAL can be paused for direct output
6959 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6960 "minFrames = %u, mFormat = %#x",
6961 framesReady, minFrames, mFormat);
6962 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6963 doHwPause = true;
6964 mHwPaused = true;
6965 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006966 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006967 } else if (last) {
6968 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006969 }
6970 }
6971 }
6972 }
6973
Eric Laurentd1f69b02014-12-15 14:33:13 -08006974 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006975 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006976 for (size_t i = 0; i < mTracks.size(); i++) {
6977 if (mTracks[i]->isFlushPending()) {
6978 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006979 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006980 }
6981 }
6982 }
6983
6984 // make sure the pause/flush/resume sequence is executed in the right order.
6985 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6986 // before flush and then resume HW. This can happen in case of pause/flush/resume
6987 // if resume is received before pause is executed.
6988 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006989 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006990 status_t result = mOutput->stream->pause();
6991 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006992 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006993 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006994 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006995 flushHw_l();
6996 }
6997 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006998 status_t result = mOutput->stream->resume();
6999 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007000 }
Eric Laurent81784c32012-11-19 14:55:58 -08007001 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007002 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007003
7004 return mixerStatus;
7005}
7006
Andy Hung4b17e882023-07-07 13:47:37 -07007007void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007008{
Eric Laurent81784c32012-11-19 14:55:58 -08007009 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007010 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007011 // output audio to hardware
7012 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007013 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007014 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007015 status_t status = mActiveTrack->getNextBuffer(&buffer);
7016 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007017 // no need to pad with 0 for compressed audio
7018 if (audio_has_proportional_frames(mFormat)) {
7019 memset(curBuf, 0, frameCount * mFrameSize);
7020 }
Eric Laurent81784c32012-11-19 14:55:58 -08007021 break;
7022 }
7023 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7024 frameCount -= buffer.frameCount;
7025 curBuf += buffer.frameCount * mFrameSize;
7026 mActiveTrack->releaseBuffer(&buffer);
7027 }
Andy Hung2098f272014-02-27 14:00:06 -08007028 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007029 mSleepTimeUs = 0;
7030 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007031 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007032}
7033
Andy Hung4b17e882023-07-07 13:47:37 -07007034void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007035{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007036 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007037 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007038 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007039 return;
7040 }
Andy Hung85ba3332021-04-27 17:40:26 -07007041 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7042 mSleepTimeUs = mActiveSleepTimeUs;
7043 } else {
7044 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007045 }
Andy Hung85ba3332021-04-27 17:40:26 -07007046 // Note: In S or later, we do not write zeroes for
7047 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007048}
7049
Andy Hung4b17e882023-07-07 13:47:37 -07007050void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007051{
7052 {
Andy Hungf8635b62023-08-31 16:13:39 -07007053 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007054 for (size_t i = 0; i < mTracks.size(); i++) {
7055 if (mTracks[i]->isFlushPending()) {
7056 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007057 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007058 }
7059 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007060 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007061 flushHw_l();
7062 }
7063 }
7064 PlaybackThread::threadLoop_exit();
7065}
7066
7067// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007068bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007069{
7070 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007071 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007072
7073 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
7074 // after a timeout and we will enter standby then.
7075 if (mTracks.size() > 0) {
7076 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07007077 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07007078 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007079 }
7080
Eric Laurent5cff4032015-05-26 13:49:58 -07007081 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08007082}
7083
Andy Hungb17d24b2023-08-29 14:26:09 -07007084// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07007085bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007086 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007087{
7088 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007089 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007090
Eric Laurent10351942014-05-08 18:49:52 -07007091 AudioParameter param = AudioParameter(keyValuePair);
7092 int value;
7093 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007094 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007095 }
Eric Laurent10351942014-05-08 18:49:52 -07007096 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7097 // do not accept frame count changes if tracks are open as the track buffer
7098 // size depends on frame count and correct behavior would not be garantied
7099 // if frame count is changed after track creation
7100 if (!mTracks.isEmpty()) {
7101 status = INVALID_OPERATION;
7102 } else {
7103 reconfig = true;
7104 }
7105 }
7106 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007107 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007108 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007109 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007110 if (!mStandby) {
7111 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007112 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007113 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007114 }
Eric Laurent10351942014-05-08 18:49:52 -07007115 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007116 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007117 }
7118 if (status == NO_ERROR && reconfig) {
7119 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007120 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007121 }
7122 }
7123
Dean Wheatley68918102021-03-19 22:09:19 +11007124 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007125}
7126
Andy Hung4b17e882023-07-07 13:47:37 -07007127uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007128{
7129 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007130 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007131 time = PlaybackThread::activeSleepTimeUs();
7132 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007133 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007134 }
7135 return time;
7136}
7137
Andy Hung4b17e882023-07-07 13:47:37 -07007138uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007139{
7140 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007141 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007142 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7143 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007144 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007145 }
7146 return time;
7147}
7148
Andy Hung4b17e882023-07-07 13:47:37 -07007149uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007150{
7151 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007152 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007153 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7154 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007155 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007156 }
7157 return time;
7158}
7159
Andy Hung4b17e882023-07-07 13:47:37 -07007160void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007161{
7162 PlaybackThread::cacheParameters_l();
7163
7164 // use shorter standby delay as on normal output to release
7165 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007166 // no delay on outputs with HW A/V sync
7167 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007168 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007169 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007170 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007171 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007172 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007173 }
Eric Laurent81784c32012-11-19 14:55:58 -08007174}
7175
Andy Hung4b17e882023-07-07 13:47:37 -07007176void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007177{
ziyangch8f194f12021-12-01 13:48:04 -08007178 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007179 mOutput->flush();
Haofan Wang3987e9d2024-06-17 21:22:00 +00007180 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007181 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007182 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007183 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007184 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007185}
7186
Andy Hung4b17e882023-07-07 13:47:37 -07007187int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007188 // If a VolumeShaper is active, we must wake up periodically to update volume.
7189 const int64_t NS_PER_MS = 1000000;
7190 return mVolumeShaperActive ?
7191 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7192}
7193
Eric Laurent81784c32012-11-19 14:55:58 -08007194// ----------------------------------------------------------------------------
7195
Andy Hung4b17e882023-07-07 13:47:37 -07007196AsyncCallbackThread::AsyncCallbackThread(
7197 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007198 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007199 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007200 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007201 mDrainSequence(0),
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007202 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007203{
7204}
7205
Andy Hung4b17e882023-07-07 13:47:37 -07007206void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007207{
7208 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7209}
7210
Andy Hung4b17e882023-07-07 13:47:37 -07007211bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007212{
7213 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007214 uint32_t writeAckSequence;
7215 uint32_t drainSequence;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007216 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007217
7218 {
Andy Hungb17d24b2023-08-29 14:26:09 -07007219 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007220 while (!((mWriteAckSequence & 1) ||
7221 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007222 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007223 exitPending())) {
Andy Hungb17d24b2023-08-29 14:26:09 -07007224 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007225 }
7226
Eric Laurentbfb1b832013-01-07 09:53:42 -08007227 if (exitPending()) {
7228 break;
7229 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007230 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7231 mWriteAckSequence, mDrainSequence);
7232 writeAckSequence = mWriteAckSequence;
7233 mWriteAckSequence &= ~1;
7234 drainSequence = mDrainSequence;
7235 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007236 asyncError = mAsyncError;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007237 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007238 }
7239 {
Andy Hung4b17e882023-07-07 13:47:37 -07007240 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007241 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007242 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007243 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007244 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007245 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007246 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007247 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007248 if (asyncError != ASYNC_ERROR_NONE) {
7249 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007250 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007251 }
7252 }
7253 }
7254 return false;
7255}
7256
Andy Hung4b17e882023-07-07 13:47:37 -07007257void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007258{
7259 ALOGV("AsyncCallbackThread::exit");
Andy Hungf8635b62023-08-31 16:13:39 -07007260 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007261 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -07007262 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007263}
7264
Andy Hung4b17e882023-07-07 13:47:37 -07007265void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007266{
Andy Hungf8635b62023-08-31 16:13:39 -07007267 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007268 // bit 0 is cleared
7269 mWriteAckSequence = sequence << 1;
7270}
7271
Andy Hung4b17e882023-07-07 13:47:37 -07007272void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007273{
Andy Hungf8635b62023-08-31 16:13:39 -07007274 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007275 // ignore unexpected callbacks
7276 if (mWriteAckSequence & 2) {
7277 mWriteAckSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007278 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007279 }
7280}
7281
Andy Hung4b17e882023-07-07 13:47:37 -07007282void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007283{
Andy Hungf8635b62023-08-31 16:13:39 -07007284 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007285 // bit 0 is cleared
7286 mDrainSequence = sequence << 1;
7287}
7288
Andy Hung4b17e882023-07-07 13:47:37 -07007289void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007290{
Andy Hungf8635b62023-08-31 16:13:39 -07007291 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007292 // ignore unexpected callbacks
7293 if (mDrainSequence & 2) {
7294 mDrainSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007295 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007296 }
7297}
7298
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007299void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007300{
Andy Hungf8635b62023-08-31 16:13:39 -07007301 audio_utils::lock_guard _l(mutex());
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007302 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungb17d24b2023-08-29 14:26:09 -07007303 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007304}
7305
Eric Laurentbfb1b832013-01-07 09:53:42 -08007306
7307// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007308
7309/* static */
7310sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007311 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007312 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7313 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007314 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007315}
7316
Andy Hung7535ed92023-07-17 17:05:00 -07007317OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007318 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7319 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007320 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007321 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007322{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007323 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007324 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007325 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007326}
7327
Andy Hung4b17e882023-07-07 13:47:37 -07007328void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007329{
7330 if (mFlushPending || mHwPaused) {
7331 // If a flush is pending or track was paused, just discard buffered data
Andy Hung94dfbb42023-09-06 19:41:47 -07007332 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007333 flushHw_l();
7334 } else {
7335 mMixerStatus = MIXER_DRAIN_ALL;
7336 threadLoop_drain();
7337 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007338 if (mUseAsyncWrite) {
7339 ALOG_ASSERT(mCallbackThread != 0);
7340 mCallbackThread->exit();
7341 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007342 PlaybackThread::threadLoop_exit();
7343}
7344
Andy Hung4b17e882023-07-07 13:47:37 -07007345PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007346 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007347)
7348{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007349 size_t count = mActiveTracks.size();
7350
7351 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007352 bool doHwPause = false;
7353 bool doHwResume = false;
7354
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007355 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007356
Eric Laurentbfb1b832013-01-07 09:53:42 -08007357 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007358 for (const sp<IAfTrack>& t : mActiveTracks) {
7359 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007360#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007361 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007362#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007363 // Only consider last track started for volume and mixer state control.
7364 // In theory an older track could underrun and restart after the new one starts
7365 // but as we only care about the transition phase between two tracks on a
7366 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007367 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007368 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007369
Haynes Mathew George7844f672014-01-15 12:32:55 -08007370 if (track->isInvalid()) {
7371 ALOGW("An invalidated track shouldn't be in active list");
7372 tracksToRemove->add(track);
7373 continue;
7374 }
7375
Andy Hung11e74242023-06-26 19:20:57 -07007376 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007377 ALOGW("An idle track shouldn't be in active list");
7378 continue;
7379 }
7380
Kuowei Li23666472021-01-20 10:23:25 +08007381 if (track->isPausePending()) {
7382 track->pauseAck();
7383 // It is possible a track might have been flushed or stopped.
7384 // Other operations such as flush pending might occur on the next prepare.
7385 if (track->isPausing()) {
7386 track->setPaused();
7387 }
7388 // Always perform pause if last, as an immediate flush will change
7389 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007390 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007391 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007392 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007393 mHwPaused = true;
7394 }
7395 // If we were part way through writing the mixbuffer to
7396 // the HAL we must save this until we resume
7397 // BUG - this will be wrong if a different track is made active,
7398 // in that case we want to discard the pending data in the
7399 // mixbuffer and tell the client to present it again when the
7400 // track is resumed
7401 mPausedWriteLength = mCurrentWriteLength;
7402 mPausedBytesRemaining = mBytesRemaining;
7403 mBytesRemaining = 0; // stop writing
7404 }
7405 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007406 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007407 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007408 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007409 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007410 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007411 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007412 track->flushAck();
7413 if (last) {
7414 mFlushPending = true;
7415 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007416 } else if (track->isResumePending()){
7417 track->resumeAck();
7418 if (last) {
7419 if (mPausedBytesRemaining) {
7420 // Need to continue write that was interrupted
7421 mCurrentWriteLength = mPausedWriteLength;
7422 mBytesRemaining = mPausedBytesRemaining;
7423 mPausedBytesRemaining = 0;
7424 }
7425 if (mHwPaused) {
7426 doHwResume = true;
7427 mHwPaused = false;
7428 // threadLoop_mix() will handle the case that we need to
7429 // resume an interrupted write
7430 }
7431 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007432 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007433
Eric Laurent3df841a2016-07-15 15:15:40 -07007434 mLeftVolFloat = mRightVolFloat = -1.0;
7435
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007436 // Do not handle new data in this iteration even if track->framesReady()
7437 mixerStatus = MIXER_TRACKS_ENABLED;
7438 }
7439 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007440 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007441 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007442 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7443 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007444 if (last) {
7445 // make sure processVolume_l() will apply new volume even if 0
7446 mLeftVolFloat = mRightVolFloat = -1.0;
7447 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007448 }
7449
7450 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007451 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007452 if (previousTrack != 0) {
7453 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007454 // Flush any data still being written from last track
7455 mBytesRemaining = 0;
7456 if (mPausedBytesRemaining) {
7457 // Last track was paused so we also need to flush saved
7458 // mixbuffer state and invalidate track so that it will
7459 // re-submit that unwritten data when it is next resumed
7460 mPausedBytesRemaining = 0;
7461 // Invalidate is a bit drastic - would be more efficient
7462 // to have a flag to tell client that some of the
7463 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007464 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007465 }
7466 // flush data already sent to the DSP if changing audio session as audio
7467 // comes from a different source. Also invalidate previous track to force a
7468 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007469 if (previousTrack->sessionId() != track->sessionId()) {
7470 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007471 }
7472 }
7473 }
7474 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007475 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007476 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007477 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007478 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007479 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007480 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007481 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007482 mixerStatus = MIXER_TRACKS_READY;
7483 }
7484 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007485 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007486 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007487 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007488 // Hardware buffer can hold a large amount of audio so we must
7489 // wait for all current track's data to drain before we say
7490 // that the track is stopped.
7491 if (mBytesRemaining == 0) {
7492 // Only start draining when all data in mixbuffer
7493 // has been written
7494 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007495 track->setState(IAfTrackBase::STOPPING_2);
7496 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007497 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7498 if (last && !mStandby) {
7499 // do not modify drain sequence if we are already draining. This happens
7500 // when resuming from pause after drain.
7501 if ((mDrainSequence & 1) == 0) {
7502 mSleepTimeUs = 0;
7503 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7504 mixerStatus = MIXER_DRAIN_TRACK;
7505 mDrainSequence += 2;
7506 }
7507 if (mHwPaused) {
7508 // It is possible to move from PAUSED to STOPPING_1 without
7509 // a resume so we must ensure hardware is running
7510 doHwResume = true;
7511 mHwPaused = false;
7512 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007513 }
7514 }
Eric Laurente93cc032016-05-05 10:15:10 -07007515 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007516 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007517 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007518 }
7519 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007520 // Drain has completed or we are in standby, signal presentation complete
7521 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007522 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007523 mOutput->presentationComplete();
7524 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007525 track->reset();
7526 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007527 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007528 if (!mUseAsyncWrite) {
7529 // If we don't get explicit drain notification we must
7530 // register discontinuity regardless of whether this is
7531 // the previous (!last) or the upcoming (last) track
7532 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007533 mTimestampVerifier.discontinuity(
7534 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007535 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007536 }
7537 } else {
7538 // No buffers for this track. Give it a few chances to
7539 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007540 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007541 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007542 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007543 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007544 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007545 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007546 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7547 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007548 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007549 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007550 // it will then automatically call start() when data is available
7551 track->disable();
7552 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007553 } else if (last){
7554 mixerStatus = MIXER_TRACKS_ENABLED;
7555 }
7556 }
7557 }
7558 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007559 if (track->isReady()) { // check ready to prevent premature start.
7560 processVolume_l(track, last);
7561 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007562 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007563
Eric Laurentea0fade2013-10-04 16:23:48 -07007564 // make sure the pause/flush/resume sequence is executed in the right order.
7565 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7566 // before flush and then resume HW. This can happen in case of pause/flush/resume
7567 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007568 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007569 status_t result = mOutput->stream->pause();
7570 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007571 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007572 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007573 if (mFlushPending) {
7574 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007575 }
Eric Laurentfd477972013-10-25 18:10:40 -07007576 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007577 status_t result = mOutput->stream->resume();
7578 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007579 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007580
Eric Laurentbfb1b832013-01-07 09:53:42 -08007581 // remove all the tracks that need to be...
7582 removeTracks_l(*tracksToRemove);
7583
7584 return mixerStatus;
7585}
7586
Eric Laurentbfb1b832013-01-07 09:53:42 -08007587// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007588bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007589{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007590 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7591 mWriteAckSequence, mDrainSequence);
7592 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007593 return true;
7594 }
7595 return false;
7596}
7597
Andy Hung4b17e882023-07-07 13:47:37 -07007598bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007599{
Andy Hungf8635b62023-08-31 16:13:39 -07007600 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007601 return waitingAsyncCallback_l();
7602}
7603
Andy Hung4b17e882023-07-07 13:47:37 -07007604void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007605{
Eric Laurente659ef42014-09-29 13:06:46 -07007606 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007607 // Flush anything still waiting in the mixbuffer
7608 mCurrentWriteLength = 0;
7609 mBytesRemaining = 0;
7610 mPausedWriteLength = 0;
7611 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007612 // reset bytes written count to reflect that DSP buffers are empty after flush.
7613 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007614
Eric Laurentbfb1b832013-01-07 09:53:42 -08007615 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007616 // discard any pending drain or write ack by incrementing sequence
7617 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7618 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007619 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007620 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7621 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007622 }
7623}
7624
Andy Hung4b17e882023-07-07 13:47:37 -07007625void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007626{
Andy Hungf8635b62023-08-31 16:13:39 -07007627 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007628 if (PlaybackThread::invalidateTracks_l(streamType)) {
7629 mFlushPending = true;
7630 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007631}
7632
Andy Hung4b17e882023-07-07 13:47:37 -07007633void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07007634 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007635 if (PlaybackThread::invalidateTracks_l(portIds)) {
7636 mFlushPending = true;
7637 }
7638}
7639
Eric Laurentbfb1b832013-01-07 09:53:42 -08007640// ----------------------------------------------------------------------------
7641
Andy Hung4b17e882023-07-07 13:47:37 -07007642/* static */
7643sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007644 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007645 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007646 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007647}
7648
Andy Hung7535ed92023-07-17 17:05:00 -07007649DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007650 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007651 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007652 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007653 mWaitTimeMs(UINT_MAX)
7654{
7655 addOutputTrack(mainThread);
7656}
7657
Andy Hung4b17e882023-07-07 13:47:37 -07007658DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007659{
7660 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7661 mOutputTracks[i]->destroy();
7662 }
7663}
7664
Andy Hung4b17e882023-07-07 13:47:37 -07007665void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007666{
7667 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007668 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007669 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007670 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007671 if (mMixerBufferValid) {
7672 memset(mMixerBuffer, 0, mMixerBufferSize);
7673 } else {
7674 memset(mSinkBuffer, 0, mSinkBufferSize);
7675 }
Eric Laurent81784c32012-11-19 14:55:58 -08007676 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007677 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007678 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007679 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007680 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007681}
7682
Andy Hung4b17e882023-07-07 13:47:37 -07007683void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007684{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007685 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007686 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007687 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007688 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007689 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007690 }
7691 } else if (mBytesWritten != 0) {
7692 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7693 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007694 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007695 } else {
7696 // flush remaining overflow buffers in output tracks
7697 writeFrames = 0;
7698 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007699 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007700 }
7701}
7702
Andy Hung4b17e882023-07-07 13:47:37 -07007703ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007704{
7705 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007706 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7707
7708 // Consider the first OutputTrack for timestamp and frame counting.
7709
7710 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7711 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7712 // we always claim success.
7713 if (i == 0) {
7714 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7715 ALOGD_IF(correction != 0 && writeFrames != 0,
7716 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7717 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7718 mFramesWritten -= correction;
7719 }
7720
7721 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007722 }
Andy Hungcf10d742020-04-28 15:38:24 -07007723 if (mStandby) {
7724 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007725 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007726 mStandby = false;
7727 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007728 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007729}
7730
Andy Hung4b17e882023-07-07 13:47:37 -07007731void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007732{
7733 // DuplicatingThread implements standby by stopping all tracks
7734 for (size_t i = 0; i < outputTracks.size(); i++) {
7735 outputTracks[i]->stop();
7736 }
7737}
7738
Andy Hung8a5abfd2023-12-07 19:35:12 -08007739void DuplicatingThread::threadLoop_exit()
7740{
7741 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7742 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7743 // Do so here in the threadLoop_exit().
7744
7745 SortedVector <sp<IAfOutputTrack>> localTracks;
7746 {
7747 audio_utils::lock_guard l(mutex());
7748 localTracks = std::move(mOutputTracks);
7749 mOutputTracks.clear();
7750 }
7751 localTracks.clear();
7752 outputTracks.clear();
7753 PlaybackThread::threadLoop_exit();
7754}
7755
Andy Hung4b17e882023-07-07 13:47:37 -07007756void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007757{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007758 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007759
7760 std::stringstream ss;
7761 const size_t numTracks = mOutputTracks.size();
7762 ss << " " << numTracks << " OutputTracks";
7763 if (numTracks > 0) {
7764 ss << ":";
7765 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007766 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007767 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007768 if (thread.get() != nullptr) {
7769 ss << thread.get() << ", " << thread->id();
7770 } else {
7771 ss << "null";
7772 }
7773 ss << ")";
7774 }
7775 }
7776 ss << "\n";
7777 std::string result = ss.str();
7778 write(fd, result.c_str(), result.size());
7779}
7780
Andy Hung4b17e882023-07-07 13:47:37 -07007781void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007782{
7783 outputTracks = mOutputTracks;
7784}
7785
Andy Hung4b17e882023-07-07 13:47:37 -07007786void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007787{
7788 outputTracks.clear();
7789}
7790
Andy Hung4b17e882023-07-07 13:47:37 -07007791void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007792{
Andy Hungf8635b62023-08-31 16:13:39 -07007793 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007794 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7795 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7796 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7797 const size_t frameCount =
7798 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7799 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7800 // from different OutputTracks and their associated MixerThreads (e.g. one may
7801 // nearly empty and the other may be dropping data).
7802
Svet Ganov33761132021-05-13 22:51:08 +00007803 // TODO b/182392769: use attribution source util, move to server edge
7804 AttributionSourceState attributionSource = AttributionSourceState();
7805 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007806 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007807 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007808 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007809 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007810 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007811 this,
7812 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007813 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007814 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007815 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007816 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007817 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7818 if (status != NO_ERROR) {
7819 ALOGE("addOutputTrack() initCheck failed %d", status);
7820 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007821 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007822 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7823 mOutputTracks.add(outputTrack);
7824 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7825 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007826}
7827
Andy Hung4b17e882023-07-07 13:47:37 -07007828void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007829{
Andy Hungf8635b62023-08-31 16:13:39 -07007830 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007831 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7832 if (mOutputTracks[i]->thread() == thread) {
7833 mOutputTracks[i]->destroy();
7834 mOutputTracks.removeAt(i);
7835 updateWaitTime_l();
Andy Hung160664b2023-09-15 18:19:28 -07007836 // NO_THREAD_SAFETY_ANALYSIS
7837 // Lambda workaround: as thread != this
7838 // we can safely call the remote thread getOutput.
7839 const bool equalOutput =
7840 [&](){ return thread->getOutput() == mOutput; }();
7841 if (equalOutput) {
7842 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007843 }
Eric Laurent81784c32012-11-19 14:55:58 -08007844 return;
7845 }
7846 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007847 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007848}
7849
Andy Hungb17d24b2023-08-29 14:26:09 -07007850// caller must hold mutex()
Andy Hung4b17e882023-07-07 13:47:37 -07007851void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007852{
7853 mWaitTimeMs = UINT_MAX;
7854 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007855 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007856 if (strong != 0) {
7857 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7858 if (waitTimeMs < mWaitTimeMs) {
7859 mWaitTimeMs = waitTimeMs;
7860 }
7861 }
7862 }
7863}
7864
Andy Hung4b17e882023-07-07 13:47:37 -07007865bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007866{
7867 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007868 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007869 if (thread == 0) {
7870 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7871 outputTracks[i].get());
7872 return false;
7873 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007874 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007875 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007876 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007877 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7878 thread.get());
7879 return false;
7880 }
7881 }
7882 return true;
7883}
7884
Andy Hung4b17e882023-07-07 13:47:37 -07007885void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007886 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007887{
Kevin Rocard12381092018-04-11 09:19:59 -07007888 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7889 outputTrack->setMetadatas(metadata.tracks);
7890 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007891}
7892
Andy Hung4b17e882023-07-07 13:47:37 -07007893uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007894{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007895 // return half the wait time in microseconds.
7896 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007897}
7898
Andy Hung4b17e882023-07-07 13:47:37 -07007899void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007900{
7901 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7902 updateWaitTime_l();
7903
7904 MixerThread::cacheParameters_l();
7905}
7906
Eric Laurentb3f315a2021-07-13 15:09:05 +02007907// ----------------------------------------------------------------------------
7908
Andy Hung4b17e882023-07-07 13:47:37 -07007909/* static */
7910sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007911 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007912 AudioStreamOut* output,
7913 audio_io_handle_t id,
7914 bool systemReady,
7915 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007916 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007917}
7918
Andy Hung7535ed92023-07-17 17:05:00 -07007919SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007920 AudioStreamOut* output,
7921 audio_io_handle_t id,
7922 bool systemReady,
7923 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007924 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007925{
7926}
7927
Andy Hung4b17e882023-07-07 13:47:37 -07007928void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007929 // if mSupportedLatencyModes is empty, the HAL stream does not support
7930 // latency mode control and we can exit.
7931 if (mSupportedLatencyModes.empty()) {
7932 return;
7933 }
7934 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7935 if (mSupportedLatencyModes.size() == 1) {
7936 // If the HAL only support one latency mode currently, confirm the choice
7937 latencyMode = mSupportedLatencyModes[0];
7938 } else if (mSupportedLatencyModes.size() > 1) {
7939 // Request low latency if:
7940 // - The low latency mode is requested by the spatializer controller
7941 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7942 // AND
7943 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007944 for (const auto& track : mActiveTracks) {
7945 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007946 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007947 break;
7948 }
7949 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007950 }
7951
7952 if (latencyMode != mSetLatencyMode) {
7953 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007954 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7955 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007956 if (status == NO_ERROR) {
7957 mSetLatencyMode = latencyMode;
7958 }
7959 }
7960}
7961
Andy Hung4b17e882023-07-07 13:47:37 -07007962status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01007963 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007964 return BAD_VALUE;
7965 }
Andy Hungf8635b62023-08-31 16:13:39 -07007966 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007967 mRequestedLatencyMode = mode;
7968 return NO_ERROR;
7969}
7970
Andy Hung4b17e882023-07-07 13:47:37 -07007971void SpatializerThread::checkOutputStageEffects()
Andy Hungf8635b62023-08-31 16:13:39 -07007972NO_THREAD_SAFETY_ANALYSIS
7973// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007974{
7975 bool hasVirtualizer = false;
7976 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007977 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007978 {
Andy Hungf8635b62023-08-31 16:13:39 -07007979 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007980 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007981 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007982 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007983 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7984 }
7985
7986 finalDownMixer = mFinalDownMixer;
7987 mFinalDownMixer.clear();
7988 }
7989
7990 if (hasVirtualizer) {
7991 if (finalDownMixer != nullptr) {
7992 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007993 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007994 }
7995 finalDownMixer.clear();
7996 } else if (!hasDownMixer) {
7997 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07007998 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007999 EFFECT_UIID_DOWNMIX, &descriptors);
8000 if (status != NO_ERROR) {
8001 return;
8002 }
8003 ALOG_ASSERT(!descriptors.empty(),
8004 "%s getDescriptors() returned no error but empty list", __func__);
8005
8006 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8007 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008008 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008009
8010 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8011 ALOGW("%s error creating downmixer %d", __func__, status);
8012 finalDownMixer.clear();
8013 } else {
8014 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008015 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008016 }
8017 }
8018
8019 {
Andy Hungf8635b62023-08-31 16:13:39 -07008020 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008021 mFinalDownMixer = finalDownMixer;
8022 }
8023}
8024
Andy Hunge2514462023-12-06 14:59:24 -08008025void SpatializerThread::threadLoop_exit()
8026{
8027 // The Spatializer EffectHandle must be released on the PlaybackThread
8028 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8029 mFinalDownMixer.clear();
8030
8031 PlaybackThread::threadLoop_exit();
8032}
8033
Eric Laurent81784c32012-11-19 14:55:58 -08008034// ----------------------------------------------------------------------------
8035// Record
8036// ----------------------------------------------------------------------------
8037
Andy Hung7535ed92023-07-17 17:05:00 -07008038sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07008039 AudioStreamIn* input,
8040 audio_io_handle_t id,
8041 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07008042 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07008043}
8044
Andy Hung7535ed92023-07-17 17:05:00 -07008045RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008046 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008047 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008048 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008049 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07008050 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008051 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008052 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008053 mActiveTracks(&this->mLocalLog),
8054 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008055 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008056 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008057 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8058 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008059 // mFastCapture below
8060 , mFastCaptureFutex(0)
8061 // mInputSource
8062 // mPipeSink
8063 // mPipeSource
8064 , mPipeFramesP2(0)
8065 // mPipeMemory
8066 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008067 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008068 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008069{
Glenn Kastend7dca052015-03-05 16:05:54 -08008070 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07008071 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008072
George Burgess IVa8f90c12020-05-14 11:27:19 -07008073 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008074 mIsMsdDevice = strcmp(
8075 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8076 }
8077
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008078 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008079
Andy Hungc8fddf32018-08-08 18:32:37 -07008080 // TODO: We may also match on address as well as device type for
8081 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008082 // TODO: This property should be ensure that only contains one single device type.
8083 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8084 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008085 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8086 : AUDIO_DEVICE_NONE));
8087
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008088 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008089 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008090 size_t numCounterOffers = 0;
8091 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008092#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008093 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008094#else
8095 (void)
8096#endif
8097 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008098 ALOG_ASSERT(index == 0);
8099
8100 // initialize fast capture depending on configuration
8101 bool initFastCapture;
8102 switch (kUseFastCapture) {
8103 case FastCapture_Never:
8104 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008105 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008106 break;
8107 case FastCapture_Always:
8108 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008109 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008110 break;
8111 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008112 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008113 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008114 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008115 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8116 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8117 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008118 break;
8119 // case FastCapture_Dynamic:
8120 }
8121
8122 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008123 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008124 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008125 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8126 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008127 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008128 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008129 const sp<MemoryDealer> roHeap(readOnlyHeap());
8130 sp<IMemory> pipeMemory;
8131 if ((roHeap == 0) ||
8132 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008133 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008134 ALOGE("not enough memory for pipe buffer size=%zu; "
8135 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8136 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8137 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008138 goto failed;
8139 }
8140 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8141 memset(pipeBuffer, 0, pipeSize);
8142 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008143 const NBAIO_Format offersFast[1] = {format};
8144 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008145 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008146 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008147 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008148 mPipeSink = pipe;
8149 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008150 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008151 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008152 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008153 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008154 mPipeSource = pipeReader;
8155 mPipeFramesP2 = pipeFramesP2;
8156 mPipeMemory = pipeMemory;
8157
8158 // create fast capture
8159 mFastCapture = new FastCapture();
8160 FastCaptureStateQueue *sq = mFastCapture->sq();
8161#ifdef STATE_QUEUE_DUMP
8162 // FIXME
8163#endif
8164 FastCaptureState *state = sq->begin();
8165 state->mCblk = NULL;
8166 state->mInputSource = mInputSource.get();
8167 state->mInputSourceGen++;
8168 state->mPipeSink = pipe;
8169 state->mPipeSinkGen++;
8170 state->mFrameCount = mFrameCount;
8171 state->mCommand = FastCaptureState::COLD_IDLE;
8172 // already done in constructor initialization list
8173 //mFastCaptureFutex = 0;
8174 state->mColdFutexAddr = &mFastCaptureFutex;
8175 state->mColdGen++;
8176 state->mDumpState = &mFastCaptureDumpState;
8177#ifdef TEE_SINK
8178 // FIXME
8179#endif
Andy Hung7535ed92023-07-17 17:05:00 -07008180 mFastCaptureNBLogWriter =
8181 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008182 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8183 sq->end();
8184 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8185
8186 // start the fast capture
8187 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8188 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008189 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008190 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008191#ifdef AUDIO_WATCHDOG
8192 // FIXME
8193#endif
8194
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008195 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008196 }
Andy Hung8946a282018-04-19 20:04:56 -07008197#ifdef TEE_SINK
8198 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8199 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8200#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008201failed: ;
8202
8203 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008204}
8205
Andy Hung4b17e882023-07-07 13:47:37 -07008206RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008207{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008208 if (mFastCapture != 0) {
8209 FastCaptureStateQueue *sq = mFastCapture->sq();
8210 FastCaptureState *state = sq->begin();
8211 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8212 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8213 if (old == -1) {
8214 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8215 }
8216 }
8217 state->mCommand = FastCaptureState::EXIT;
8218 sq->end();
8219 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8220 mFastCapture->join();
8221 mFastCapture.clear();
8222 }
Andy Hung7535ed92023-07-17 17:05:00 -07008223 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8224 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008225 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008226}
8227
Andy Hung4b17e882023-07-07 13:47:37 -07008228void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008229{
Glenn Kastend7dca052015-03-05 16:05:54 -08008230 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008231}
8232
Andy Hung4b17e882023-07-07 13:47:37 -07008233void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008234{
8235 ALOGV(" preExit()");
Andy Hungf8635b62023-08-31 16:13:39 -07008236 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008237 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008238 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008239 track->invalidate();
8240 }
8241 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008242 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008243}
8244
Andy Hung4b17e882023-07-07 13:47:37 -07008245bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008246{
Eric Laurent81784c32012-11-19 14:55:58 -08008247 nsecs_t lastWarning = 0;
8248
8249 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008250
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008251reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008252 {
Andy Hungf8635b62023-08-31 16:13:39 -07008253 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008254 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008255 }
8256
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008257 // used to request a deferred sleep, to be executed later while mutex is unlocked
8258 uint32_t sleepUs = 0;
8259
Andy Hung1381a072023-10-20 16:41:18 -07008260 // timestamp correction enable is determined under lock, used in processing step.
8261 bool timestampCorrectionEnabled = false;
8262
Andy Hung446f4df2019-02-21 12:26:41 -08008263 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8264
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008265 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008266 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungfdb84b92024-03-15 10:15:10 -07008267 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8268 sp<IAfRecordTrack> activeTrack;
Andy Hungb2b01c62024-04-23 13:56:19 -07008269 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008270 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008271
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008272 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008273 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008274
Glenn Kasten735f45f2014-08-18 15:51:59 -07008275 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008276 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008277
Glenn Kasten735f45f2014-08-18 15:51:59 -07008278 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008279 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008280
Eric Laurent33403f02020-05-29 18:35:06 -07008281 bool silenceFastCapture = false;
8282
Andy Hungb17d24b2023-08-29 14:26:09 -07008283 { // scope for mutex()
8284 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008285
Eric Laurent021cf962014-05-13 10:18:14 -07008286 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008287
Eric Laurent000a4192014-01-29 15:17:32 -08008288 // check exitPending here because checkForNewParameters_l() and
Andy Hungb17d24b2023-08-29 14:26:09 -07008289 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008290 if (exitPending()) {
8291 break;
8292 }
8293
Eric Laurent5c25d562016-07-13 17:17:45 -07008294 // sleep with mutex unlocked
8295 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008296 ATRACE_BEGIN("sleepC");
Andy Hungb17d24b2023-08-29 14:26:09 -07008297 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008298 ATRACE_END();
8299 sleepUs = 0;
8300 continue;
8301 }
8302
Glenn Kasten2b806402013-11-20 16:37:38 -08008303 // if no active track(s), then standby and release wakelock
8304 size_t size = mActiveTracks.size();
8305 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008306 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008307 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008308 releaseWakeLock_l();
8309 ALOGV("RecordThread: loop stopping");
8310 // go to sleep
Andy Hungb17d24b2023-08-29 14:26:09 -07008311 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008312 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008313 goto reacquire_wakelock;
8314 }
8315
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008316 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008317 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008318 for (size_t i = 0; i < size; ) {
Andy Hungb2b01c62024-04-23 13:56:19 -07008319 if (activeTrack) { // ensure track release is outside lock.
8320 oldActiveTracks.emplace_back(std::move(activeTrack));
8321 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008322 activeTrack = mActiveTracks[i];
8323 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008324 if (activeTrack->isFastTrack()) {
8325 ALOG_ASSERT(fastTrackToRemove == 0);
8326 fastTrackToRemove = activeTrack;
8327 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008328 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008329 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008330 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008331 continue;
8332 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008333
Andy Hung11e74242023-06-26 19:20:57 -07008334 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008335 switch (activeTrackState) {
8336
Andy Hung11e74242023-06-26 19:20:57 -07008337 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008338 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008339 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008340 if (activeTrack->isFastTrack()) {
8341 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8342 // Keep a ref on fast track to wait for FastCapture thread to get updated
8343 // state before potential track removal
8344 fastTrackToRemove = activeTrack;
8345 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008346 doBroadcast = true;
8347 size--;
8348 continue;
8349
Andy Hung11e74242023-06-26 19:20:57 -07008350 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008351 sleepUs = 10000;
8352 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008353 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008354 continue;
8355
Andy Hung11e74242023-06-26 19:20:57 -07008356 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008357 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008358 if (mStandby) {
8359 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008360 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008361 mStandby = false;
8362 }
Andy Hung11e74242023-06-26 19:20:57 -07008363 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008364 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008365 break;
8366
Andy Hung11e74242023-06-26 19:20:57 -07008367 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008368 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008369 break;
8370
Andy Hung11e74242023-06-26 19:20:57 -07008371 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8372 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8373 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008374 default:
Andy Hungce685402018-10-05 17:23:27 -07008375 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8376 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008377 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008378
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008379 if (activeTrack->isFastTrack()) {
8380 ALOG_ASSERT(!mFastTrackAvail);
8381 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008382 // if the active fast track is silenced either:
8383 // 1) silence the whole capture from fast capture buffer if this is
8384 // the only active track
8385 // 2) invalidate this track: this will cause the client to reconnect and possibly
8386 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008387 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008388 if (activeTrack->isSilenced()) {
8389 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008390 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008391 } else {
8392 silenceFastCapture = true;
8393 }
8394 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008395 // Invalidate fast tracks if access to audio history is required as this is not
8396 // possible with fast tracks. Once the fast track has been invalidated, no new
8397 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8398 if (mMaxSharedAudioHistoryMs != 0) {
8399 invalidate = true;
8400 }
8401 if (invalidate) {
8402 activeTrack->invalidate();
8403 ALOG_ASSERT(fastTrackToRemove == 0);
8404 fastTrackToRemove = activeTrack;
8405 removeTrack_l(activeTrack);
8406 mActiveTracks.remove(activeTrack);
8407 size--;
8408 continue;
8409 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008410 fastTrack = activeTrack;
8411 }
Eric Laurent33403f02020-05-29 18:35:06 -07008412
8413 activeTracks.add(activeTrack);
8414 i++;
8415
Glenn Kasten9e982352013-08-14 14:39:50 -07008416 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008417
Andy Hung94dfbb42023-09-06 19:41:47 -07008418 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008419
Kevin Rocard069c2712018-03-29 19:09:14 -07008420 updateMetadata_l();
8421
Eric Laurent5c25d562016-07-13 17:17:45 -07008422 if (allStopped) {
8423 standbyIfNotAlreadyInStandby();
8424 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008425 if (doBroadcast) {
Andy Hungb17d24b2023-08-29 14:26:09 -07008426 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008427 }
8428
8429 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008430 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008431 if (sleepUs == 0) {
8432 sleepUs = kRecordThreadSleepUs;
8433 }
8434 continue;
8435 }
8436 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008437
Andy Hung1381a072023-10-20 16:41:18 -07008438 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008439 lockEffectChains_l(effectChains);
8440 }
8441
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008442 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008443
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008444 size_t size = effectChains.size();
8445 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008446 // thread mutex is not locked, but effect chain is locked
8447 effectChains[i]->process_l();
8448 }
8449
Glenn Kasten735f45f2014-08-18 15:51:59 -07008450 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008451 if (mFastCapture != 0) {
8452 FastCaptureStateQueue *sq = mFastCapture->sq();
8453 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008454 bool didModify = false;
8455 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008456 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8457 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8458 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8459 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8460 if (old == -1) {
8461 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8462 }
8463 }
8464 state->mCommand = FastCaptureState::READ_WRITE;
8465#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008466 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008467 FastThreadDumpState::kSamplingNforLowRamDevice :
8468 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008469#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008470 didModify = true;
8471 }
8472 audio_track_cblk_t *cblkOld = state->mCblk;
8473 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8474 if (cblkNew != cblkOld) {
8475 state->mCblk = cblkNew;
8476 // block until acked if removing a fast track
8477 if (cblkOld != NULL) {
8478 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8479 }
8480 didModify = true;
8481 }
jiabin01c8f562018-07-19 17:47:28 -07008482 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8483 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8484 if (state->mFastPatchRecordBufferProvider != abp) {
8485 state->mFastPatchRecordBufferProvider = abp;
8486 state->mFastPatchRecordFormat = fastTrack == 0 ?
8487 AUDIO_FORMAT_INVALID : fastTrack->format();
8488 didModify = true;
8489 }
Eric Laurent33403f02020-05-29 18:35:06 -07008490 if (state->mSilenceCapture != silenceFastCapture) {
8491 state->mSilenceCapture = silenceFastCapture;
8492 didModify = true;
8493 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008494 sq->end(didModify);
8495 if (didModify) {
8496 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008497#if 0
8498 if (kUseFastCapture == FastCapture_Dynamic) {
8499 mNormalSource = mPipeSource;
8500 }
8501#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008502 }
8503 }
8504
Glenn Kasten735f45f2014-08-18 15:51:59 -07008505 // now run the fast track destructor with thread mutex unlocked
8506 fastTrackToRemove.clear();
8507
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008508 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8509 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8510 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8511 // If destination is non-contiguous, first read past the nominal end of buffer, then
8512 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008513
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008514 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008515 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008516 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008517
8518 // If an NBAIO source is present, use it to read the normal capture's data
8519 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008520 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008521
8522 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8523 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8524 // we immediately retry the read() to get data and prevent another overflow.
8525 for (int retries = 0; retries <= 2; ++retries) {
8526 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8527 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8528 framesToRead);
8529 if (framesRead != OVERRUN) break;
8530 }
8531
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008532 const ssize_t availableToRead = mPipeSource->availableToRead();
8533 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008534 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008535 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008536 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8537 "more frames to read than fifo size, %zd > %zu",
8538 availableToRead, mPipeFramesP2);
8539 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8540 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8541 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8542 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008543 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8544 }
8545 if (framesRead < 0) {
8546 status_t status = (status_t) framesRead;
8547 switch (status) {
8548 case OVERRUN:
8549 ALOGW("overrun on read from pipe");
8550 framesRead = 0;
8551 break;
8552 case NEGOTIATE:
8553 ALOGE("re-negotiation is needed");
8554 framesRead = -1; // Will cause an attempt to recover.
8555 break;
8556 default:
8557 ALOGE("unknown error %d on read from pipe", status);
8558 break;
8559 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008560 }
8561 // otherwise use the HAL / AudioStreamIn directly
8562 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008563 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008564 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008565 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008566 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008567 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008568 if (result < 0) {
8569 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008570 } else {
8571 framesRead = bytesRead / mFrameSize;
8572 }
8573 }
8574
Andy Hung446f4df2019-02-21 12:26:41 -08008575 const int64_t lastIoEndNs = systemTime(); // end IO timing
8576
Andy Hung3f0c9022016-01-15 17:49:46 -08008577 // Update server timestamp with server stats
8578 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008579 if (framesRead >= 0) {
8580 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8581 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8582 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008583
8584 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008585 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008586 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008587 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008588 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8589 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8590 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008591 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008592 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8593
8594 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hung94dfbb42023-09-06 19:41:47 -07008595 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008596 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008597 id(), (long long)time, (long long)position);
8598 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8599 position = correctedTimestamp.mFrames;
8600 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008601 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008602 id(), (long long)time, (long long)position);
8603 }
8604
Andy Hung3f0c9022016-01-15 17:49:46 -08008605 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8606 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8607 // Note: In general record buffers should tend to be empty in
8608 // a properly running pipeline.
8609 //
8610 // Also, it is not advantageous to call get_presentation_position during the read
8611 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008612 } else {
8613 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008614 }
8615 }
Andy Hunge6c37112019-02-26 17:38:10 -08008616
8617 // From the timestamp, input read latency is negative output write latency.
8618 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008619 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008620 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8621 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8622 mLatencyMs.add(latencyMs);
8623 }
8624
Andy Hung3f0c9022016-01-15 17:49:46 -08008625 // Use this to track timestamp information
8626 // ALOGD("%s", mTimestamp.toString().c_str());
8627
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008628 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008629 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008630 // Force input into standby so that it tries to recover at next read attempt
8631 inputStandBy();
8632 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008633 }
8634 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008635 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008636 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008637 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008638 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008639
Andy Hung8946a282018-04-19 20:04:56 -07008640#ifdef TEE_SINK
8641 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8642#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008643 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008644 {
8645 size_t part1 = mRsmpInFramesP2 - rear;
8646 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008647 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008648 (framesRead - part1) * mFrameSize);
8649 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008650 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008651 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008652
8653 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008654
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008655 // loop over each active track
8656 for (size_t i = 0; i < size; i++) {
Andy Hung460e10f2024-06-17 15:42:48 -07008657 if (activeTrack) { // ensure track release is outside lock.
8658 oldActiveTracks.emplace_back(std::move(activeTrack));
8659 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008660 activeTrack = activeTracks[i];
8661
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008662 // skip fast tracks, as those are handled directly by FastCapture
8663 if (activeTrack->isFastTrack()) {
8664 continue;
8665 }
8666
Andy Hung73c02e42015-03-29 01:13:58 -07008667 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008668 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8669
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008670 enum {
8671 OVERRUN_UNKNOWN,
8672 OVERRUN_TRUE,
8673 OVERRUN_FALSE
8674 } overrun = OVERRUN_UNKNOWN;
8675
8676 // loop over getNextBuffer to handle circular sink
8677 for (;;) {
8678
Andy Hung11e74242023-06-26 19:20:57 -07008679 activeTrack->sinkBuffer().frameCount = ~0;
8680 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8681 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008682 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8683
Andy Hung73c02e42015-03-29 01:13:58 -07008684 // check available frames and handle overrun conditions
8685 // if the record track isn't draining fast enough.
8686 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008687 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008688 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008689 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008690 overrun = OVERRUN_TRUE;
8691 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008692 if (framesOut == 0 || framesIn == 0) {
8693 break;
8694 }
8695
Andy Hung6770c6f2015-04-07 13:43:36 -07008696 // Don't allow framesOut to be larger than what is possible with resampling
8697 // from framesIn.
8698 // This isn't strictly necessary but helps limit buffer resizing in
8699 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008700 if (audio_is_linear_pcm(activeTrack->format())) {
8701 framesOut = min(framesOut,
8702 destinationFramesPossible(
8703 framesIn, mSampleRate, activeTrack->sampleRate()));
8704 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008705
8706 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008707 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008708 // straight from RecordThread buffer to RecordTrack buffer.
8709 AudioBufferProvider::Buffer buffer;
8710 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008711 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008712 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008713 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008714 ALOGV_IF(buffer.frameCount != framesOut,
8715 "%s() read less than expected (%zu vs %zu)",
8716 __func__, buffer.frameCount, framesOut);
8717 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008718 memcpy(activeTrack->sinkBuffer().raw,
8719 buffer.raw, buffer.frameCount * mFrameSize);
8720 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008721 } else {
8722 framesOut = 0;
8723 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008724 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008725 }
8726 } else {
8727 // process frames from the RecordThread buffer provider to the RecordTrack
8728 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008729 framesOut = activeTrack->recordBufferConverter()->convert(
8730 activeTrack->sinkBuffer().raw,
8731 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008732 framesOut);
8733 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008734
8735 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8736 overrun = OVERRUN_FALSE;
8737 }
8738
Andy Hung93bb5732023-05-04 21:16:34 -07008739 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8740 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008741 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008742 if (framesToDrop == 0) {
8743 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008744 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008745 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008746 // Sanitize before releasing if the track has no access to the source data
8747 // An idle UID receives silence from non virtual devices until active
8748 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008749 memset(activeTrack->sinkBuffer().raw,
8750 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008751 }
Andy Hung11e74242023-06-26 19:20:57 -07008752 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008753 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008754 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008755 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008756 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008757 }
8758 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008759
8760 switch (overrun) {
8761 case OVERRUN_TRUE:
8762 // client isn't retrieving buffers fast enough
8763 if (!activeTrack->setOverflow()) {
8764 nsecs_t now = systemTime();
8765 // FIXME should lastWarning per track?
8766 if ((now - lastWarning) > kWarningThrottleNs) {
8767 ALOGW("RecordThread: buffer overflow");
8768 lastWarning = now;
8769 }
8770 }
8771 break;
8772 case OVERRUN_FALSE:
8773 activeTrack->clearOverflow();
8774 break;
8775 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008776 break;
8777 }
8778
Andy Hung3f0c9022016-01-15 17:49:46 -08008779 // update frame information and push timestamp out
8780 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008781 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008782 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8783 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008784 }
8785
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008786unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008787 // enable changes in effect chain
8788 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008789 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008790 if (audio_has_proportional_frames(mFormat)
8791 && loopCount == lastLoopCountRead + 1) {
8792 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8793 const double jitterMs =
8794 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8795 {framesRead, readPeriodNs},
8796 {0, 0} /* lastTimestamp */, mSampleRate);
8797 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8798
Andy Hungf8635b62023-08-31 16:13:39 -07008799 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008800 mIoJitterMs.add(jitterMs);
8801 mProcessTimeMs.add(processMs);
8802 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008803 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008804 // update timing info.
8805 mLastIoBeginNs = lastIoBeginNs;
8806 mLastIoEndNs = lastIoEndNs;
8807 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008808 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008809 mThreadloopExecutor.process(); // process any remaining deferred actions.
8810 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008811
Glenn Kasten93e471f2013-08-19 08:40:07 -07008812 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008813
8814 {
Andy Hungf8635b62023-08-31 16:13:39 -07008815 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008816 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008817 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008818 track->invalidate();
8819 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008820 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008821 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008822 }
8823
8824 releaseWakeLock();
8825
8826 ALOGV("RecordThread %p exiting", this);
8827 return false;
8828}
8829
Andy Hung4b17e882023-07-07 13:47:37 -07008830void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008831{
8832 if (!mStandby) {
8833 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008834 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008835 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008836 mStandby = true;
8837 }
8838}
8839
Andy Hung4b17e882023-07-07 13:47:37 -07008840void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008841{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008842 // Idle the fast capture if it's currently running
8843 if (mFastCapture != 0) {
8844 FastCaptureStateQueue *sq = mFastCapture->sq();
8845 FastCaptureState *state = sq->begin();
8846 if (!(state->mCommand & FastCaptureState::IDLE)) {
8847 state->mCommand = FastCaptureState::COLD_IDLE;
8848 state->mColdFutexAddr = &mFastCaptureFutex;
8849 state->mColdGen++;
8850 mFastCaptureFutex = 0;
8851 sq->end();
8852 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8853 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8854#if 0
8855 if (kUseFastCapture == FastCapture_Dynamic) {
8856 // FIXME
8857 }
8858#endif
8859#ifdef AUDIO_WATCHDOG
8860 // FIXME
8861#endif
8862 } else {
8863 sq->end(false /*didModify*/);
8864 }
8865 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008866 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008867 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008868
8869 // If going into standby, flush the pipe source.
8870 if (mPipeSource.get() != nullptr) {
8871 const ssize_t flushed = mPipeSource->flush();
8872 if (flushed > 0) {
8873 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8874 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8875 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8876 }
8877 }
Eric Laurent81784c32012-11-19 14:55:58 -08008878}
8879
Andy Hungb17d24b2023-08-29 14:26:09 -07008880// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07008881sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008882 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008883 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008884 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008885 audio_format_t format,
8886 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008887 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008888 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008889 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008890 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008891 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008892 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008893 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008894 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008895 audio_port_handle_t portId,
8896 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008897{
Glenn Kasten74935e42013-12-19 08:56:45 -08008898 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008899 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008900 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008901 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008902 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008903 audio_input_flags_t requestedFlags = *flags;
8904 uint32_t sampleRate;
8905
8906 lStatus = initCheck();
8907 if (lStatus != NO_ERROR) {
8908 ALOGE("createRecordTrack_l() audio driver not initialized");
8909 goto Exit;
8910 }
8911
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008912 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8913 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8914 lStatus = BAD_VALUE;
8915 goto Exit;
8916 }
8917
Eric Laurentec376dc2021-04-08 20:41:22 +02008918 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008919 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008920 lStatus = PERMISSION_DENIED;
8921 goto Exit;
8922 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008923 if (maxSharedAudioHistoryMs < 0
Andy Hung409572b2023-07-19 12:47:35 -07008924 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008925 lStatus = BAD_VALUE;
8926 goto Exit;
8927 }
8928 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008929 if (*pSampleRate == 0) {
8930 *pSampleRate = mSampleRate;
8931 }
8932 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008933
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008934 // special case for FAST flag considered OK if fast capture is present and access to
8935 // audio history is not required
8936 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008937 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8938 }
8939
Eric Laurentf14db3c2017-12-08 14:20:36 -08008940 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008941 if ((*flags & inputFlags) != *flags) {
8942 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8943 " input flags (%08x)",
8944 *flags, inputFlags);
8945 *flags = (audio_input_flags_t)(*flags & inputFlags);
8946 }
Eric Laurent81784c32012-11-19 14:55:58 -08008947
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008948 // client expresses a preference for FAST and no access to audio history,
8949 // but we get the final say
8950 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008951 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008952 // we formerly checked for a callback handler (non-0 tid),
8953 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008954 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008955 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008956 // Frame count is not specified (0), or is less than or equal the pipe depth.
8957 // It is OK to provide a higher capacity than requested.
8958 // We will force it to mPipeFramesP2 below.
8959 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008960 // PCM data
8961 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008962 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008963 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008964 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008965 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008966 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008967 hasFastCapture() &&
8968 // there are sufficient fast track slots available
8969 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008970 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008971 // check compatibility with audio effects.
Andy Hungf8635b62023-08-31 16:13:39 -07008972 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008973 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008974 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008975 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008976 audio_input_flags_t old = *flags;
8977 chain->checkInputFlagCompatibility(flags);
8978 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008979 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8980 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008981 }
8982 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008983 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008984 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8985 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008986 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008987 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8988 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008989 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008990 this, frameCount, mFrameCount, mPipeFramesP2,
8991 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008992 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008993 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008994 }
8995 }
8996
Eric Laurentf14db3c2017-12-08 14:20:36 -08008997 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8998 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8999 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9000 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9001 lStatus = BAD_TYPE;
9002 goto Exit;
9003 }
9004
Glenn Kasten74105912014-07-03 12:28:53 -07009005 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009006 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009007 // fast track: frame count is exactly the pipe depth
9008 frameCount = mPipeFramesP2;
9009 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009010 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009011 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009012 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9013 // or 20 ms if there is a fast capture
9014 // TODO This could be a roundupRatio inline, and const
9015 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9016 * sampleRate + mSampleRate - 1) / mSampleRate;
9017 // minimum number of notification periods is at least kMinNotifications,
9018 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9019 static const size_t kMinNotifications = 3;
9020 static const uint32_t kMinMs = 30;
9021 // TODO This could be a roundupRatio inline
9022 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9023 // TODO This could be a roundupRatio inline
9024 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9025 maxNotificationFrames;
9026 const size_t minFrameCount = maxNotificationFrames *
9027 max(kMinNotifications, minNotificationsByMs);
9028 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009029 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9030 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009031 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009032 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009033 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009034 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009035
Andy Hungb17d24b2023-08-29 14:26:09 -07009036 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07009037 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009038 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009039 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009040 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009041 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009042 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009043 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009044 }
Eric Laurent81784c32012-11-19 14:55:58 -08009045
Andy Hung11e74242023-06-26 19:20:57 -07009046 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009047 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009048 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07009049 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009050 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009051
Glenn Kasten03003332013-08-06 15:40:54 -07009052 lStatus = track->initCheck();
9053 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009054 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009055 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009056 goto Exit;
9057 }
9058 mTracks.add(track);
9059
Eric Laurent05067782016-06-01 18:27:28 -07009060 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009061 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9062 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9063 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009064 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009065 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009066
9067 if (maxSharedAudioHistoryMs != 0) {
9068 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9069 }
Eric Laurent81784c32012-11-19 14:55:58 -08009070 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009071
Eric Laurent81784c32012-11-19 14:55:58 -08009072 lStatus = NO_ERROR;
9073
9074Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009075 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009076 return track;
9077}
9078
Andy Hung4b17e882023-07-07 13:47:37 -07009079status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009080 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009081 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009082{
9083 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9084 sp<ThreadBase> strongMe = this;
9085 status_t status = NO_ERROR;
9086
9087 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009088 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009089 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07009090 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07009091 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009092 event, triggerSession,
9093 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009094 }
9095
9096 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009097 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hungf8635b62023-08-31 16:13:39 -07009098 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009099 if (recordTrack->isInvalid()) {
9100 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009101 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9102 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009103 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009104 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07009105 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009106 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9107 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009108 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07009109 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009110 } else {
Andy Hung11e74242023-06-26 19:20:57 -07009111 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009112 }
9113 return status;
9114 }
9115
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009116 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9117 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9118 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07009119 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009120 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009121 if (recordTrack->isExternalTrack()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009122 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009123 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07009124 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009125 if (recordTrack->isInvalid()) {
9126 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07009127 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9128 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009129 // STARTING_2 forces destroy to call stopInput.
9130 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009131 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9132 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009133 }
Andy Hung11e74242023-06-26 19:20:57 -07009134 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009135 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07009136 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009137 // Someone else has changed state, let them take over,
9138 // leave mState in the new state.
9139 recordTrack->clearSyncStartEvent();
9140 return INVALID_OPERATION;
9141 }
9142 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009143 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009144 ALOGW("%s(%d): startInput failed, status %d",
9145 __func__, recordTrack->id(), status);
9146 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9147 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009148 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009149 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009150 return status;
9151 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009152 sendIoConfigEvent_l(
9153 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009154 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009155
9156 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9157
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009158 // Catch up with current buffer indices if thread is already running.
9159 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9160 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9161 // see previously buffered data before it called start(), but with greater risk of overrun.
9162
Andy Hung11e74242023-06-26 19:20:57 -07009163 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009164 if (!recordTrack->isDirect()) {
9165 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07009166 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009167 }
Andy Hung11e74242023-06-26 19:20:57 -07009168 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009169 // signal thread to start
Andy Hungb17d24b2023-08-29 14:26:09 -07009170 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009171 return status;
9172 }
Eric Laurent81784c32012-11-19 14:55:58 -08009173}
9174
Andy Hung4b17e882023-07-07 13:47:37 -07009175void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009176{
Andy Hung4b17e882023-07-07 13:47:37 -07009177 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009178
9179 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07009180 sp<IAfTrackBase> ptr =
9181 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9182 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07009183 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07009184 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009185 }
Eric Laurent81784c32012-11-19 14:55:58 -08009186 }
9187}
9188
Andy Hung4b17e882023-07-07 13:47:37 -07009189bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009190 ALOGV("RecordThread::stop");
Andy Hungb17d24b2023-08-29 14:26:09 -07009191 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009192 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07009193 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009194 return false;
9195 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009196 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07009197 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009198
Andy Hungabfab202019-03-07 19:45:54 -08009199 // NOTE: Waiting here is important to keep stop synchronous.
9200 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07009201 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009202 mWaitWorkCV.notify_all(); // signal thread to stop
9203 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009204 }
Andy Hungce685402018-10-05 17:23:27 -07009205
Andy Hung11e74242023-06-26 19:20:57 -07009206 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009207 ALOGV("Record stopped OK");
9208 return true;
9209 }
Andy Hungce685402018-10-05 17:23:27 -07009210
9211 // don't handle anything - we've been invalidated or restarted and in a different state
9212 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07009213 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009214 return false;
9215}
9216
Andy Hung4b17e882023-07-07 13:47:37 -07009217bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009218{
9219 return false;
9220}
9221
Andy Hung4b17e882023-07-07 13:47:37 -07009222status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009223{
9224#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9225 if (!isValidSyncEvent(event)) {
9226 return BAD_VALUE;
9227 }
9228
Glenn Kastend848eb42016-03-08 13:42:11 -08009229 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009230 status_t ret = NAME_NOT_FOUND;
9231
Andy Hungf8635b62023-08-31 16:13:39 -07009232 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009233
9234 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009235 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009236 if (eventSession == track->sessionId()) {
9237 (void) track->setSyncEvent(event);
9238 ret = NO_ERROR;
9239 }
9240 }
9241 return ret;
9242#else
9243 return BAD_VALUE;
9244#endif
9245}
9246
Andy Hung4b17e882023-07-07 13:47:37 -07009247status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07009248 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009249{
9250 ALOGV("RecordThread::getActiveMicrophones");
Andy Hungf8635b62023-08-31 16:13:39 -07009251 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009252 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009253 return NO_INIT;
9254 }
jiabin9ff780e2018-03-19 18:19:52 -07009255 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9256 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009257}
9258
Andy Hung4b17e882023-07-07 13:47:37 -07009259status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009260 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009261{
Paul McLean12340082019-03-19 09:35:05 -06009262 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hungf8635b62023-08-31 16:13:39 -07009263 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009264 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009265 return NO_INIT;
9266 }
Paul McLean12340082019-03-19 09:35:05 -06009267 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009268}
9269
Andy Hung4b17e882023-07-07 13:47:37 -07009270status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009271{
Paul McLean12340082019-03-19 09:35:05 -06009272 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hungf8635b62023-08-31 16:13:39 -07009273 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009274 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009275 return NO_INIT;
9276 }
Paul McLean12340082019-03-19 09:35:05 -06009277 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009278}
9279
Andy Hung4b17e882023-07-07 13:47:37 -07009280status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009281 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9282 int64_t sharedAudioStartMs) {
Andy Hungf8635b62023-08-31 16:13:39 -07009283 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009284 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9285}
9286
Andy Hung4b17e882023-07-07 13:47:37 -07009287status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009288 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9289 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009290
Eric Laurentec376dc2021-04-08 20:41:22 +02009291 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9292 return BAD_VALUE;
9293 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009294
9295 if (sharedAudioStartMs < 0
9296 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009297 return BAD_VALUE;
9298 }
9299
Eric Laurent2407ce32021-04-26 14:56:03 +02009300 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9301 // As we cannot detect more than one wraparound, only accept values up current write position
9302 // after one wraparound
9303 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9304 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009305 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009306 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9307 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009308 // Bring the start frame position within the input buffer to match the documented
9309 // "best effort" behavior of the API.
9310 if (sharedOffset < 0) {
9311 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009312 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009313 sharedAudioStartFrames =
9314 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009315 }
9316
Eric Laurentec376dc2021-04-08 20:41:22 +02009317 mSharedAudioPackageName = sharedAudioPackageName;
9318 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009319 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009320 } else {
9321 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009322 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009323 }
9324 return NO_ERROR;
9325}
9326
Andy Hung4b17e882023-07-07 13:47:37 -07009327void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009328 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9329 mSharedAudioStartFrames = -1;
9330 mSharedAudioPackageName = "";
9331}
9332
Andy Hung4b17e882023-07-07 13:47:37 -07009333ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009334{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009335 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009336 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009337 }
9338 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009339 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009340 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009341 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009342 }
9343 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009344 MetadataUpdate change;
9345 change.recordMetadataUpdate = metadata.tracks;
9346 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009347}
9348
Andy Hungb17d24b2023-08-29 14:26:09 -07009349// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07009350void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009351{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009352 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009353 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009354
Eric Laurent81784c32012-11-19 14:55:58 -08009355 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009356 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009357 removeTrack_l(track);
9358 }
9359}
9360
Andy Hung4b17e882023-07-07 13:47:37 -07009361void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009362{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009363 String8 result;
9364 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009365 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009366
Eric Laurent81784c32012-11-19 14:55:58 -08009367 mTracks.remove(track);
9368 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009369 if (track->isFastTrack()) {
9370 ALOG_ASSERT(!mFastTrackAvail);
9371 mFastTrackAvail = true;
9372 }
Eric Laurent81784c32012-11-19 14:55:58 -08009373}
9374
Andy Hung4b17e882023-07-07 13:47:37 -07009375void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009376{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009377 AudioStreamIn *input = mInput;
9378 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9379 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009380 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009381 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009382 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009383 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009384 }
Andy Hungbfa64962017-06-12 14:43:19 -07009385
9386 if (input != nullptr) {
9387 dprintf(fd, " Hal stream dump:\n");
9388 (void)input->stream->dump(fd);
9389 }
9390
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009391 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009392 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009393
Glenn Kasten2f90c512015-12-02 11:40:09 -08009394 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9395 // while we are dumping it. It may be inconsistent, but it won't mutate!
9396 // This is a large object so we place it on the heap.
9397 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009398 const std::unique_ptr<FastCaptureDumpState> copy =
9399 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009400 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009401}
9402
Andy Hung4b17e882023-07-07 13:47:37 -07009403void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009404{
Eric Laurent81784c32012-11-19 14:55:58 -08009405 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009406 size_t numtracks = mTracks.size();
9407 size_t numactive = mActiveTracks.size();
9408 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009409 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009410 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009411 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009412 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009413 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009414 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009415 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009416 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009417 if (track != 0) {
9418 bool active = mActiveTracks.indexOf(track) >= 0;
9419 if (active) {
9420 numactiveseen++;
9421 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009422 result.append(prefix);
9423 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009424 }
Eric Laurent81784c32012-11-19 14:55:58 -08009425 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009426 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009427 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009428 }
9429
Marco Nelissenb2208842014-02-07 14:00:50 -08009430 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009431 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009432 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009433 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009434 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009435 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009436 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009437 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009438 result.append(prefix);
9439 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009440 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009441 }
Eric Laurent81784c32012-11-19 14:55:58 -08009442
9443 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009444 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009445}
9446
Andy Hung4b17e882023-07-07 13:47:37 -07009447void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009448{
Andy Hungf8635b62023-08-31 16:13:39 -07009449 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009450 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009451 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009452 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009453 track->setSilenced(silenced);
9454 }
9455 }
9456}
Andy Hung73c02e42015-03-29 01:13:58 -07009457
Andy Hung11e74242023-06-26 19:20:57 -07009458void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009459{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009460 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009461 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009462 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009463 const int32_t rear = recordThread->mRsmpInRear;
9464 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009465 if (mRecordTrack->startFrames() >= 0) {
9466 int32_t startFrames = mRecordTrack->startFrames();
9467 // Accept a recent wraparound of mRsmpInRear
9468 if (startFrames <= rear) {
9469 deltaFrames = rear - startFrames;
9470 } else {
9471 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009472 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009473 // start frame cannot be further in the past than start of resampling buffer
9474 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9475 deltaFrames = recordThread->mRsmpInFrames;
9476 }
9477 }
9478 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009479}
9480
Andy Hung11e74242023-06-26 19:20:57 -07009481void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009482 size_t *framesAvailable, bool *hasOverrun)
9483{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009484 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009485 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009486 const int32_t rear = recordThread->mRsmpInRear;
9487 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009488 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009489
9490 size_t framesIn;
9491 bool overrun = false;
9492 if (filled < 0) {
9493 // should not happen, but treat like a massive overrun and re-sync
9494 framesIn = 0;
9495 mRsmpInFront = rear;
9496 overrun = true;
9497 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9498 framesIn = (size_t) filled;
9499 } else {
9500 // client is not keeping up with server, but give it latest data
9501 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009502 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9503 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009504 overrun = true;
9505 }
9506 if (framesAvailable != NULL) {
9507 *framesAvailable = framesIn;
9508 }
9509 if (hasOverrun != NULL) {
9510 *hasOverrun = overrun;
9511 }
9512}
9513
Eric Laurent81784c32012-11-19 14:55:58 -08009514// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009515status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009516 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009517{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009518 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009519 if (threadBase == 0) {
9520 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009521 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009522 return NOT_ENOUGH_DATA;
9523 }
Andy Hung4b17e882023-07-07 13:47:37 -07009524 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009525 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009526 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009527 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009528 // FIXME should not be P2 (don't want to increase latency)
9529 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009530 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009531 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009532
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009533 front &= recordThread->mRsmpInFramesP2 - 1;
9534 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009535 if (part1 > (size_t) filled) {
9536 part1 = filled;
9537 }
9538 size_t ask = buffer->frameCount;
9539 ALOG_ASSERT(ask > 0);
9540 if (part1 > ask) {
9541 part1 = ask;
9542 }
9543 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009544 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009545 buffer->raw = NULL;
9546 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009547 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009548 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009549 }
9550
Andy Hung57446612015-04-19 23:56:46 -07009551 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009552 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009553 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009554 return NO_ERROR;
9555}
9556
9557// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009558void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009559 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009560{
Hongwei Wang95e37682019-04-12 11:13:36 -07009561 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009562 if (stepCount == 0) {
9563 return;
9564 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009565 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009566 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009567 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009568 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009569 buffer->frameCount = 0;
9570}
9571
Andy Hung4b17e882023-07-07 13:47:37 -07009572void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009573{
Andy Hungf8635b62023-08-31 16:13:39 -07009574 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009575 checkBtNrec_l();
9576}
9577
Andy Hung4b17e882023-07-07 13:47:37 -07009578void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009579{
9580 // disable AEC and NS if the device is a BT SCO headset supporting those
9581 // pre processings
Andy Hung94dfbb42023-09-06 19:41:47 -07009582 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009583 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009584 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9585 for (size_t i = 0; i < mEffectChains.size(); i++) {
9586 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9587 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9588 }
9589 }
9590}
9591
Andy Hung97a893e2015-03-29 01:03:07 -07009592
Andy Hung4b17e882023-07-07 13:47:37 -07009593bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009594 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009595{
9596 bool reconfig = false;
9597
Eric Laurent10351942014-05-08 18:49:52 -07009598 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009599
Eric Laurent10351942014-05-08 18:49:52 -07009600 audio_format_t reqFormat = mFormat;
9601 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009602 // 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 +08009603 [[maybe_unused]] audio_channel_mask_t channelMask =
9604 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009605
9606 AudioParameter param = AudioParameter(keyValuePair);
9607 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009608
9609 // scope for AutoPark extends to end of method
9610 AutoPark<FastCapture> park(mFastCapture);
9611
Eric Laurent10351942014-05-08 18:49:52 -07009612 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9613 // channel count change can be requested. Do we mandate the first client defines the
9614 // HAL sampling rate and channel count or do we allow changes on the fly?
9615 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9616 samplingRate = value;
9617 reconfig = true;
9618 }
9619 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009620 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009621 status = BAD_VALUE;
9622 } else {
9623 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009624 reconfig = true;
9625 }
Eric Laurent10351942014-05-08 18:49:52 -07009626 }
9627 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9628 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009629 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009630 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009631 status = BAD_VALUE;
9632 } else {
9633 channelMask = mask;
9634 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009635 }
Eric Laurent10351942014-05-08 18:49:52 -07009636 }
9637 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9638 // do not accept frame count changes if tracks are open as the track buffer
9639 // size depends on frame count and correct behavior would not be guaranteed
9640 // if frame count is changed after track creation
9641 if (mActiveTracks.size() > 0) {
9642 status = INVALID_OPERATION;
9643 } else {
9644 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009645 }
Eric Laurent10351942014-05-08 18:49:52 -07009646 }
9647 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009648 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009649 }
9650 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9651 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009652 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009653 }
Glenn Kastene198c362013-08-13 09:13:36 -07009654
Eric Laurent10351942014-05-08 18:49:52 -07009655 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009656 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009657 if (status == INVALID_OPERATION) {
9658 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009659 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009660 }
9661 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009662 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009663 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9664 if (mInput->stream->getAudioProperties(&config) == OK &&
9665 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9666 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009667 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009668 status = NO_ERROR;
9669 }
Eric Laurent81784c32012-11-19 14:55:58 -08009670 }
Eric Laurent10351942014-05-08 18:49:52 -07009671 if (status == NO_ERROR) {
9672 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009673 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009674 }
9675 }
Eric Laurent81784c32012-11-19 14:55:58 -08009676 }
Eric Laurent10351942014-05-08 18:49:52 -07009677
Eric Laurent81784c32012-11-19 14:55:58 -08009678 return reconfig;
9679}
9680
Andy Hung4b17e882023-07-07 13:47:37 -07009681String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009682{
Andy Hungf8635b62023-08-31 16:13:39 -07009683 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009684 if (initCheck() == NO_ERROR) {
9685 String8 out_s8;
9686 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9687 return out_s8;
9688 }
Eric Laurent81784c32012-11-19 14:55:58 -08009689 }
Andy Hung920f6572022-10-06 12:09:49 -07009690 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009691}
9692
Andy Hung94dfbb42023-09-06 19:41:47 -07009693void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009694 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009695 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009696 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009697 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009698 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009699 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009700 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9701 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009702 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009703 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009704 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009705 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009706 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009707 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009708 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009709 break;
9710 }
Andy Hung94dfbb42023-09-06 19:41:47 -07009711 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009712}
9713
Andy Hung4b17e882023-07-07 13:47:37 -07009714void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009715{
Dean Wheatley6c009512023-10-23 09:34:14 +11009716 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9717 mSampleRate = audioConfig.sample_rate;
9718 mChannelMask = audioConfig.channel_mask;
9719 if (!audio_is_input_channel(mChannelMask)) {
9720 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9721 }
9722
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009723 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009724
9725 // Get actual HAL format.
9726 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9727 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9728 // Get format from the shim, which will be different than the HAL format
9729 // if recording compressed audio from IEC61937 wrapped sources.
9730 mFormat = audioConfig.format;
9731 if (!audio_is_valid_format(mFormat)) {
9732 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9733 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009734 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009735 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9736 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009737 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009738 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009739 ALOGI("HAL format %#x is not linear pcm", mFormat);
9740 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009741 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009742 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9743 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009744 result = mInput->stream->getBufferSize(&mBufferSize);
9745 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009746 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009747 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9748 "mBufferSize=%zu, mFrameCount=%zu",
9749 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009750
Eric Laurentec376dc2021-04-08 20:41:22 +02009751 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9752 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009753 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009754
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009755 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9756 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009757
9758 audio_input_flags_t flags = mInput->flags;
9759 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9760 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07009761 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009762 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9763 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9764 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9765 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9766 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9767 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009768}
9769
Andy Hung4b17e882023-07-07 13:47:37 -07009770uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009771{
Andy Hungf8635b62023-08-31 16:13:39 -07009772 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009773 uint32_t result;
9774 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9775 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009776 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009777 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009778}
9779
Andy Hung4b17e882023-07-07 13:47:37 -07009780KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009781{
Glenn Kastend848eb42016-03-08 13:42:11 -08009782 KeyedVector<audio_session_t, bool> ids;
Andy Hungf8635b62023-08-31 16:13:39 -07009783 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009784 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009785 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009786 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009787 if (ids.indexOfKey(sessionId) < 0) {
9788 ids.add(sessionId, true);
9789 }
9790 }
9791 return ids;
9792}
9793
Andy Hung4b17e882023-07-07 13:47:37 -07009794AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009795{
Andy Hungf8635b62023-08-31 16:13:39 -07009796 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009797 AudioStreamIn *input = mInput;
9798 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009799 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009800 return input;
9801}
9802
Andy Hungb17d24b2023-08-29 14:26:09 -07009803// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009804sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009805{
9806 if (mInput == NULL) {
9807 return NULL;
9808 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009809 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009810}
9811
Andy Hung4b17e882023-07-07 13:47:37 -07009812status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009813{
Eric Laurent81784c32012-11-19 14:55:58 -08009814 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009815 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009816 chain->setInBuffer(NULL);
9817 chain->setOutBuffer(NULL);
9818
9819 checkSuspendOnAddEffectChain_l(chain);
9820
Eric Laurent1b928682014-10-02 19:41:47 -07009821 // make sure enabled pre processing effects state is communicated to the HAL as we
9822 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009823 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009824
Eric Laurent81784c32012-11-19 14:55:58 -08009825 mEffectChains.add(chain);
9826
9827 return NO_ERROR;
9828}
9829
Andy Hung4b17e882023-07-07 13:47:37 -07009830size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009831{
9832 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009833
9834 for (size_t i = 0; i < mEffectChains.size(); i++) {
9835 if (chain == mEffectChains[i]) {
9836 mEffectChains.removeAt(i);
9837 break;
9838 }
Eric Laurent81784c32012-11-19 14:55:58 -08009839 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009840 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009841}
9842
Andy Hung4b17e882023-07-07 13:47:37 -07009843status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009844 audio_patch_handle_t *handle)
9845{
9846 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009847
9848 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009849 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009850 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009851 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009852 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009853 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009854 }
9855
Eric Laurentd8365c52017-07-16 15:27:05 -07009856 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009857
9858 // store new source and send to effects
9859 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9860 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009861 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009862 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009863 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009864 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009865
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009866 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009867 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9868 status = hwDevice->createAudioPatch(patch->num_sources,
9869 patch->sources,
9870 patch->num_sinks,
9871 patch->sinks,
9872 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009873 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009874 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9875 patch->sinks[0].ext.mix.usecase.source,
9876 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009877 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009878 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009879
jiabinc52b1ff2019-10-31 17:20:42 -07009880 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009881 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009882 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009883 }
Eric Laurent296fb132015-05-01 11:38:42 -07009884
Andy Hungc2b11cb2020-04-22 09:04:01 -07009885 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009886 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009887 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009888 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009889 // also dispatch to active AudioRecords
9890 for (const auto &track : mActiveTracks) {
9891 track->logEndInterval();
9892 track->logBeginInterval(pathSourcesAsString);
9893 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009894 // Force meteadata update after a route change
9895 mActiveTracks.setHasChanged();
9896
Eric Laurent1c333e22014-05-20 10:48:17 -07009897 return status;
9898}
9899
Andy Hung4b17e882023-07-07 13:47:37 -07009900status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009901{
9902 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009903
jiabinc52b1ff2019-10-31 17:20:42 -07009904 mPatch = audio_patch{};
9905 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009906
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009907 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009908 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9909 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009910 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009911 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009912 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009913 // Force meteadata update after a route change
9914 mActiveTracks.setHasChanged();
9915
Eric Laurent1c333e22014-05-20 10:48:17 -07009916 return status;
9917}
9918
Andy Hung4b17e882023-07-07 13:47:37 -07009919void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009920{
Andy Hungf8635b62023-08-31 16:13:39 -07009921 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009922 mOutDevices = outDevices;
9923 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9924 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009925 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009926 }
9927}
9928
Andy Hung4b17e882023-07-07 13:47:37 -07009929int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009930{
9931 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009932 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009933 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009934 int32_t oldestFront = mRsmpInRear;
9935 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009936 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009937 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009938 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009939 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009940 if (filled > maxFilled) {
9941 oldestFront = front;
9942 maxFilled = filled;
9943 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009944 }
Andy Hung920f6572022-10-06 12:09:49 -07009945 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009946 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9947 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009948 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009949}
9950
Andy Hung4b17e882023-07-07 13:47:37 -07009951void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009952{
9953 if (offset == 0) {
9954 return;
9955 }
9956 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009957 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009958 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009959 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009960 }
9961}
9962
Andy Hung4b17e882023-07-07 13:47:37 -07009963void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009964{
9965 // This is the formula for calculating the temporary buffer size.
9966 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9967 // 1 full output buffer, regardless of the alignment of the available input.
9968 // The value is somewhat arbitrary, and could probably be even larger.
9969 // A larger value should allow more old data to be read after a track calls start(),
9970 // without increasing latency.
9971 //
9972 // Note this is independent of the maximum downsampling ratio permitted for capture.
9973 size_t minRsmpInFrames = mFrameCount * 7;
9974
9975 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9976 // capture history available to another client using the same session ID:
9977 // dimension the resampler input buffer accordingly.
9978
9979 // Get oldest client read position: getOldestFront_l() must be called before altering
9980 // mRsmpInRear, or mRsmpInFrames
9981 int32_t previousFront = getOldestFront_l();
9982 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9983 int32_t previousRear = mRsmpInRear;
9984 mRsmpInRear = 0;
9985
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009986 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009987 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009988 "resizeInputBuffer_l() called with invalid max shared history %d",
9989 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009990 if (maxSharedAudioHistoryMs != 0) {
9991 // resizeInputBuffer_l should never be called with a non zero shared history if the
9992 // buffer was not already allocated
9993 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9994 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9995 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9996 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009997 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009998 return;
9999 }
10000 mRsmpInFrames = rsmpInFrames;
10001 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010002 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010003 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10004 // initialized
10005 if (mRsmpInFrames < minRsmpInFrames) {
10006 mRsmpInFrames = minRsmpInFrames;
10007 }
10008 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10009
10010 // TODO optimize audio capture buffer sizes ...
10011 // Here we calculate the size of the sliding buffer used as a source
10012 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10013 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10014 // be better to have it derived from the pipe depth in the long term.
10015 // The current value is higher than necessary. However it should not add to latency.
10016
10017 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10018 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10019
10020 void *rsmpInBuffer;
10021 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10022 // if posix_memalign fails, will segv here.
10023 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10024
10025 // Copy audio history if any from old buffer before freeing it
10026 if (previousRear != 0) {
10027 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10028 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10029
10030 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10031 previousFront &= previousRsmpInFramesP2 - 1;
10032 size_t part1 = previousRsmpInFramesP2 - previousFront;
10033 if (part1 > (size_t) unread) {
10034 part1 = unread;
10035 }
10036 if (part1 != 0) {
10037 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10038 part1 * mFrameSize);
10039 mRsmpInRear = part1;
10040 part1 = unread - part1;
10041 if (part1 != 0) {
10042 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10043 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10044 mRsmpInRear += part1;
10045 }
10046 }
10047 // Update front for all clients according to new rear
10048 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10049 } else {
10050 mRsmpInRear = 0;
10051 }
10052 free(mRsmpInBuffer);
10053 mRsmpInBuffer = rsmpInBuffer;
10054}
10055
Andy Hung4b17e882023-07-07 13:47:37 -070010056void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010057{
Andy Hungf8635b62023-08-31 16:13:39 -070010058 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010059 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010060 if (record->getSource()) {
10061 mSource = record->getSource();
10062 }
Eric Laurent83b88082014-06-20 18:31:16 -070010063}
10064
Andy Hung4b17e882023-07-07 13:47:37 -070010065void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010066{
Andy Hungf8635b62023-08-31 16:13:39 -070010067 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010068 if (mSource == record->getSource()) {
10069 mSource = mInput;
10070 }
Eric Laurent83b88082014-06-20 18:31:16 -070010071 destroyTrack_l(record);
10072}
10073
Andy Hung4b17e882023-07-07 13:47:37 -070010074void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010075{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010076 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010077 config->role = AUDIO_PORT_ROLE_SINK;
10078 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10079 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010080 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10081 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10082 config->flags.input = mInput->flags;
10083 }
Eric Laurent83b88082014-06-20 18:31:16 -070010084}
Eric Laurent1c333e22014-05-20 10:48:17 -070010085
Eric Laurent6acd1d42017-01-04 14:23:29 -080010086// ----------------------------------------------------------------------------
10087// Mmap
10088// ----------------------------------------------------------------------------
10089
Andy Hung765de282023-07-07 15:58:48 -070010090// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10091// MmapPlaybackThread or MmapCaptureThread instance.
10092class MmapThreadHandle : public MmapStreamInterface {
10093public:
10094 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10095 ~MmapThreadHandle() override;
10096
10097 // MmapStreamInterface virtuals
10098 status_t createMmapBuffer(int32_t minSizeFrames,
10099 struct audio_mmap_buffer_info* info) final;
10100 status_t getMmapPosition(struct audio_mmap_position* position) final;
10101 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10102 status_t start(const AudioClient& client,
10103 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10104 status_t stop(audio_port_handle_t handle) final;
10105 status_t standby() final;
10106 status_t reportData(const void* buffer, size_t frameCount) final;
10107private:
10108 const sp<IAfMmapThread> mThread;
10109};
10110
10111/* static */
10112sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10113 const sp<IAfMmapThread>& mmapThread) {
10114 return sp<MmapThreadHandle>::make(mmapThread);
10115}
10116
10117MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010118 : mThread(thread)
10119{
Phil Burk9fabbf82017-08-03 12:02:00 -070010120 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010121}
10122
Andy Hung765de282023-07-07 15:58:48 -070010123// MmapStreamInterface could be directly implemented by MmapThread excepting this
10124// special handling on adapter dtor.
10125MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126{
Phil Burk9fabbf82017-08-03 12:02:00 -070010127 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128}
10129
Andy Hung765de282023-07-07 15:58:48 -070010130status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010131 struct audio_mmap_buffer_info *info)
10132{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010133 return mThread->createMmapBuffer(minSizeFrames, info);
10134}
10135
Andy Hung765de282023-07-07 15:58:48 -070010136status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010137{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138 return mThread->getMmapPosition(position);
10139}
10140
Andy Hung765de282023-07-07 15:58:48 -070010141status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010142 int64_t *timeNanos) {
10143 return mThread->getExternalPosition(position, timeNanos);
10144}
10145
Andy Hung765de282023-07-07 15:58:48 -070010146status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010147 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010148{
jiabind1f1cb62020-03-24 11:57:57 -070010149 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150}
10151
Andy Hung765de282023-07-07 15:58:48 -070010152status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010153{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010154 return mThread->stop(handle);
10155}
10156
Andy Hung765de282023-07-07 15:58:48 -070010157status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010158{
Eric Laurent18b57012017-02-13 16:23:52 -080010159 return mThread->standby();
10160}
10161
Andy Hung765de282023-07-07 15:58:48 -070010162status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10163{
jiabinfc791ee2023-02-15 19:43:40 +000010164 return mThread->reportData(buffer, frameCount);
10165}
10166
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167
Andy Hung4b17e882023-07-07 13:47:37 -070010168MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010169 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010170 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -070010171 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010172 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010173 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010174 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010175 mActiveTracks(&this->mLocalLog),
10176 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10177 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178{
Eric Laurent18b57012017-02-13 16:23:52 -080010179 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010180 readHalParameters_l();
10181}
10182
Andy Hung4b17e882023-07-07 13:47:37 -070010183void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010184{
10185 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10186}
10187
Andy Hung4b17e882023-07-07 13:47:37 -070010188void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010189{
Andy Hung11e74242023-06-26 19:20:57 -070010190 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010191 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010192 {
Andy Hungf8635b62023-08-31 16:13:39 -070010193 audio_utils::lock_guard _l(mutex());
Andy Hung11e74242023-06-26 19:20:57 -070010194 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010195 activeTracks.add(t);
10196 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010197 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010198 }
Andy Hung11e74242023-06-26 19:20:57 -070010199 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010200 stop(t->portId());
10201 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010202 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010203 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010204 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010205 } else {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010206 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207 }
10208}
10209
10210
Andy Hung160664b2023-09-15 18:19:28 -070010211void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010212 audio_stream_type_t streamType __unused,
10213 audio_session_t sessionId,
10214 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010215 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010216 audio_port_handle_t portId)
10217{
10218 mAttr = *attr;
10219 mSessionId = sessionId;
10220 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010221 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010222 mPortId = portId;
10223}
10224
Andy Hung4b17e882023-07-07 13:47:37 -070010225status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010226 struct audio_mmap_buffer_info *info)
10227{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010228 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229 if (mHalStream == 0) {
10230 return NO_INIT;
10231 }
Eric Laurent18b57012017-02-13 16:23:52 -080010232 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010233 return mHalStream->createMmapBuffer(minSizeFrames, info);
10234}
10235
Andy Hung4b17e882023-07-07 13:47:37 -070010236status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010237{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010238 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010239 if (mHalStream == 0) {
10240 return NO_INIT;
10241 }
10242 return mHalStream->getMmapPosition(position);
10243}
10244
Andy Hung4b17e882023-07-07 13:47:37 -070010245status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010246{
Eric Laurentdda206a2022-07-08 17:28:35 +020010247 // The HAL must receive track metadata before starting the stream
10248 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010249 status_t ret = mHalStream->start();
10250 if (ret != NO_ERROR) {
10251 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10252 return ret;
10253 }
Andy Hungcf10d742020-04-28 15:38:24 -070010254 if (mStandby) {
10255 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010256 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010257 mStandby = false;
10258 }
Eric Laurent331679c2018-04-16 17:03:16 -070010259 return NO_ERROR;
10260}
10261
Andy Hung4b17e882023-07-07 13:47:37 -070010262status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010263 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010264 audio_port_handle_t *handle)
10265{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010266 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010267 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010268 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 if (mHalStream == 0) {
10270 return NO_INIT;
10271 }
10272
10273 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010274
Eric Laurentdda206a2022-07-08 17:28:35 +020010275 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010276 if (*handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010277 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010278 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010279 }
10280
10281 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10282
10283 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010284 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010285 client.attributionSource);
10286
Andy Hungbcfd9e12023-09-19 14:48:41 -070010287 const auto localSessionId = mSessionId;
10288 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010289 if (isOutput()) {
10290 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10291 config.sample_rate = mSampleRate;
10292 config.channel_mask = mChannelMask;
10293 config.format = mFormat;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010294 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010295 audio_output_flags_t flags =
10296 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010297 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010298 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010299 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010300 bool isBitPerfect;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010301 mutex().unlock();
10302 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10303 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010304 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010305 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010306 &config,
10307 flags,
10308 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010309 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010310 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010311 &isSpatialized,
10312 &isBitPerfect);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010313 mutex().lock();
10314 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010315 ALOGD_IF(!secondaryOutputs.empty(),
10316 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010317 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010318 audio_config_base_t config;
10319 config.sample_rate = mSampleRate;
10320 config.channel_mask = mChannelMask;
10321 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010322 audio_port_handle_t deviceId = mDeviceId;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010323 mutex().unlock();
10324 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010325 RECORD_RIID_INVALID,
Andy Hungbcfd9e12023-09-19 14:48:41 -070010326 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010327 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010328 &config,
10329 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10330 &deviceId,
10331 &portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010332 mutex().lock();
10333 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010334 }
10335 // APM should not chose a different input or output stream for the same set of attributes
10336 // and audo configuration
10337 if (ret != NO_ERROR || io != mId) {
10338 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10339 __FUNCTION__, ret, io, mId);
10340 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010341 }
10342
10343 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010344 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010345 ret = AudioSystem::startOutput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010346 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010347 } else {
jiabin09609032022-06-15 19:26:01 +000010348 {
10349 // Add the track record before starting input so that the silent status for the
10350 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010351 setClientSilencedState_l(portId, false /*silenced*/);
10352 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010353 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010354 ret = AudioSystem::startInput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010355 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356 }
10357
10358 // abort if start is rejected by audio policy manager
10359 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010360 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010361 if (!mActiveTracks.isEmpty()) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010362 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010363 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010364 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010366 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010367 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010368 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010369 } else {
10370 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010371 }
jiabin09609032022-06-15 19:26:01 +000010372 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010373 return PERMISSION_DENIED;
10374 }
10375
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010376 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010377 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10378 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010379 mChannelMask, mSessionId, isOutput(),
10380 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010381 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010382 if (!isOutput()) {
10383 track->setSilenced_l(isClientSilenced_l(portId));
10384 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385
Eric Laurent4eb58f12018-12-07 16:41:02 -080010386 if (isOutput()) {
10387 // force volume update when a new track is added
10388 mHalVolFloat = -1.0f;
10389 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010390 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010391 if (t->isSilenced_l()
10392 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010393 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010394 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010395 }
10396 }
10397
Eric Laurent6acd1d42017-01-04 14:23:29 -080010398 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010399 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010400 if (chain != 0) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010401 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 chain->incTrackCnt();
10403 chain->incActiveTrackCnt();
10404 }
10405
Andy Hungc2b11cb2020-04-22 09:04:01 -070010406 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010407 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010408
10409 if (mActiveTracks.size() == 1) {
10410 ret = exitStandby_l();
10411 }
10412
Eric Laurent6acd1d42017-01-04 14:23:29 -080010413 broadcast_l();
10414
Eric Laurentdda206a2022-07-08 17:28:35 +020010415 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010416
Eric Laurentdda206a2022-07-08 17:28:35 +020010417 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010418}
10419
Andy Hung4b17e882023-07-07 13:47:37 -070010420status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010423 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010424
10425 if (mHalStream == 0) {
10426 return NO_INIT;
10427 }
10428
Eric Laurenta54f1282017-07-01 19:39:32 -070010429 if (handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010430 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010431 return NO_ERROR;
10432 }
10433
Andy Hung11e74242023-06-26 19:20:57 -070010434 sp<IAfMmapTrack> track;
10435 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010436 if (handle == t->portId()) {
10437 track = t;
10438 break;
10439 }
10440 }
10441 if (track == 0) {
10442 return BAD_VALUE;
10443 }
10444
10445 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010446 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010447
Andy Hungb17d24b2023-08-29 14:26:09 -070010448 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010450 AudioSystem::stopOutput(track->portId());
10451 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010452 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010453 AudioSystem::stopInput(track->portId());
10454 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010455 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010456 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457
Andy Hung116bc262023-06-20 18:56:17 -070010458 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459 if (chain != 0) {
10460 chain->decActiveTrackCnt();
10461 chain->decTrackCnt();
10462 }
10463
Eric Laurentdda206a2022-07-08 17:28:35 +020010464 if (mActiveTracks.isEmpty()) {
10465 mHalStream->stop();
10466 }
10467
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468 broadcast_l();
10469
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470 return NO_ERROR;
10471}
10472
Andy Hung4b17e882023-07-07 13:47:37 -070010473status_t MmapThread::standby()
Andy Hungbcfd9e12023-09-19 14:48:41 -070010474NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010475{
10476 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010477 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010478
10479 if (mHalStream == 0) {
10480 return NO_INIT;
10481 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010482 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010483 return INVALID_OPERATION;
10484 }
10485 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010486 if (!mStandby) {
10487 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010488 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010489 mStandby = true;
10490 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010491 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010492 return NO_ERROR;
10493}
10494
Andy Hung4b17e882023-07-07 13:47:37 -070010495status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010496 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10497 return INVALID_OPERATION;
10498}
10499
Andy Hung4b17e882023-07-07 13:47:37 -070010500void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501{
10502 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10503 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10504 mFormat = mHALFormat;
10505 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10506 result = mHalStream->getFrameSize(&mFrameSize);
10507 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010508 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10509 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010510 result = mHalStream->getBufferSize(&mBufferSize);
10511 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10512 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010513
Andy Hungcf10d742020-04-28 15:38:24 -070010514 // TODO: make a readHalParameters call?
10515 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010516 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -070010517 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010518 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10519 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10520 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10521 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10522 /*
10523 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10524 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10525 (int32_t)mHapticChannelMask)
10526 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10527 (int32_t)mHapticChannelCount)
10528 */
10529 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -070010530 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010531 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10532 (int32_t)mFrameCount) // sic - added HAL
10533 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010534}
10535
Andy Hung4b17e882023-07-07 13:47:37 -070010536bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010537{
Andy Hung94dfbb42023-09-06 19:41:47 -070010538 {
10539 audio_utils::unique_lock _l(mutex());
10540 checkSilentMode_l();
10541 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010542
10543 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10544
10545 while (!exitPending())
10546 {
Andy Hung116bc262023-06-20 18:56:17 -070010547 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010548
Andy Hung13850be2019-03-14 11:33:09 -070010549 { // under Thread lock
Andy Hungb17d24b2023-08-29 14:26:09 -070010550 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010551
Eric Laurent6acd1d42017-01-04 14:23:29 -080010552 if (mSignalPending) {
10553 // A signal was raised while we were unlocked
10554 mSignalPending = false;
10555 } else {
10556 if (mConfigEvents.isEmpty()) {
10557 // we're about to wait, flush the binder command buffer
10558 IPCThreadState::self()->flushCommands();
10559
10560 if (exitPending()) {
10561 break;
10562 }
10563
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010565 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -070010566 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010567 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010568
10569 checkSilentMode_l();
10570
10571 continue;
10572 }
10573 }
10574
10575 processConfigEvents_l();
10576
10577 processVolume_l();
10578
10579 checkInvalidTracks_l();
10580
Andy Hung94dfbb42023-09-06 19:41:47 -070010581 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582
Kevin Rocard069c2712018-03-29 19:09:14 -070010583 updateMetadata_l();
10584
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010586 } // release Thread lock
10587
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010589 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010590 }
Andy Hung13850be2019-03-14 11:33:09 -070010591
10592 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010593 unlockEffectChains(effectChains);
10594 // Effect chains will be actually deleted here if they were removed from
10595 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010596 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010597 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010598 mThreadloopExecutor.process(); // process any remaining deferred actions.
10599 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010600
10601 threadLoop_exit();
10602
10603 if (!mStandby) {
10604 threadLoop_standby();
10605 mStandby = true;
10606 }
10607
Eric Laurent6acd1d42017-01-04 14:23:29 -080010608 ALOGV("Thread %p type %d exiting", this, mType);
10609 return false;
10610}
10611
Andy Hungb17d24b2023-08-29 14:26:09 -070010612// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070010613bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010614 status_t& status)
10615{
10616 AudioParameter param = AudioParameter(keyValuePair);
10617 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010618 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010619 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010620 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010622 if (sendToHal) {
10623 status = mHalStream->setParameters(keyValuePair);
10624 } else {
10625 status = NO_ERROR;
10626 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627
10628 return false;
10629}
10630
Andy Hung4b17e882023-07-07 13:47:37 -070010631String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632{
Andy Hungf8635b62023-08-31 16:13:39 -070010633 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634 String8 out_s8;
10635 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10636 return out_s8;
10637 }
Andy Hung920f6572022-10-06 12:09:49 -070010638 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010639}
10640
Andy Hung94dfbb42023-09-06 19:41:47 -070010641void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010642 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010643 sp<AudioIoDescriptor> desc;
10644 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010645 switch (event) {
10646 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010647 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010648 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010649 isInput = true;
10650 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010651 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010652 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010653 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010654 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10655 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010656 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010657 case AUDIO_INPUT_CLOSED:
10658 case AUDIO_OUTPUT_CLOSED:
10659 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010660 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010661 break;
10662 }
Andy Hung94dfbb42023-09-06 19:41:47 -070010663 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010664}
10665
Andy Hung4b17e882023-07-07 13:47:37 -070010666status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010667 audio_patch_handle_t *handle)
Andy Hungb17d24b2023-08-29 14:26:09 -070010668NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669{
10670 status_t status = NO_ERROR;
10671
10672 // store new device and send to effects
10673 audio_devices_t type = AUDIO_DEVICE_NONE;
10674 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010675 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10676 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10677 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010678 if (isOutput()) {
10679 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010680 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10681 && !mAudioHwDev->supportsAudioPatches(),
10682 "Enumerated device type(%#x) must not be used "
10683 "as it does not support audio patches",
10684 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010685 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010686 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10687 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688 }
10689 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010690 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010691 } else {
10692 type = patch->sources[0].ext.device.type;
10693 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010694 numDevices = mPatch.num_sources;
10695 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010696 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 }
10698
10699 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010700 if (isOutput()) {
10701 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10702 } else {
10703 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10704 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010705 }
10706
jiabinc52b1ff2019-10-31 17:20:42 -070010707 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708 // store new source and send to effects
10709 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10710 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10711 for (size_t i = 0; i < mEffectChains.size(); i++) {
10712 mEffectChains[i]->setAudioSource_l(mAudioSource);
10713 }
10714 }
10715 }
10716
jiabin78b86f22024-02-22 00:39:29 +000010717 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10718 // okay to notify the client earlier before the new patch creation.
10719 if (mDeviceId != deviceId) {
10720 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10721 // The aaudioservice handle the routing changed event asynchronously. In that case,
10722 // it is safe to hold the lock here.
10723 callback->onRoutingChanged(deviceId);
10724 }
10725 }
10726
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010728 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10729 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010730 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010731 audio_port_config port;
10732 std::optional<audio_source_t> source;
10733 if (isOutput()) {
10734 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010735 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010736 port = patch->sources[0];
10737 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010738 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010739 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740 *handle = AUDIO_PATCH_HANDLE_NONE;
10741 }
10742
jiabinc52b1ff2019-10-31 17:20:42 -070010743 if (numDevices == 0 || mDeviceId != deviceId) {
10744 if (isOutput()) {
10745 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10746 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010747 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010748 } else {
10749 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10750 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10751 }
jiabinc52b1ff2019-10-31 17:20:42 -070010752 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010753 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010754 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010755 // Force meteadata update after a route change
10756 mActiveTracks.setHasChanged();
10757
Eric Laurent6acd1d42017-01-04 14:23:29 -080010758 return status;
10759}
10760
Andy Hung4b17e882023-07-07 13:47:37 -070010761status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010762{
10763 status_t status = NO_ERROR;
10764
jiabinc52b1ff2019-10-31 17:20:42 -070010765 mPatch = audio_patch{};
10766 mOutDeviceTypeAddrs.clear();
10767 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010768
10769 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10770 supportsAudioPatches : false;
10771
10772 if (supportsAudioPatches) {
10773 status = mHalDevice->releaseAudioPatch(handle);
10774 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010775 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010777 // Force meteadata update after a route change
10778 mActiveTracks.setHasChanged();
10779
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780 return status;
10781}
10782
Andy Hung4b17e882023-07-07 13:47:37 -070010783void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hungbcfd9e12023-09-19 14:48:41 -070010784NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010785{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010786 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787 if (isOutput()) {
10788 config->role = AUDIO_PORT_ROLE_SOURCE;
10789 config->ext.mix.hw_module = mAudioHwDev->handle();
10790 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10791 } else {
10792 config->role = AUDIO_PORT_ROLE_SINK;
10793 config->ext.mix.hw_module = mAudioHwDev->handle();
10794 config->ext.mix.usecase.source = mAudioSource;
10795 }
10796}
10797
Andy Hung4b17e882023-07-07 13:47:37 -070010798status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010799{
10800 audio_session_t session = chain->sessionId();
10801
10802 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10803 // Attach all tracks with same session ID to this chain.
10804 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010805 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010806 if (session == track->sessionId()) {
10807 chain->incTrackCnt();
10808 chain->incActiveTrackCnt();
10809 }
10810 }
10811
10812 chain->setThread(this);
10813 chain->setInBuffer(nullptr);
10814 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010815 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010816
10817 mEffectChains.add(chain);
10818 checkSuspendOnAddEffectChain_l(chain);
10819 return NO_ERROR;
10820}
10821
Andy Hung4b17e882023-07-07 13:47:37 -070010822size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010823{
10824 audio_session_t session = chain->sessionId();
10825
10826 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10827
10828 for (size_t i = 0; i < mEffectChains.size(); i++) {
10829 if (chain == mEffectChains[i]) {
10830 mEffectChains.removeAt(i);
10831 // detach all active tracks from the chain
10832 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010833 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010834 if (session == track->sessionId()) {
10835 chain->decActiveTrackCnt();
10836 chain->decTrackCnt();
10837 }
10838 }
10839 break;
10840 }
10841 }
10842 return mEffectChains.size();
10843}
10844
Andy Hung4b17e882023-07-07 13:47:37 -070010845void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010846{
10847 mHalStream->standby();
10848}
10849
Andy Hung4b17e882023-07-07 13:47:37 -070010850void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010851{
Phil Burk7dce7282017-09-27 13:51:41 -070010852 // Do not call callback->onTearDown() because it is redundant for thread exit
10853 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854}
10855
Andy Hung4b17e882023-07-07 13:47:37 -070010856status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010857{
10858 return BAD_VALUE;
10859}
10860
Andy Hung4b17e882023-07-07 13:47:37 -070010861bool MmapThread::isValidSyncEvent(
10862 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010863{
10864 return false;
10865}
10866
Andy Hung4b17e882023-07-07 13:47:37 -070010867status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010868 const effect_descriptor_t *desc, audio_session_t sessionId)
10869{
10870 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010871 if (audio_is_global_session(sessionId)) {
10872 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010873 desc->name, mThreadName);
10874 return BAD_VALUE;
10875 }
10876
10877 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10878 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10879 desc->name);
10880 return BAD_VALUE;
10881 }
10882 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010883 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10884 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010885 return BAD_VALUE;
10886 }
10887
10888 // Only allow effects without processing load or latency
10889 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10890 return BAD_VALUE;
10891 }
10892
Andy Hung116bc262023-06-20 18:56:17 -070010893 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010894 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10895 return BAD_VALUE;
10896 }
10897
Eric Laurent6acd1d42017-01-04 14:23:29 -080010898 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010899}
10900
Andy Hung4b17e882023-07-07 13:47:37 -070010901void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010902{
Andy Hung11e74242023-06-26 19:20:57 -070010903 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010904 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010905 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10906 // The aaudioservice handle the routing changed event asynchronously. In that case,
10907 // it is safe to hold the lock here.
10908 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10909 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010910 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10911 mNoCallbackWarningCount++;
10912 }
10913 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010914 }
10915 }
10916}
10917
Andy Hung4b17e882023-07-07 13:47:37 -070010918void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010919{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010920 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10921 mAttr.content_type, mAttr.usage, mAttr.source);
10922 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010923 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010924 dprintf(fd, " No active clients\n");
10925 }
10926}
10927
Andy Hung4b17e882023-07-07 13:47:37 -070010928void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010929{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010930 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010931 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010932 dprintf(fd, " %zu Tracks\n", numtracks);
10933 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010934 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010935 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010936 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010938 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010939 result.append(prefix);
10940 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010941 }
10942 } else {
10943 dprintf(fd, "\n");
10944 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010945 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010946}
10947
Andy Hung4b17e882023-07-07 13:47:37 -070010948/* static */
10949sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010950 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010951 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010952 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010953}
10954
10955MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010956 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010957 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010958 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010960 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010961{
10962 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10963 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070010964 mMasterVolume = afThreadCallback->masterVolume_l();
10965 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent19611512023-07-03 18:14:07 +020010966
10967 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10968 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10969 mStreamTypes[stream].volume = 0.0f;
10970 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
10971 }
10972 // Audio patch and call assistant volume are always max
10973 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10974 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10975 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10976 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10977
Eric Laurent6acd1d42017-01-04 14:23:29 -080010978 if (mAudioHwDev) {
10979 if (mAudioHwDev->canSetMasterVolume()) {
10980 mMasterVolume = 1.0;
10981 }
10982
10983 if (mAudioHwDev->canSetMasterMute()) {
10984 mMasterMute = false;
10985 }
10986 }
10987}
10988
Andy Hung4b17e882023-07-07 13:47:37 -070010989void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010990 audio_stream_type_t streamType,
10991 audio_session_t sessionId,
10992 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010993 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010994 audio_port_handle_t portId)
10995{
Andy Hung160664b2023-09-15 18:19:28 -070010996 audio_utils::lock_guard l(mutex());
10997 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010998 mStreamType = streamType;
10999}
11000
Andy Hung4b17e882023-07-07 13:47:37 -070011001AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011002{
Andy Hungf8635b62023-08-31 16:13:39 -070011003 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011004 AudioStreamOut *output = mOutput;
11005 mOutput = NULL;
11006 return output;
11007}
11008
Andy Hung4b17e882023-07-07 13:47:37 -070011009void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011010{
Andy Hungf8635b62023-08-31 16:13:39 -070011011 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011012 // Don't apply master volume in SW if our HAL can do it for us.
11013 if (mAudioHwDev &&
11014 mAudioHwDev->canSetMasterVolume()) {
11015 mMasterVolume = 1.0;
11016 } else {
11017 mMasterVolume = value;
11018 }
11019}
11020
Andy Hung4b17e882023-07-07 13:47:37 -070011021void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011022{
Andy Hungf8635b62023-08-31 16:13:39 -070011023 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011024 // Don't apply master mute in SW if our HAL can do it for us.
11025 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11026 mMasterMute = false;
11027 } else {
11028 mMasterMute = muted;
11029 }
11030}
11031
Andy Hung4b17e882023-07-07 13:47:37 -070011032void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033{
Andy Hungf8635b62023-08-31 16:13:39 -070011034 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011035 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011036 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011037 broadcast_l();
11038 }
11039}
11040
Andy Hung4b17e882023-07-07 13:47:37 -070011041float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011042{
Andy Hungf8635b62023-08-31 16:13:39 -070011043 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011044 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045}
11046
Andy Hung4b17e882023-07-07 13:47:37 -070011047void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011048{
Andy Hungf8635b62023-08-31 16:13:39 -070011049 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011050 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011051 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011052 broadcast_l();
11053 }
11054}
11055
Andy Hung4b17e882023-07-07 13:47:37 -070011056void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011057{
Andy Hungf8635b62023-08-31 16:13:39 -070011058 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070011060 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011061 track->invalidate();
11062 }
11063 broadcast_l();
11064 }
11065}
11066
Andy Hung4b17e882023-07-07 13:47:37 -070011067void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011068{
Andy Hungf8635b62023-08-31 16:13:39 -070011069 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011070 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070011071 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011072 if (portIds.find(track->portId()) != portIds.end()) {
11073 track->invalidate();
11074 trackMatch = true;
11075 portIds.erase(track->portId());
11076 }
11077 if (portIds.empty()) {
11078 break;
11079 }
11080 }
11081 if (trackMatch) {
11082 broadcast_l();
11083 }
11084}
11085
Andy Hung4b17e882023-07-07 13:47:37 -070011086void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011087NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011088{
11089 float volume;
11090
Eric Laurent19611512023-07-03 18:14:07 +020011091 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011092 volume = 0;
11093 } else {
Eric Laurent19611512023-07-03 18:14:07 +020011094 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011095 }
11096
11097 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011098 // Convert volumes from float to 8.24
11099 uint32_t vol = (uint32_t)(volume * (1 << 24));
11100
11101 // Delegate volume control to effect in track effect chain if needed
11102 // only one effect chain can be present on DirectOutputThread, so if
11103 // there is one, the track is connected to it
11104 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011105 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011106 volume = (float)vol / (1 << 24);
11107 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011108 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011109 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11110 mHalVolFloat = volume; // HW volume control worked, so update value.
11111 mNoCallbackWarningCount = 0;
11112 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011113 sp<MmapStreamCallback> callback = mCallback.promote();
11114 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011115 mHalVolFloat = volume; // SW volume control worked, so update value.
11116 mNoCallbackWarningCount = 0;
Andy Hungb17d24b2023-08-29 14:26:09 -070011117 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011118 callback->onVolumeChanged(volume);
Andy Hungb17d24b2023-08-29 14:26:09 -070011119 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011120 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011121 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11122 ALOGW("Could not set MMAP stream volume: no volume callback!");
11123 mNoCallbackWarningCount++;
11124 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011125 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011126 }
Andy Hung11e74242023-06-26 19:20:57 -070011127 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011128 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070011129 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011130 /*muteState=*/{mMasterMute,
Eric Laurent19611512023-07-03 18:14:07 +020011131 streamVolume_l() == 0.f,
11132 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011133 // TODO(b/241533526): adjust logic to include mute from AppOps
11134 false /*muteFromPlaybackRestricted*/,
11135 false /*muteFromClientVolume*/,
11136 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011137 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011138 }
11139}
11140
Andy Hung4b17e882023-07-07 13:47:37 -070011141ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011142{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011143 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011144 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011145 }
11146 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011147 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011148 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011149 playback_track_metadata_v7_t trackMetadata;
11150 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011151 .usage = track->attributes().usage,
11152 .content_type = track->attributes().content_type,
11153 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011154 };
11155 trackMetadata.channel_mask = track->channelMask(),
11156 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11157 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011158 }
11159 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011160
11161 MetadataUpdate change;
11162 change.playbackMetadataUpdate = metadata.tracks;
11163 return change;
11164};
Kevin Rocard069c2712018-03-29 19:09:14 -070011165
Andy Hung4b17e882023-07-07 13:47:37 -070011166void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011167{
11168 if (!mMasterMute) {
11169 char value[PROPERTY_VALUE_MAX];
11170 if (property_get("ro.audio.silent", value, "0") > 0) {
11171 char *endptr;
11172 unsigned long ul = strtoul(value, &endptr, 0);
11173 if (*endptr == '\0' && ul != 0) {
Andy Hung6fb26892024-02-20 16:32:57 -080011174 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011175 // The setprop command will not allow a property to be changed after
11176 // the first time it is set, so we don't have to worry about un-muting.
11177 setMasterMute_l(true);
11178 }
11179 }
11180 }
11181}
11182
Andy Hung4b17e882023-07-07 13:47:37 -070011183void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011184{
11185 MmapThread::toAudioPortConfig(config);
11186 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11187 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11188 config->flags.output = mOutput->flags;
11189 }
11190}
11191
Andy Hung4b17e882023-07-07 13:47:37 -070011192status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070011193 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011194{
11195 if (mOutput == nullptr) {
11196 return NO_INIT;
11197 }
11198 struct timespec timestamp;
11199 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11200 if (status == NO_ERROR) {
11201 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11202 }
11203 return status;
11204}
11205
Andy Hung4b17e882023-07-07 13:47:37 -070011206status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011207 // Send to MelProcessor for sound dose measurement.
11208 auto processor = mMelProcessor.load();
11209 if (processor) {
11210 processor->process(buffer, frameCount * mFrameSize);
11211 }
11212
jiabinfc791ee2023-02-15 19:43:40 +000011213 return NO_ERROR;
11214}
11215
Andy Hungb17d24b2023-08-29 14:26:09 -070011216// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011217void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011218 const sp<audio_utils::MelProcessor>& processor)
11219{
11220 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011221 mMelProcessor.store(processor);
11222 if (processor) {
11223 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011224 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011225
11226 // no need to update output format for MMapPlaybackThread since it is
11227 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011228}
11229
Andy Hungb17d24b2023-08-29 14:26:09 -070011230// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011231void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011232{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011233 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11234 auto melProcessor = mMelProcessor.load();
11235 if (melProcessor != nullptr) {
11236 melProcessor->pause();
11237 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011238}
11239
Andy Hung4b17e882023-07-07 13:47:37 -070011240void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011241{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011242 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011243
Glenn Kastend3bb6452016-12-05 18:14:37 -080011244 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent19611512023-07-03 18:14:07 +020011245 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011246 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11247}
11248
Andy Hung4b17e882023-07-07 13:47:37 -070011249/* static */
11250sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070011251 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070011252 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011253 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011254}
11255
11256MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011257 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011258 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011259 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011260 mInput(input)
11261{
11262 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11263 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11264}
11265
Andy Hung4b17e882023-07-07 13:47:37 -070011266status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011267{
Phil Burkf054fc32018-12-06 09:45:59 -080011268 {
11269 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011270 if (mInput != nullptr && mInput->stream != nullptr) {
11271 mInput->stream->setGain(1.0f);
11272 }
11273 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011274 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011275}
11276
Andy Hung4b17e882023-07-07 13:47:37 -070011277AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011278{
Andy Hungf8635b62023-08-31 16:13:39 -070011279 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011280 AudioStreamIn *input = mInput;
11281 mInput = NULL;
11282 return input;
11283}
Kevin Rocard069c2712018-03-29 19:09:14 -070011284
Andy Hung4b17e882023-07-07 13:47:37 -070011285void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011286{
11287 bool changed = false;
11288 bool silenced = false;
11289
11290 sp<MmapStreamCallback> callback = mCallback.promote();
11291 if (callback == 0) {
11292 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11293 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11294 mNoCallbackWarningCount++;
11295 }
11296 }
11297
11298 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11299 // track is silenced and unmute otherwise
11300 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11301 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11302 changed = true;
11303 silenced = mActiveTracks[i]->isSilenced_l();
11304 }
11305 }
11306
11307 if (changed) {
11308 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11309 }
11310}
11311
Andy Hung4b17e882023-07-07 13:47:37 -070011312ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011313{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011314 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011315 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011316 }
11317 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011318 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011319 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011320 record_track_metadata_v7_t trackMetadata;
11321 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011322 .source = track->attributes().source,
11323 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011324 };
11325 trackMetadata.channel_mask = track->channelMask(),
11326 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11327 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011328 }
11329 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011330 MetadataUpdate change;
11331 change.recordMetadataUpdate = metadata.tracks;
11332 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011333}
11334
Andy Hung4b17e882023-07-07 13:47:37 -070011335void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011336{
Andy Hungf8635b62023-08-31 16:13:39 -070011337 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011338 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011339 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011340 mActiveTracks[i]->setSilenced_l(silenced);
11341 broadcast_l();
11342 }
11343 }
jiabin09609032022-06-15 19:26:01 +000011344 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011345}
11346
Andy Hung4b17e882023-07-07 13:47:37 -070011347void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011348{
11349 MmapThread::toAudioPortConfig(config);
11350 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11351 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11352 config->flags.input = mInput->flags;
11353 }
11354}
11355
Andy Hung4b17e882023-07-07 13:47:37 -070011356status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011357 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011358{
11359 if (mInput == nullptr) {
11360 return NO_INIT;
11361 }
11362 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11363}
11364
jiabinc658e452022-10-21 20:52:21 +000011365// ----------------------------------------------------------------------------
11366
Andy Hung4b17e882023-07-07 13:47:37 -070011367/* static */
11368sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011369 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011370 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011371 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011372}
11373
Andy Hung7535ed92023-07-17 17:05:00 -070011374BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011375 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011376 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011377
Andy Hung4b17e882023-07-07 13:47:37 -070011378PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011379 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011380 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11381 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011382 float volumeLeft = 1.0f;
11383 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011384 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11385 const int trackId = mActiveTracks[0]->id();
11386 mAudioMixer->setParameter(
11387 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11388 mAudioMixer->setParameter(
11389 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11390 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011391 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011392 mIsBitPerfect = true;
11393 } else {
11394 mIsBitPerfect = false;
11395 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11396 // active.
11397 for (const auto& track : mActiveTracks) {
11398 const int trackId = track->id();
11399 mAudioMixer->setParameter(
11400 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11401 }
11402 }
jiabin76d94692022-12-15 21:51:21 +000011403 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11404 mVolumeLeft = volumeLeft;
11405 mVolumeRight = volumeRight;
11406 setVolumeForOutput_l(volumeLeft, volumeRight);
11407 }
jiabinc658e452022-10-21 20:52:21 +000011408 return result;
11409}
11410
Andy Hung4b17e882023-07-07 13:47:37 -070011411void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011412 MixerThread::threadLoop_mix();
11413 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11414}
11415
Glenn Kasten63238ef2015-03-02 15:50:29 -080011416} // namespace android