blob: d69a5902d2d8b7013b5e18a4d0f078c8839261e3 [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();"
697 requestExitAndWait();
698}
699
Andy Hung4b17e882023-07-07 13:47:37 -0700700status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800701{
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000702 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hungf8635b62023-08-31 16:13:39 -0700703 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800704
Eric Laurent10351942014-05-08 18:49:52 -0700705 return sendSetParameterConfigEvent_l(keyValuePairs);
706}
707
708// sendConfigEvent_l() must be called with ThreadBase::mLock held
709// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung4b17e882023-07-07 13:47:37 -0700710status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700711NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700712{
713 status_t status = NO_ERROR;
714
Eric Laurent72e3f392015-05-20 14:43:50 -0700715 if (event->mRequiresSystemReady && !mSystemReady) {
716 event->mWaitStatus = false;
717 mPendingConfigEvents.add(event);
718 return status;
719 }
Eric Laurent10351942014-05-08 18:49:52 -0700720 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700721 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungb17d24b2023-08-29 14:26:09 -0700722 mWaitWorkCV.notify_one();
723 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700724 {
Andy Hungb17d24b2023-08-29 14:26:09 -0700725 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700726 while (event->mWaitStatus) {
Andy Hung5529c132024-01-25 17:02:30 -0800727 if (event->mCondition.wait_for(
728 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
729 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700730 event->mStatus = TIMED_OUT;
731 event->mWaitStatus = false;
732 }
733 }
734 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800735 }
Andy Hungb17d24b2023-08-29 14:26:09 -0700736 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800737 return status;
738}
739
Andy Hung4b17e882023-07-07 13:47:37 -0700740void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700741 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800742{
Andy Hungf8635b62023-08-31 16:13:39 -0700743 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700744 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800745}
746
Andy Hungb17d24b2023-08-29 14:26:09 -0700747// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700748void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700749 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800750{
Andy Hungd0979812019-02-21 15:51:44 -0800751 // The audio statistics history is exponentially weighted to forget events
752 // about five or more seconds in the past. In order to have
753 // crisper statistics for mediametrics, we reset the statistics on
754 // an IoConfigEvent, to reflect different properties for a new device.
755 mIoJitterMs.reset();
756 mLatencyMs.reset();
757 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000758 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100759 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800760
Eric Laurent09f1ed22019-04-24 17:45:17 -0700761 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700762 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800763}
764
Andy Hung4b17e882023-07-07 13:47:37 -0700765void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700766{
Andy Hungf8635b62023-08-31 16:13:39 -0700767 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800768 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700769}
770
Andy Hungb17d24b2023-08-29 14:26:09 -0700771// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700772void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800773 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800774{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800775 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700776 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800777}
778
Andy Hungb17d24b2023-08-29 14:26:09 -0700779// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700780status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800781{
Andy Hung2ddee192015-12-18 17:34:44 -0800782 sp<ConfigEvent> configEvent;
783 AudioParameter param(keyValuePair);
784 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700785 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800786 setMasterMono_l(value != 0);
787 if (param.size() == 1) {
788 return NO_ERROR; // should be a solo parameter - we don't pass down
789 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700790 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800791 configEvent = new SetParameterConfigEvent(param.toString());
792 } else {
793 configEvent = new SetParameterConfigEvent(keyValuePair);
794 }
Eric Laurent10351942014-05-08 18:49:52 -0700795 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700796}
797
Andy Hung4b17e882023-07-07 13:47:37 -0700798status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700799 const struct audio_patch *patch,
800 audio_patch_handle_t *handle)
801{
Andy Hungf8635b62023-08-31 16:13:39 -0700802 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700803 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
804 status_t status = sendConfigEvent_l(configEvent);
805 if (status == NO_ERROR) {
806 CreateAudioPatchConfigEventData *data =
807 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
808 *handle = data->mHandle;
809 }
810 return status;
811}
812
Andy Hung4b17e882023-07-07 13:47:37 -0700813status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 const audio_patch_handle_t handle)
815{
Andy Hungf8635b62023-08-31 16:13:39 -0700816 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700817 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
818 return sendConfigEvent_l(configEvent);
819}
820
Andy Hung4b17e882023-07-07 13:47:37 -0700821status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700822 const DeviceDescriptorBaseVector& outDevices)
823{
824 if (type() != RECORD) {
825 // The update out device operation is only for record thread.
826 return INVALID_OPERATION;
827 }
Andy Hungf8635b62023-08-31 16:13:39 -0700828 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700829 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
830 return sendConfigEvent_l(configEvent);
831}
832
Andy Hung4b17e882023-07-07 13:47:37 -0700833void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200834{
835 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
836 sp<ConfigEvent> configEvent =
837 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
838 sendConfigEvent_l(configEvent);
839}
Eric Laurent1c333e22014-05-20 10:48:17 -0700840
Andy Hung4b17e882023-07-07 13:47:37 -0700841void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200842{
Andy Hungf8635b62023-08-31 16:13:39 -0700843 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200844 sendCheckOutputStageEffectsEvent_l();
845}
846
Andy Hung4b17e882023-07-07 13:47:37 -0700847void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200848{
849 sp<ConfigEvent> configEvent =
850 (ConfigEvent *)new CheckOutputStageEffectsEvent();
851 sendConfigEvent_l(configEvent);
852}
853
Andy Hung4b17e882023-07-07 13:47:37 -0700854void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200855{
856 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
857 sendConfigEvent_l(configEvent);
858}
859
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700860// post condition: mConfigEvents.isEmpty()
Andy Hung4b17e882023-07-07 13:47:37 -0700861void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700862{
Eric Laurent10351942014-05-08 18:49:52 -0700863 bool configChanged = false;
864
Eric Laurent81784c32012-11-19 14:55:58 -0800865 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700866 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700867 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800868 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700869 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700870 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700871 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
872 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800873 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700874 true /*asynchronous*/);
875 if (err != 0) {
876 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700877 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700878 }
879 } break;
880 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700881 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hung94dfbb42023-09-06 19:41:47 -0700882 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700883 } break;
884 case CFG_EVENT_SET_PARAMETER: {
885 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
886 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
887 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700888 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000889 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700890 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700891 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700892 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700893 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700894 CreateAudioPatchConfigEventData *data =
895 (CreateAudioPatchConfigEventData *)event->mData.get();
896 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700897 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200898 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700899 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
900 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
901 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 } break;
903 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700904 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700905 ReleaseAudioPatchConfigEventData *data =
906 (ReleaseAudioPatchConfigEventData *)event->mData.get();
907 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700908 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200909 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700910 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
911 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
912 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
913 } break;
914 case CFG_EVENT_UPDATE_OUT_DEVICE: {
915 UpdateOutDevicesConfigEventData *data =
916 (UpdateOutDevicesConfigEventData *)event->mData.get();
917 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700918 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200919 case CFG_EVENT_RESIZE_BUFFER: {
920 ResizeBufferConfigEventData *data =
921 (ResizeBufferConfigEventData *)event->mData.get();
922 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
923 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200924
925 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
926 setCheckOutputStageEffects();
927 } break;
928
Eric Laurent68a40a82022-05-03 18:15:04 +0200929 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
930 onHalLatencyModesChanged_l();
931 } break;
932
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700933 default:
Eric Laurent10351942014-05-08 18:49:52 -0700934 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700935 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800936 }
Eric Laurent10351942014-05-08 18:49:52 -0700937 {
Andy Hungf8635b62023-08-31 16:13:39 -0700938 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700939 if (event->mWaitStatus) {
940 event->mWaitStatus = false;
Andy Hungb17d24b2023-08-29 14:26:09 -0700941 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700942 }
943 }
944 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
945 }
946
947 if (configChanged) {
948 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800949 }
Eric Laurent81784c32012-11-19 14:55:58 -0800950}
951
Marco Nelissenb2208842014-02-07 14:00:50 -0800952String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
953 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700954 const audio_channel_representation_t representation =
955 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700956
957 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800958 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700959 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
960 if (output) {
961 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
962 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
963 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700964 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700965 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
966 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
967 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
968 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
969 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
970 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
971 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700977 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
978 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
979 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
980 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
981 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
982 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
983 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700984 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700985 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
986 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700987 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
988 } else {
989 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
990 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
991 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
992 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
993 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
994 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
995 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
996 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
997 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
998 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
999 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1000 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001001 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1002 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1003 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001004 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001005 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1006 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001007 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1008 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1009 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1010 }
1011 const int len = s.length();
1012 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001013 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001014 s.unlockBuffer(len - 2); // remove trailing ", "
1015 }
1016 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001017 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001018 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1019 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1020 return s;
1021 default:
1022 s.appendFormat("unknown mask, representation:%d bits:%#x",
1023 representation, audio_channel_mask_get_bits(mask));
1024 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001025 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001026}
1027
Andy Hung4b17e882023-07-07 13:47:37 -07001028void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001029NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001030{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001031 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1032 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1033
Andy Hungb17d24b2023-08-29 14:26:09 -07001034 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001035 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001036 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001037 }
1038
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001039 dumpBase_l(fd, args);
1040 dumpInternals_l(fd, args);
1041 dumpTracks_l(fd, args);
1042 dumpEffectChains_l(fd, args);
1043
1044 if (locked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001045 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001046 }
1047
1048 dprintf(fd, " Local log:\n");
1049 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001050
1051 // --all does the statistics
1052 bool dumpAll = false;
1053 for (const auto &arg : args) {
1054 if (arg == String16("--all")) {
1055 dumpAll = true;
1056 }
1057 }
1058 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001059 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001060 if (!sched.empty()) {
1061 (void)write(fd, sched.c_str(), sched.size());
1062 }
1063 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001064}
1065
Andy Hung4b17e882023-07-07 13:47:37 -07001066void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001067{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001068 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001069 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001070 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001071 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung409572b2023-07-19 12:47:35 -07001072 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1073 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001074 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001075 dprintf(fd, " Channel count: %u\n", mChannelCount);
1076 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001077 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung409572b2023-07-19 12:47:35 -07001078 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1079 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001080 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001081 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001082 size_t numConfig = mConfigEvents.size();
1083 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001084 const size_t SIZE = 256;
1085 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001086 for (size_t i = 0; i < numConfig; i++) {
1087 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001088 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001089 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001090 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001091 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001092 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001093 }
Andy Hung293558a2017-03-21 12:19:20 -07001094 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001095 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001096 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001097 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001098 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001099 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001100
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001101 // Dump timestamp statistics for the Thread types that support it.
1102 if (mType == RECORD
1103 || mType == MIXER
1104 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001105 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001106 || mType == OFFLOAD
1107 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001108 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hung94dfbb42023-09-06 19:41:47 -07001109 dprintf(fd, " Timestamp corrected: %s\n",
1110 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001111 }
1112
Andy Hung446f4df2019-02-21 12:26:41 -08001113 if (mLastIoBeginNs > 0) { // MMAP may not set this
1114 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1115 isOutput() ? "write" : "read",
1116 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1117 }
1118
1119 if (mProcessTimeMs.getN() > 0) {
1120 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1121 }
1122
1123 if (mIoJitterMs.getN() > 0) {
1124 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1125 isOutput() ? "write" : "read",
1126 mIoJitterMs.toString().c_str());
1127 }
1128
Andy Hunge6c37112019-02-26 17:38:10 -08001129 if (mLatencyMs.getN() > 0) {
1130 dprintf(fd, " Threadloop %s latency stats: %s\n",
1131 isOutput() ? "write" : "read",
1132 mLatencyMs.toString().c_str());
1133 }
Robert Wu06db0a32021-08-10 19:05:34 +00001134
1135 if (mMonopipePipeDepthStats.getN() > 0) {
1136 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1137 isOutput() ? "write" : "read",
1138 mMonopipePipeDepthStats.toString().c_str());
1139 }
Eric Laurent81784c32012-11-19 14:55:58 -08001140}
1141
Andy Hung4b17e882023-07-07 13:47:37 -07001142void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001143{
1144 const size_t SIZE = 256;
1145 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001146
Marco Nelissenb2208842014-02-07 14:00:50 -08001147 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001148 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001149 write(fd, buffer, strlen(buffer));
1150
Marco Nelissenb2208842014-02-07 14:00:50 -08001151 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001152 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001153 if (chain != 0) {
1154 chain->dump(fd, args);
1155 }
1156 }
1157}
1158
Andy Hung4b17e882023-07-07 13:47:37 -07001159void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001160{
Andy Hungf8635b62023-08-31 16:13:39 -07001161 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001162 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001163}
1164
Andy Hung4b17e882023-07-07 13:47:37 -07001165String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001166{
1167 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001168 case MIXER:
1169 return String16("AudioMix");
1170 case DIRECT:
1171 return String16("AudioDirectOut");
1172 case DUPLICATING:
1173 return String16("AudioDup");
1174 case RECORD:
1175 return String16("AudioIn");
1176 case OFFLOAD:
1177 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001178 case MMAP_PLAYBACK:
1179 return String16("MmapPlayback");
1180 case MMAP_CAPTURE:
1181 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001182 case SPATIALIZER:
1183 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001184 default:
1185 ALOG_ASSERT(false);
1186 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001187 }
1188}
1189
Andy Hung4b17e882023-07-07 13:47:37 -07001190void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001191{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001192 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001193 if (mPowerManager != 0) {
1194 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001195 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001196 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1197 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001198 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001199 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001200 {} /* workSource */,
1201 {} /* historyTag */);
1202 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001203 mWakeLockToken = binder;
1204 }
Chris Ye6597d732020-02-28 22:38:25 -08001205 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001206 }
Wei Jia3f273d12015-11-24 09:06:49 -08001207
Andy Hung3f0c9022016-01-15 17:49:46 -08001208 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001209 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1210 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001211}
1212
Andy Hung4b17e882023-07-07 13:47:37 -07001213void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001214{
Andy Hungf8635b62023-08-31 16:13:39 -07001215 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001216 releaseWakeLock_l();
1217}
1218
Andy Hung4b17e882023-07-07 13:47:37 -07001219void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001220{
Andy Hung3f0c9022016-01-15 17:49:46 -08001221 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001222 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001223 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001224 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001225 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001226 }
1227 mWakeLockToken.clear();
1228 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001229}
1230
Andy Hung4b17e882023-07-07 13:47:37 -07001231void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001232 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001233 // use checkService() to avoid blocking if power service is not up yet
1234 sp<IBinder> binder =
1235 defaultServiceManager()->checkService(String16("power"));
1236 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001237 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001238 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001239 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001240 binder->linkToDeath(mDeathRecipient);
1241 }
1242 }
1243}
1244
Andy Hung4b17e882023-07-07 13:47:37 -07001245void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001246 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001247
1248#if !LOG_NDEBUG
1249 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001250 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001251 s << uid << " ";
1252 }
1253 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1254#endif
1255
Andy Hung438e7572015-12-14 15:51:17 -08001256 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1257 if (mSystemReady) {
1258 ALOGE("no wake lock to update, but system ready!");
1259 } else {
1260 ALOGW("no wake lock to update, system not ready yet");
1261 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001262 return;
1263 }
1264 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001265 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001266 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1267 mWakeLockToken, uidsAsInt);
1268 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001269 }
1270}
1271
Andy Hung4b17e882023-07-07 13:47:37 -07001272void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001273{
Andy Hungf8635b62023-08-31 16:13:39 -07001274 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001275 releaseWakeLock_l();
1276 mPowerManager.clear();
1277}
1278
Andy Hung4b17e882023-07-07 13:47:37 -07001279void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001280 const DeviceDescriptorBaseVector& outDevices __unused)
1281{
1282 ALOGE("%s should only be called in RecordThread", __func__);
1283}
1284
Andy Hung4b17e882023-07-07 13:47:37 -07001285void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001286{
1287 ALOGE("%s should only be called in RecordThread", __func__);
1288}
1289
Andy Hung4b17e882023-07-07 13:47:37 -07001290void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001291{
1292 sp<ThreadBase> thread = mThread.promote();
1293 if (thread != 0) {
1294 thread->clearPowerManager();
1295 }
1296 ALOGW("power manager service died !!!");
1297}
1298
Andy Hung4b17e882023-07-07 13:47:37 -07001299void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001300 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001301{
Andy Hung116bc262023-06-20 18:56:17 -07001302 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001303 if (chain != 0) {
1304 if (type != NULL) {
1305 chain->setEffectSuspended_l(type, suspend);
1306 } else {
1307 chain->setEffectSuspendedAll_l(suspend);
1308 }
1309 }
1310
1311 updateSuspendedSessions_l(type, suspend, sessionId);
1312}
1313
Andy Hung4b17e882023-07-07 13:47:37 -07001314void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001315{
1316 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1317 if (index < 0) {
1318 return;
1319 }
1320
1321 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1322 mSuspendedSessions.valueAt(index);
1323
1324 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001325 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001326 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001327 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001328 chain->setEffectSuspendedAll_l(true);
1329 } else {
1330 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1331 desc->mType.timeLow);
1332 chain->setEffectSuspended_l(&desc->mType, true);
1333 }
1334 }
1335 }
1336}
1337
Andy Hung4b17e882023-07-07 13:47:37 -07001338void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001339 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001340 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001341{
1342 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1343
1344 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1345
1346 if (suspend) {
1347 if (index >= 0) {
1348 sessionEffects = mSuspendedSessions.valueAt(index);
1349 } else {
1350 mSuspendedSessions.add(sessionId, sessionEffects);
1351 }
1352 } else {
1353 if (index < 0) {
1354 return;
1355 }
1356 sessionEffects = mSuspendedSessions.valueAt(index);
1357 }
1358
1359
Andy Hung116bc262023-06-20 18:56:17 -07001360 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 if (type != NULL) {
1362 key = type->timeLow;
1363 }
1364 index = sessionEffects.indexOfKey(key);
1365
1366 sp<SuspendedSessionDesc> desc;
1367 if (suspend) {
1368 if (index >= 0) {
1369 desc = sessionEffects.valueAt(index);
1370 } else {
1371 desc = new SuspendedSessionDesc();
1372 if (type != NULL) {
1373 desc->mType = *type;
1374 }
1375 sessionEffects.add(key, desc);
1376 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1377 }
1378 desc->mRefCount++;
1379 } else {
1380 if (index < 0) {
1381 return;
1382 }
1383 desc = sessionEffects.valueAt(index);
1384 if (--desc->mRefCount == 0) {
1385 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1386 sessionEffects.removeItemsAt(index);
1387 if (sessionEffects.isEmpty()) {
1388 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1389 sessionId);
1390 mSuspendedSessions.removeItem(sessionId);
1391 }
1392 }
1393 }
1394 if (!sessionEffects.isEmpty()) {
1395 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1396 }
1397}
1398
Andy Hung4b17e882023-07-07 13:47:37 -07001399void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001400 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001401 bool threadLocked)
1402NO_THREAD_SAFETY_ANALYSIS // manual locking
1403{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001404 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001405 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001406 }
Eric Laurent81784c32012-11-19 14:55:58 -08001407
Eric Laurent81784c32012-11-19 14:55:58 -08001408 if (mType != RECORD) {
1409 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1410 // another session. This gives the priority to well behaved effect control panels
1411 // and applications not using global effects.
1412 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1413 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001414 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001415 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1416 }
1417 }
1418
Eric Laurent6b446ce2019-12-13 10:56:31 -08001419 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001420 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001421 }
1422}
1423
Andy Hungb17d24b2023-08-29 14:26:09 -07001424// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001425status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001426 const effect_descriptor_t *desc, audio_session_t sessionId)
1427{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001428 // No global output effect sessions on record threads
1429 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1430 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001431 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1432 desc->name, mThreadName);
1433 return BAD_VALUE;
1434 }
1435 // only pre processing effects on record thread
1436 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1437 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1438 desc->name, mThreadName);
1439 return BAD_VALUE;
1440 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001441
1442 // always allow effects without processing load or latency
1443 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1444 return NO_ERROR;
1445 }
1446
Eric Laurent4c415062016-06-17 16:14:16 -07001447 audio_input_flags_t flags = mInput->flags;
1448 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1449 if (flags & AUDIO_INPUT_FLAG_RAW) {
1450 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1451 desc->name, mThreadName);
1452 return BAD_VALUE;
1453 }
1454 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1455 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1456 desc->name, mThreadName);
1457 return BAD_VALUE;
1458 }
1459 }
jiabineb3bda02020-06-30 14:07:03 -07001460
Andy Hung116bc262023-06-20 18:56:17 -07001461 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001462 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1463 return BAD_VALUE;
1464 }
Eric Laurent4c415062016-06-17 16:14:16 -07001465 return NO_ERROR;
1466}
1467
Andy Hungb17d24b2023-08-29 14:26:09 -07001468// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001469status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001470 const effect_descriptor_t *desc, audio_session_t sessionId)
1471{
1472 // no preprocessing on playback threads
1473 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001474 ALOGW("%s: pre processing effect %s created on playback"
1475 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001476 return BAD_VALUE;
1477 }
1478
Eric Laurent3e4de772017-07-16 16:55:08 -07001479 // always allow effects without processing load or latency
1480 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1481 return NO_ERROR;
1482 }
1483
Andy Hung116bc262023-06-20 18:56:17 -07001484 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001485 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1486 __func__);
1487 return BAD_VALUE;
1488 }
1489
Eric Laurent4eb45d02023-12-20 12:07:17 +01001490 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001491 && mType != SPATIALIZER) {
1492 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1493 __func__, mType);
1494 return BAD_VALUE;
1495 }
1496
Eric Laurent4c415062016-06-17 16:14:16 -07001497 switch (mType) {
1498 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001499 audio_output_flags_t flags = mOutput->flags;
1500 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1501 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1502 // global effects are applied only to non fast tracks if they are SW
1503 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1504 break;
1505 }
1506 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1507 // only post processing on output stage session
1508 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001509 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1510 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001511 return BAD_VALUE;
1512 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001513 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1514 // only post processing on output stage session
1515 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001516 ALOGW("%s: non post processing effect %s not allowed on device session",
1517 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001518 return BAD_VALUE;
1519 }
Eric Laurent4c415062016-06-17 16:14:16 -07001520 } else {
1521 // no restriction on effects applied on non fast tracks
1522 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1523 break;
1524 }
1525 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001526
Eric Laurent4c415062016-06-17 16:14:16 -07001527 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001528 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001529 return BAD_VALUE;
1530 }
1531 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001532 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1533 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001534 return BAD_VALUE;
1535 }
1536 }
1537 } break;
1538 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001539 // nothing actionable on offload threads, if the effect:
1540 // - is offloadable: the effect can be created
1541 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1542 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001543 break;
1544 case DIRECT:
1545 // Reject any effect on Direct output threads for now, since the format of
1546 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001547 ALOGW("%s: effect %s on DIRECT output thread %s",
1548 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001549 return BAD_VALUE;
1550 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001551 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001552 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1553 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001554 return BAD_VALUE;
1555 }
1556 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001557 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1558 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001559 return BAD_VALUE;
1560 }
1561 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001562 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1563 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001564 return BAD_VALUE;
1565 }
1566 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001567 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001568 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1569 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1570 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1571 // are supported and added after the spatializer.
1572 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1573 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1574 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001575 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001576 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1577 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001578 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001579 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1580 break;
1581 }
1582 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1583 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1584 __func__, desc->name);
1585 return BAD_VALUE;
1586 }
1587 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1588 // only post processing on output stage session
1589 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1590 ALOGW("%s: non post processing effect %s not allowed on device session",
1591 __func__, desc->name);
1592 return BAD_VALUE;
1593 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001594 }
1595 break;
jiabinc658e452022-10-21 20:52:21 +00001596 case BIT_PERFECT:
1597 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1598 // Allow HW accelerated effects of tunnel type
1599 break;
1600 }
1601 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1602 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1603 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1604 // 3) there is any bit-perfect track with the given session id.
1605 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1606 sessionId == AUDIO_SESSION_DEVICE) {
1607 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1608 __func__, desc->name, mThreadName);
1609 return BAD_VALUE;
1610 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1611 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1612 __func__, desc->name, sessionId);
1613 return BAD_VALUE;
1614 }
1615 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001616 default:
1617 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1618 }
1619
1620 return NO_ERROR;
1621}
1622
Andy Hungb17d24b2023-08-29 14:26:09 -07001623// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001624sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001625 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001626 const sp<IEffectClient>& effectClient,
1627 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001628 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001629 effect_descriptor_t *desc,
1630 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001631 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001632 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001633 bool probe,
1634 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001635{
Andy Hung116bc262023-06-20 18:56:17 -07001636 sp<IAfEffectModule> effect;
1637 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001638 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001639 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001640 bool chainCreated = false;
1641 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001642 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001643
1644 lStatus = initCheck();
1645 if (lStatus != NO_ERROR) {
1646 ALOGW("createEffect_l() Audio driver not initialized.");
1647 goto Exit;
1648 }
1649
Eric Laurent81784c32012-11-19 14:55:58 -08001650 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1651
Andy Hungb17d24b2023-08-29 14:26:09 -07001652 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07001653 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001654
Eric Laurent4c415062016-06-17 16:14:16 -07001655 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001656 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001657 goto Exit;
1658 }
1659
Eric Laurent81784c32012-11-19 14:55:58 -08001660 // check for existing effect chain with the requested audio session
1661 chain = getEffectChain_l(sessionId);
1662 if (chain == 0) {
1663 // create a new chain for this session
1664 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001665 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001666 addEffectChain_l(chain);
1667 chain->setStrategy(getStrategyForSession_l(sessionId));
1668 chainCreated = true;
1669 } else {
1670 effect = chain->getEffectFromDesc_l(desc);
1671 }
1672
1673 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1674
1675 if (effect == 0) {
Andy Hung7535ed92023-07-17 17:05:00 -07001676 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001677 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001678 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001679 if (lStatus != NO_ERROR) {
1680 goto Exit;
1681 }
1682 effectCreated = true;
1683
jiabinc52b1ff2019-10-31 17:20:42 -07001684 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001685 effect->setDevices(outDeviceTypeAddrs());
1686 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001687 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001688 effect->setAudioSource(mAudioSource);
1689 }
jiabin1319f5a2021-03-30 22:21:24 +00001690 if (effect->isHapticGenerator()) {
1691 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1692 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001693 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung7535ed92023-07-17 17:05:00 -07001694 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001695 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001696 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001697 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001698 }
1699 }
Eric Laurent81784c32012-11-19 14:55:58 -08001700 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001701 handle = IAfEffectHandle::create(
1702 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001703 lStatus = handle->initCheck();
1704 if (lStatus == OK) {
1705 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001706 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001707 }
Eric Laurent81784c32012-11-19 14:55:58 -08001708 if (enabled != NULL) {
1709 *enabled = (int)effect->isEnabled();
1710 }
1711 }
1712
1713Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001714 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hungf8635b62023-08-31 16:13:39 -07001715 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001716 if (effectCreated) {
1717 chain->removeEffect_l(effect);
1718 }
Eric Laurent81784c32012-11-19 14:55:58 -08001719 if (chainCreated) {
1720 removeEffectChain_l(chain);
1721 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001722 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001723 }
1724
Glenn Kasten9156ef32013-08-06 15:39:08 -07001725 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001726 return handle;
1727}
1728
Andy Hung4b17e882023-07-07 13:47:37 -07001729void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001730 bool unpinIfLast)
1731{
1732 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001733 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001734 {
Andy Hungf8635b62023-08-31 16:13:39 -07001735 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001736 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001737 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001738 return;
1739 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001740 effect = effectBase->asEffectModule();
1741 if (effect == nullptr) {
1742 return;
1743 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001744 // restore suspended effects if the disconnected handle was enabled and the last one.
1745 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1746 if (remove) {
1747 removeEffect_l(effect, true);
1748 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001749 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750 }
1751 if (remove) {
Andy Hung7535ed92023-07-17 17:05:00 -07001752 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001753 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001754 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001755 }
1756 }
1757}
1758
Andy Hung4b17e882023-07-07 13:47:37 -07001759void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001760 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001761 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001762 broadcast_l();
1763 }
1764 if (!effect->isOffloadable()) {
1765 if (mType == ThreadBase::OFFLOAD) {
1766 PlaybackThread *t = (PlaybackThread *)this;
1767 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1768 }
1769 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung7535ed92023-07-17 17:05:00 -07001770 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001771 }
1772 }
1773}
1774
Andy Hung4b17e882023-07-07 13:47:37 -07001775void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001776 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001777 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001778 broadcast_l();
1779 }
1780}
1781
Andy Hung4b17e882023-07-07 13:47:37 -07001782sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001783 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001784{
Andy Hungf8635b62023-08-31 16:13:39 -07001785 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001786 return getEffect_l(sessionId, effectId);
1787}
1788
Andy Hung4b17e882023-07-07 13:47:37 -07001789sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001790 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001791{
Andy Hung116bc262023-06-20 18:56:17 -07001792 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001793 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1794}
1795
Andy Hung4b17e882023-07-07 13:47:37 -07001796std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001797{
Andy Hung116bc262023-06-20 18:56:17 -07001798 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001799 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001800}
1801
Andy Hungf8635b62023-08-31 16:13:39 -07001802// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1803// ThreadBase::mutex() held
1804status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001805{
1806 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001807 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001808 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001809 bool chainCreated = false;
1810
Eric Laurent5baf2af2013-09-12 17:37:00 -07001811 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hungf8635b62023-08-31 16:13:39 -07001812 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1813 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001814
Eric Laurent81784c32012-11-19 14:55:58 -08001815 if (chain == 0) {
1816 // create a new chain for this session
Andy Hungf8635b62023-08-31 16:13:39 -07001817 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001818 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001819 addEffectChain_l(chain);
1820 chain->setStrategy(getStrategyForSession_l(sessionId));
1821 chainCreated = true;
1822 }
Andy Hungf8635b62023-08-31 16:13:39 -07001823 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001824
1825 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hungf8635b62023-08-31 16:13:39 -07001826 ALOGW("%s: %p effect %s already present in chain %p",
1827 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001828 return BAD_VALUE;
1829 }
1830
Shunkai Yaod125e402024-01-20 03:19:06 +00001831 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001832
Eric Laurent81784c32012-11-19 14:55:58 -08001833 status_t status = chain->addEffect_l(effect);
1834 if (status != NO_ERROR) {
1835 if (chainCreated) {
1836 removeEffectChain_l(chain);
1837 }
1838 return status;
1839 }
1840
jiabin8f278ee2019-11-11 12:16:27 -08001841 effect->setDevices(outDeviceTypeAddrs());
1842 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001843 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001844 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001845
Eric Laurent81784c32012-11-19 14:55:58 -08001846 return NO_ERROR;
1847}
1848
Andy Hung4b17e882023-07-07 13:47:37 -07001849void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001850
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001851 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001852 effect_descriptor_t desc = effect->desc();
1853 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1854 detachAuxEffect_l(effect->id());
1855 }
1856
Andy Hung116bc262023-06-20 18:56:17 -07001857 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001858 if (chain != 0) {
1859 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001860 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001861 removeEffectChain_l(chain);
1862 }
1863 } else {
1864 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1865 }
1866}
1867
Shunkai Yaof4847652024-01-12 00:25:20 +00001868void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1869 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001870{
1871 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001872 for (const auto& effectChain : effectChains) {
1873 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001874 }
1875}
1876
Shunkai Yaof4847652024-01-12 00:25:20 +00001877void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1878 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001879{
Shunkai Yaof4847652024-01-12 00:25:20 +00001880 for (const auto& effectChain : effectChains) {
1881 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001882 }
1883}
1884
Andy Hung4b17e882023-07-07 13:47:37 -07001885sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001886{
Andy Hungf8635b62023-08-31 16:13:39 -07001887 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001888 return getEffectChain_l(sessionId);
1889}
1890
Andy Hung4b17e882023-07-07 13:47:37 -07001891sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001892 const
Eric Laurent81784c32012-11-19 14:55:58 -08001893{
1894 size_t size = mEffectChains.size();
1895 for (size_t i = 0; i < size; i++) {
1896 if (mEffectChains[i]->sessionId() == sessionId) {
1897 return mEffectChains[i];
1898 }
1899 }
1900 return 0;
1901}
1902
Andy Hung4b17e882023-07-07 13:47:37 -07001903void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001904{
Andy Hungf8635b62023-08-31 16:13:39 -07001905 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001906 size_t size = mEffectChains.size();
1907 for (size_t i = 0; i < size; i++) {
1908 mEffectChains[i]->setMode_l(mode);
1909 }
1910}
1911
Andy Hung4b17e882023-07-07 13:47:37 -07001912void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001913{
1914 config->type = AUDIO_PORT_TYPE_MIX;
1915 config->ext.mix.handle = mId;
1916 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001917 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001918 config->channel_mask = mChannelMask;
1919 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1920 AUDIO_PORT_CONFIG_FORMAT;
1921}
1922
Andy Hung4b17e882023-07-07 13:47:37 -07001923void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001924{
Andy Hungf8635b62023-08-31 16:13:39 -07001925 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001926 if (mSystemReady) {
1927 return;
1928 }
1929 mSystemReady = true;
1930
1931 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1932 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1933 }
1934 mPendingConfigEvents.clear();
1935}
1936
Andy Hungdae27702016-10-31 14:01:16 -07001937template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001938ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001939 ssize_t index = mActiveTracks.indexOf(track);
1940 if (index >= 0) {
1941 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1942 return index;
1943 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001944 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001945 mActiveTracksGeneration++;
1946 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001947 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001948 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001949 return mActiveTracks.add(track);
1950}
1951
1952template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001953ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001954 ssize_t index = mActiveTracks.remove(track);
1955 if (index < 0) {
1956 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1957 return index;
1958 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001959 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001960 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001961 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001962 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001963 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001964#ifdef TEE_SINK
1965 track->dumpTee(-1 /* fd */, "_REMOVE");
1966#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001967 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001968 return index;
1969}
1970
1971template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001972void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001973 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001974 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001975 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001976 }
1977 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001978 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001979 mActiveTracks.clear();
1980 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001981}
1982
1983template <typename T>
Andy Hung94dfbb42023-09-06 19:41:47 -07001984void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001985 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001986 // Updates ActiveTracks client uids to the thread wakelock.
1987 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1988 thread->updateWakeLockUids_l(getWakeLockUids());
1989 mLastActiveTracksGeneration = mActiveTracksGeneration;
1990 }
Andy Hungdae27702016-10-31 14:01:16 -07001991}
Eric Laurent83b88082014-06-20 18:31:16 -07001992
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001993template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001994bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001995 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001996 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001997
1998 for (const sp<T> &track : mActiveTracks) {
1999 // Do not short-circuit as all hasChanged states must be reset
2000 // as all the metadata are going to be sent
2001 hasChanged |= track->readAndClearHasChanged();
2002 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002003 return hasChanged;
2004}
2005
2006template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002007void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002008 const char *funcName, const sp<T> &track) const {
2009 if (mLocalLog != nullptr) {
2010 String8 result;
2011 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002012 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002013 }
2014}
2015
Andy Hung4b17e882023-07-07 13:47:37 -07002016void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002017{
2018 // Thread could be blocked waiting for async
2019 // so signal it to handle state changes immediately
2020 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2021 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2022 mSignalPending = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07002023 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002024}
2025
Andy Hungd0979812019-02-21 15:51:44 -08002026// Call only from threadLoop() or when it is idle.
2027// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07002028void ThreadBase::sendStatistics(bool force)
Andy Hung94dfbb42023-09-06 19:41:47 -07002029NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002030{
2031 // Do not log if we have no stats.
2032 // We choose the timestamp verifier because it is the most likely item to be present.
2033 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2034 if (nstats == 0) {
2035 return;
2036 }
2037
2038 // Don't log more frequently than once per 12 hours.
2039 // We use BOOTTIME to include suspend time.
2040 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2041 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2042 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2043 return;
2044 }
2045
2046 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2047 mLastRecordedTimeNs = timeNs;
2048
Ray Essickf27e9872019-12-07 06:28:46 -08002049 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002050
2051#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2052
2053 // thread configuration
2054 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2055 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2056 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2057 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2058 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2059 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2060 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hung94dfbb42023-09-06 19:41:47 -07002061 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2062 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002063
2064 // thread statistics
2065 if (mIoJitterMs.getN() > 0) {
2066 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2067 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2068 }
2069 if (mProcessTimeMs.getN() > 0) {
2070 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2071 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2072 }
2073 const auto tsjitter = mTimestampVerifier.getJitterMs();
2074 if (tsjitter.getN() > 0) {
2075 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2076 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2077 }
2078 if (mLatencyMs.getN() > 0) {
2079 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2080 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2081 }
Robert Wu06db0a32021-08-10 19:05:34 +00002082 if (mMonopipePipeDepthStats.getN() > 0) {
2083 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2084 mMonopipePipeDepthStats.getMean());
2085 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2086 mMonopipePipeDepthStats.getStdDev());
2087 }
Andy Hungd0979812019-02-21 15:51:44 -08002088
2089 item->selfrecord();
2090}
2091
Andy Hung4b17e882023-07-07 13:47:37 -07002092product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002093{
Andy Hung7535ed92023-07-17 17:05:00 -07002094 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002095 return PRODUCT_STRATEGY_NONE;
2096 }
2097 return AudioSystem::getStrategyForStream(stream);
2098}
2099
Andy Hungb17d24b2023-08-29 14:26:09 -07002100// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002101void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002102 const sp<audio_utils::MelProcessor>& /*processor*/)
2103{
2104 // Do nothing
2105 ALOGW("%s: ThreadBase does not support CSD", __func__);
2106}
2107
Andy Hungb17d24b2023-08-29 14:26:09 -07002108// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002109void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002110{
2111 // Do nothing
2112 ALOGW("%s: ThreadBase does not support CSD", __func__);
2113}
2114
Eric Laurent81784c32012-11-19 14:55:58 -08002115// ----------------------------------------------------------------------------
2116// Playback
2117// ----------------------------------------------------------------------------
2118
Andy Hung7535ed92023-07-17 17:05:00 -07002119PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002120 AudioStreamOut* output,
2121 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002122 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002123 bool systemReady,
2124 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002125 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002126 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002127 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002128 mMixerBuffer(NULL),
2129 mMixerBufferSize(0),
2130 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2131 mMixerBufferValid(false),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002132 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002133 mEffectBuffer(NULL),
2134 mEffectBufferSize(0),
2135 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2136 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002137 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002138 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002139 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002140 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002141 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002142 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002143 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002144 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002145 mMixerStatus(MIXER_IDLE),
2146 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hungd58c4732023-07-20 21:31:38 -07002147 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002148 mBytesRemaining(0),
2149 mCurrentWriteLength(0),
2150 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002151 mWriteAckSequence(0),
2152 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002153 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002154 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002155 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002156 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002157 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002158 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002159 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002160{
Glenn Kastend7dca052015-03-05 16:05:54 -08002161 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002162 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002163
Andy Hungb17d24b2023-08-29 14:26:09 -07002164 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002165 // it would be safer to explicitly pass initial masterVolume/masterMute as
2166 // parameter.
2167 //
2168 // If the HAL we are using has support for master volume or master mute,
2169 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2170 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002171 mMasterVolume = afThreadCallback->masterVolume_l();
2172 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002173 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002174 if (mOutput->audioHwDev->canSetMasterVolume()) {
2175 mMasterVolume = 1.0;
2176 }
2177
2178 if (mOutput->audioHwDev->canSetMasterMute()) {
2179 mMasterMute = false;
2180 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002181 mIsMsdDevice = strcmp(
2182 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002183 }
2184
Eric Laurentf1f22e72021-07-13 14:04:14 +02002185 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2186 mMixerChannelMask = mixerConfig->channel_mask;
2187 }
2188
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002189 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002190
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002191 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002192 && mMixerChannelMask != mChannelMask) {
2193 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2194 mChannelMask, mMixerChannelMask);
2195 }
2196
Andy Hungc8fddf32018-08-08 18:32:37 -07002197 // TODO: We may also match on address as well as device type for
2198 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002199 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002200 // TODO: This property should be ensure that only contains one single device type.
2201 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2202 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002203 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2204 : AUDIO_DEVICE_NONE));
2205 }
2206
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002207 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2208 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002209 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002210 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002211 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002212 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002213 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2214 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002215 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2216 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002217}
2218
Andy Hung4b17e882023-07-07 13:47:37 -07002219PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002220{
Andy Hung7535ed92023-07-17 17:05:00 -07002221 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002222 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002223 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002224 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002225 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002226}
2227
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002228// Thread virtuals
2229
Andy Hung4b17e882023-07-07 13:47:37 -07002230void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002231{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002232 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002233 ALOGE("The stream is not open yet"); // This should not happen.
2234 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002235 // Callbacks take strong or weak pointers as a parameter.
2236 // Since PlaybackThread passes itself as a callback handler, it can only
2237 // be done outside of the constructor. Creating weak and especially strong
2238 // pointers to a refcounted object in its own constructor is strongly
2239 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2240 // Even if a function takes a weak pointer, it is possible that it will
2241 // need to convert it to a strong pointer down the line.
2242 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2243 mOutput->stream->setCallback(this) == OK) {
2244 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002245 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002246 }
2247
jiabinf6eb4c32020-02-25 14:06:25 -08002248 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002249 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002250 }
2251 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002252 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002253 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002254}
2255
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002256// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002257void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002258{
2259 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002260 status_t result = mOutput->stream->exit();
2261 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002262}
2263
Andy Hung4b17e882023-07-07 13:47:37 -07002264void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002265{
Eric Laurent81784c32012-11-19 14:55:58 -08002266 String8 result;
2267
Marco Nelissenb2208842014-02-07 14:00:50 -08002268 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002269 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2270 const stream_type_t *st = &mStreamTypes[i];
2271 if (i > 0) {
2272 result.appendFormat(", ");
2273 }
2274 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2275 if (st->mute) {
2276 result.append("M");
2277 }
2278 }
2279 result.append("\n");
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002280 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002281 result.clear();
2282
Eric Laurent81784c32012-11-19 14:55:58 -08002283 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2284 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002285 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002286 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002287
2288 size_t numtracks = mTracks.size();
2289 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002290 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002291 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002292 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002293 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002294 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002295 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002296 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002297 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002298 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002299 if (track != 0) {
2300 bool active = mActiveTracks.indexOf(track) >= 0;
2301 if (active) {
2302 numactiveseen++;
2303 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002304 result.append(prefix);
2305 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002306 }
2307 }
2308 } else {
2309 result.append("\n");
2310 }
2311 if (numactiveseen != numactive) {
2312 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002313 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002314 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002315 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002316 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002317 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002318 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002319 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002320 result.append(prefix);
2321 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002322 }
2323 }
2324 }
2325
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002326 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002327}
2328
Andy Hung4b17e882023-07-07 13:47:37 -07002329void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002330{
Andy Hung04cb8f72020-03-20 13:44:33 -07002331 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002332 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002333 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2334 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002335 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2336 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2337 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2338 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002339 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002340 dprintf(fd, " Total writes: %d\n", mNumWrites);
2341 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2342 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung160664b2023-09-15 18:19:28 -07002343 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002344 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002345 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002346 AudioStreamOut *output = mOutput;
2347 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002348 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002349 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002350 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2351 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2352 if (mPipeSink.get() != nullptr) {
2353 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2354 }
2355 if (output != nullptr) {
2356 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002357 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002358 }
Eric Laurent81784c32012-11-19 14:55:58 -08002359}
2360
Andy Hungb17d24b2023-08-29 14:26:09 -07002361// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002362sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002363 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002364 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002365 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002366 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002367 audio_format_t format,
2368 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002369 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002370 size_t *pNotificationFrameCount,
2371 uint32_t notificationsPerBuffer,
2372 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002373 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002374 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002375 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002376 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002377 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002378 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002379 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002380 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002381 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002382 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002383 bool isBitPerfect,
2384 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002385{
Glenn Kasten74935e42013-12-19 08:56:45 -08002386 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002387 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002388 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002389 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002390 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002391 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002392 uint32_t sampleRate;
2393
2394 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2395 lStatus = BAD_VALUE;
2396 goto Exit;
2397 }
Eric Laurent21da6472017-11-09 16:29:26 -08002398
2399 if (*pSampleRate == 0) {
2400 *pSampleRate = mSampleRate;
2401 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002402 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002403
2404 // special case for FAST flag considered OK if fast mixer is present
2405 if (hasFastMixer()) {
2406 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2407 }
2408
2409 // Check if requested flags are compatible with output stream flags
2410 if ((*flags & outputFlags) != *flags) {
2411 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2412 *flags, outputFlags);
2413 *flags = (audio_output_flags_t)(*flags & outputFlags);
2414 }
Eric Laurent81784c32012-11-19 14:55:58 -08002415
jiabinc658e452022-10-21 20:52:21 +00002416 if (isBitPerfect) {
Andy Hung160664b2023-09-15 18:19:28 -07002417 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002418 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002419 if (chain.get() != nullptr) {
2420 // Bit-perfect is required according to the configuration and preferred mixer
2421 // attributes, but it is not in the output flag from the client's request. Explicitly
2422 // adding bit-perfect flag to check the compatibility
2423 audio_output_flags_t flagsToCheck =
2424 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2425 chain->checkOutputFlagCompatibility(&flagsToCheck);
2426 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2427 ALOGE("%s cannot create track as there is data-processing effect attached to "
2428 "given session id(%d)", __func__, sessionId);
2429 lStatus = BAD_VALUE;
2430 goto Exit;
2431 }
2432 *flags = flagsToCheck;
2433 }
2434 }
2435
Eric Laurent81784c32012-11-19 14:55:58 -08002436 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002437 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002438 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002439 // PCM data
2440 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002441 // TODO: extract as a data library function that checks that a computationally
2442 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002443 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002444 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2445 (channelMask == AUDIO_CHANNEL_OUT_MONO
2446 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002447 // hardware sample rate
2448 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002449 // normal mixer has an associated fast mixer
2450 hasFastMixer() &&
2451 // there are sufficient fast track slots available
2452 (mFastTrackAvailMask != 0)
2453 // FIXME test that MixerThread for this fast track has a capable output HAL
2454 // FIXME add a permission test also?
2455 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002456 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2457 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002458 // read the fast track multiplier property the first time it is needed
2459 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2460 if (ok != 0) {
2461 ALOGE("%s pthread_once failed: %d", __func__, ok);
2462 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002463 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002464 }
Eric Laurent4c415062016-06-17 16:14:16 -07002465
2466 // check compatibility with audio effects.
Andy Hungb17d24b2023-08-29 14:26:09 -07002467 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002468 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002469 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002470 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002471 AUDIO_SESSION_OUTPUT_STAGE,
2472 AUDIO_SESSION_OUTPUT_MIX,
2473 sessionId,
2474 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002475 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002476 if (chain.get() != nullptr) {
2477 audio_output_flags_t old = *flags;
2478 chain->checkOutputFlagCompatibility(flags);
2479 if (old != *flags) {
2480 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2481 (int)session, (int)old, (int)*flags);
2482 }
Eric Laurent4c415062016-06-17 16:14:16 -07002483 }
2484 }
2485 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002486 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002487 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2488 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002489 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002490 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002491 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002492 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002493 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002494 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002495 audio_is_linear_pcm(format), channelMask, sampleRate,
2496 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002497 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002498 }
2499 }
Eric Laurent21da6472017-11-09 16:29:26 -08002500
2501 if (!audio_has_proportional_frames(format)) {
2502 if (sharedBuffer != 0) {
2503 // Same comment as below about ignoring frameCount parameter for set()
2504 frameCount = sharedBuffer->size();
2505 } else if (frameCount == 0) {
2506 frameCount = mNormalFrameCount;
2507 }
2508 if (notificationFrameCount != frameCount) {
2509 notificationFrameCount = frameCount;
2510 }
2511 } else if (sharedBuffer != 0) {
2512 // FIXME: Ensure client side memory buffers need
2513 // not have additional alignment beyond sample
2514 // (e.g. 16 bit stereo accessed as 32 bit frame).
2515 size_t alignment = audio_bytes_per_sample(format);
2516 if (alignment & 1) {
2517 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2518 alignment = 1;
2519 }
2520 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2521 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2522 if (channelCount > 1) {
2523 // More than 2 channels does not require stronger alignment than stereo
2524 alignment <<= 1;
2525 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002526 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002527 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002528 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002529 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002530 goto Exit;
2531 }
Eric Laurent21da6472017-11-09 16:29:26 -08002532
2533 // When initializing a shared buffer AudioTrack via constructors,
2534 // there's no frameCount parameter.
2535 // But when initializing a shared buffer AudioTrack via set(),
2536 // there _is_ a frameCount parameter. We silently ignore it.
2537 frameCount = sharedBuffer->size() / frameSize;
2538 } else {
2539 size_t minFrameCount = 0;
2540 // For fast tracks we try to respect the application's request for notifications per buffer.
2541 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2542 if (notificationsPerBuffer > 0) {
2543 // Avoid possible arithmetic overflow during multiplication.
2544 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2545 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2546 notificationsPerBuffer, mFrameCount);
2547 } else {
2548 minFrameCount = mFrameCount * notificationsPerBuffer;
2549 }
2550 }
2551 } else {
2552 // For normal PCM streaming tracks, update minimum frame count.
2553 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2554 // cover audio hardware latency.
2555 // This is probably too conservative, but legacy application code may depend on it.
2556 // If you change this calculation, also review the start threshold which is related.
2557 uint32_t latencyMs = latency_l();
2558 if (latencyMs == 0) {
2559 ALOGE("Error when retrieving output stream latency");
2560 lStatus = UNKNOWN_ERROR;
2561 goto Exit;
2562 }
2563
2564 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2565 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2566
Eric Laurent81784c32012-11-19 14:55:58 -08002567 }
Eric Laurent21da6472017-11-09 16:29:26 -08002568 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002569 frameCount = minFrameCount;
2570 }
Eric Laurent81784c32012-11-19 14:55:58 -08002571 }
Eric Laurent21da6472017-11-09 16:29:26 -08002572
2573 // Make sure that application is notified with sufficient margin before underrun.
2574 // The client can divide the AudioTrack buffer into sub-buffers,
2575 // and expresses its desire to server as the notification frame count.
2576 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2577 size_t maxNotificationFrames;
2578 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2579 // notify every HAL buffer, regardless of the size of the track buffer
2580 maxNotificationFrames = mFrameCount;
2581 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002582 // Triple buffer the notification period for a triple buffered mixer period;
2583 // otherwise, double buffering for the notification period is fine.
2584 //
2585 // TODO: This should be moved to AudioTrack to modify the notification period
2586 // on AudioTrack::setBufferSizeInFrames() changes.
2587 const int nBuffering =
2588 (uint64_t{frameCount} * mSampleRate)
2589 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2590
Eric Laurent21da6472017-11-09 16:29:26 -08002591 maxNotificationFrames = frameCount / nBuffering;
2592 // If client requested a fast track but this was denied, then use the smaller maximum.
2593 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2594 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2595 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2596 maxNotificationFrames = maxNotificationFramesFastDenied;
2597 }
2598 }
2599 }
2600 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2601 if (notificationFrameCount == 0) {
2602 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2603 maxNotificationFrames, frameCount);
2604 } else {
2605 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2606 notificationFrameCount, maxNotificationFrames, frameCount);
2607 }
2608 notificationFrameCount = maxNotificationFrames;
2609 }
2610 }
2611
Glenn Kasten74935e42013-12-19 08:56:45 -08002612 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002613 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002614
Glenn Kastenc3df8382014-03-13 15:05:25 -07002615 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002616 case BIT_PERFECT:
2617 if (isBitPerfect) {
2618 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2619 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2620 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2621 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2622 mChannelMask);
2623 lStatus = BAD_VALUE;
2624 goto Exit;
2625 }
2626 }
2627 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002628
2629 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002630 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002631 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002632 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2633 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002634 sampleRate, format, channelMask, mOutput, mFormat);
2635 lStatus = BAD_VALUE;
2636 goto Exit;
2637 }
2638 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002639 break;
2640
2641 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002643 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2644 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 sampleRate, format, channelMask, mOutput, mFormat);
2646 lStatus = BAD_VALUE;
2647 goto Exit;
2648 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002649 break;
2650
2651 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002652 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002653 ALOGE("createTrack_l() Bad parameter: format %#x \""
2654 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 format, mOutput, mFormat);
2656 lStatus = BAD_VALUE;
2657 goto Exit;
2658 }
Andy Hungcd044842014-08-07 11:04:34 -07002659 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002660 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2661 lStatus = BAD_VALUE;
2662 goto Exit;
2663 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002664 break;
2665
Eric Laurent81784c32012-11-19 14:55:58 -08002666 }
2667
2668 lStatus = initCheck();
2669 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002670 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002671 goto Exit;
2672 }
2673
Andy Hungb17d24b2023-08-29 14:26:09 -07002674 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002675 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002676
2677 // all tracks in same audio session must share the same routing strategy otherwise
2678 // conflicts will happen when tracks are moved from one output to another by audio policy
2679 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002680 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002681 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002682 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002683 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002684 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002685 if (sessionId == t->sessionId() && strategy != actual) {
2686 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2687 strategy, actual);
2688 lStatus = BAD_VALUE;
2689 goto Exit;
2690 }
2691 }
2692 }
2693
Deeraj Soman2b515232024-05-14 12:58:24 +05302694 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2695 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002696 // dynamic audio policy.
2697 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302698 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002699 audio_output_flags_t trackFlags = *flags;
2700 if (mType == DIRECT) {
2701 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302702 } else if (mType == OFFLOAD) {
2703 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2704 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002705 }
jiabin94ed47c2023-07-27 23:34:20 +00002706 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002707
Andy Hung11e74242023-06-26 19:20:57 -07002708 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002709 channelMask, frameCount,
2710 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002711 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002712 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002713 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002714
Glenn Kasten03003332013-08-06 15:40:54 -07002715 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2716 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002717 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002718 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002719 goto Exit;
2720 }
2721 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002722 {
Andy Hungf8635b62023-08-31 16:13:39 -07002723 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002724 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002725 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002726 }
2727 }
Eric Laurent81784c32012-11-19 14:55:58 -08002728
Andy Hung116bc262023-06-20 18:56:17 -07002729 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002730 if (chain != 0) {
2731 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2732 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002733 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002734 chain->incTrackCnt();
2735 }
2736
Eric Laurent05067782016-06-01 18:27:28 -07002737 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002738 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2739 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2740 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002741 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002742 }
2743 }
2744
2745 lStatus = NO_ERROR;
2746
2747Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002748 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002749 return track;
2750}
2751
Andy Hung1bc088a2018-02-09 15:57:31 -08002752template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002753ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002754{
Andy Hungc0691382018-09-12 18:01:57 -07002755 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002756 const ssize_t index = mTracks.remove(track);
2757 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002758 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002759 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002760 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002761 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002762 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002763 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002764 }
2765 return index;
2766}
2767
Andy Hung4b17e882023-07-07 13:47:37 -07002768uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002769{
2770 return latency;
2771}
2772
Andy Hung4b17e882023-07-07 13:47:37 -07002773uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002774{
Andy Hungf8635b62023-08-31 16:13:39 -07002775 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002776 return latency_l();
2777}
Andy Hung4b17e882023-07-07 13:47:37 -07002778uint32_t PlaybackThread::latency_l() const
Andy Hung94dfbb42023-09-06 19:41:47 -07002779NO_THREAD_SAFETY_ANALYSIS
2780// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002781{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002782 uint32_t latency;
2783 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2784 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002785 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002786 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002787}
2788
Andy Hung4b17e882023-07-07 13:47:37 -07002789void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002790{
Andy Hungf8635b62023-08-31 16:13:39 -07002791 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002792 // Don't apply master volume in SW if our HAL can do it for us.
2793 if (mOutput && mOutput->audioHwDev &&
2794 mOutput->audioHwDev->canSetMasterVolume()) {
2795 mMasterVolume = 1.0;
2796 } else {
2797 mMasterVolume = value;
2798 }
2799}
2800
Andy Hung4b17e882023-07-07 13:47:37 -07002801void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002802{
2803 mMasterBalance.store(balance);
2804}
2805
Andy Hung4b17e882023-07-07 13:47:37 -07002806void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002807{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002808 if (isDuplicating()) {
2809 return;
2810 }
Andy Hungf8635b62023-08-31 16:13:39 -07002811 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002812 // Don't apply master mute in SW if our HAL can do it for us.
2813 if (mOutput && mOutput->audioHwDev &&
2814 mOutput->audioHwDev->canSetMasterMute()) {
2815 mMasterMute = false;
2816 } else {
2817 mMasterMute = muted;
2818 }
2819}
2820
Andy Hung4b17e882023-07-07 13:47:37 -07002821void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002822{
Andy Hungf8635b62023-08-31 16:13:39 -07002823 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002824 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002825 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002826}
2827
Andy Hung4b17e882023-07-07 13:47:37 -07002828void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002829{
Andy Hungf8635b62023-08-31 16:13:39 -07002830 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002831 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002832 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002833}
2834
Andy Hung4b17e882023-07-07 13:47:37 -07002835float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002836{
Andy Hungf8635b62023-08-31 16:13:39 -07002837 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002838 return mStreamTypes[stream].volume;
2839}
2840
Andy Hung4b17e882023-07-07 13:47:37 -07002841void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002842{
2843 mOutput->stream->setVolume(left, right);
2844}
2845
Andy Hungb17d24b2023-08-29 14:26:09 -07002846// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002847status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002848{
2849 status_t status = ALREADY_EXISTS;
2850
Eric Laurent81784c32012-11-19 14:55:58 -08002851 if (mActiveTracks.indexOf(track) < 0) {
2852 // the track is newly added, make sure it fills up all its
2853 // buffers before playing. This is to ensure the client will
2854 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002855 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002856 IAfTrackBase::track_state state = track->state();
Andy Hunga7187712023-12-05 17:28:17 -08002857 // Because the track is not on the ActiveTracks,
2858 // at this point, only the TrackHandle will be adding the track.
Andy Hungb17d24b2023-08-29 14:26:09 -07002859 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002860 status = AudioSystem::startOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002861 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002862 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002863 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864 if (status == NO_ERROR) {
Andy Hungb17d24b2023-08-29 14:26:09 -07002865 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002866 AudioSystem::stopOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002867 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 }
2869 return INVALID_OPERATION;
2870 }
2871 // abort if start is rejected by audio policy manager
2872 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002873 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2874 // current playback thread is reopened, which may happen when clients set preferred
2875 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2876 // immediately.
2877 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 }
2879#ifdef ADD_BATTERY_DATA
2880 // to track the speaker usage
2881 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2882#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002883 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 }
2885
Eric Laurent51716182016-02-29 18:00:56 -08002886 // set retry count for buffer fill
2887 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002888 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002889 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002890 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002891 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002892 }
Andy Hung11e74242023-06-26 19:20:57 -07002893 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002894 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002895 track->retryCount() = kMaxTrackStartupRetries;
2896 track->fillingStatus() =
2897 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002898 }
2899
Andy Hung116bc262023-06-20 18:56:17 -07002900 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002901 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2902 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2903 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002904 // Unlock due to VibratorService will lock for this call and will
2905 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungb17d24b2023-08-29 14:26:09 -07002906 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002907 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002908 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002909 std::optional<media::AudioVibratorInfo> vibratorInfo;
2910 {
2911 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2912 // used to play this track.
Andy Hungf8635b62023-08-31 16:13:39 -07002913 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung7535ed92023-07-17 17:05:00 -07002914 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002915 }
Andy Hungb17d24b2023-08-29 14:26:09 -07002916 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002917 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002918 if (vibratorInfo) {
2919 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2920 }
2921
jiabin57303cc2018-12-18 15:45:57 -08002922 // Haptic playback should be enabled by vibrator service.
2923 if (track->getHapticPlaybackEnabled()) {
2924 // Disable haptic playback of all active track to ensure only
2925 // one track playing haptic if current track should play haptic.
2926 for (const auto &t : mActiveTracks) {
2927 t->setHapticPlaybackEnabled(false);
2928 }
jiabin245cdd92018-12-07 17:55:15 -08002929 }
jiabine70bc7f2020-06-30 22:07:55 -07002930
2931 // Set haptic intensity for effect
2932 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002933 // TODO(b/324559333): Add adaptive haptics scaling support for the HapticGenerator.
2934 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002935 }
jiabin245cdd92018-12-07 17:55:15 -08002936 }
2937
Andy Hung11e74242023-06-26 19:20:57 -07002938 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002939 track->resetPresentationComplete();
Andy Hunga7187712023-12-05 17:28:17 -08002940
2941 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2942 // all key changes are complete. It is possible that the threadLoop will begin
2943 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002944 mActiveTracks.add(track);
Andy Hunga7187712023-12-05 17:28:17 -08002945
Eric Laurentd0107bc2013-06-11 14:38:48 -07002946 if (chain != 0) {
2947 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2948 track->sessionId());
2949 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002950 }
2951
Andy Hungc2b11cb2020-04-22 09:04:01 -07002952 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002953 status = NO_ERROR;
2954 }
2955
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002956 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002957 return status;
2958}
2959
Andy Hung4b17e882023-07-07 13:47:37 -07002960bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002961{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002963 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002964 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002965 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002966 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002967 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002968 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002969 if (track->isPausePending()) {
2970 track->pauseAck();
2971 }
Andy Hung11e74242023-06-26 19:20:57 -07002972 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002973 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002974
2975 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002976}
2977
Andy Hung4b17e882023-07-07 13:47:37 -07002978void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002979{
2980 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002981
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002982 String8 result;
2983 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002984 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002985
Eric Laurent81784c32012-11-19 14:55:58 -08002986 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002987 {
Andy Hungf8635b62023-08-31 16:13:39 -07002988 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002989 mAudioTrackCallbacks.erase(track);
2990 }
Eric Laurent81784c32012-11-19 14:55:58 -08002991 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002992 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002993 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002994 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2995 mFastTrackAvailMask |= 1 << index;
2996 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07002997 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002998 }
Andy Hung116bc262023-06-20 18:56:17 -07002999 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003000 if (chain != 0) {
3001 chain->decTrackCnt();
3002 }
3003}
3004
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003005std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3006{
3007 std::set<int32_t> result;
3008 for (const auto& t : mTracks) {
3009 if (t->isExternalTrack()) {
3010 result.insert(t->portId());
3011 }
3012 }
3013 return result;
3014}
3015
3016std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3017{
3018 audio_utils::lock_guard _l(mutex());
3019 return getTrackPortIds_l();
3020}
3021
Andy Hung4b17e882023-07-07 13:47:37 -07003022String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003023{
Andy Hungf8635b62023-08-31 16:13:39 -07003024 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003025 String8 out_s8;
3026 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3027 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003028 }
Andy Hung920f6572022-10-06 12:09:49 -07003029 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003030}
3031
Andy Hung4b17e882023-07-07 13:47:37 -07003032status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hungf8635b62023-08-31 16:13:39 -07003033 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003034 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003035 return NO_INIT;
3036 }
3037 return mOutput->stream->selectPresentation(presentationId, programId);
3038}
3039
Andy Hung94dfbb42023-09-06 19:41:47 -07003040void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003041 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003042 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003043 sp<AudioIoDescriptor> desc;
3044 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003045 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003046 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003047 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003048 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003049 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3050 mSampleRate, mFormat, mChannelMask,
3051 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3052 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003053 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003054 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003055 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003056 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003057 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003058 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003059 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003060 break;
3061 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003062 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003063}
3064
Andy Hung4b17e882023-07-07 13:47:37 -07003065void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003067 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003068}
3069
Andy Hung4b17e882023-07-07 13:47:37 -07003070void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003071{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003072 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003073}
3074
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003075void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003076{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003077 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003078}
3079
Andy Hung4b17e882023-07-07 13:47:37 -07003080void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003081 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003082{
Andy Hung4b17e882023-07-07 13:47:37 -07003083 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003084 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07003085 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003086 if (playbackThread == nullptr) {
3087 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3088 return;
3089 }
3090
jiabinf6eb4c32020-02-25 14:06:25 -08003091 audio_utils::metadata::Data metadata =
3092 audio_utils::metadata::dataFromByteString(metadataBs);
3093 if (metadata.empty()) {
3094 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3095 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3096 (int)metadataBs.size());
3097 return;
3098 }
3099
3100 audio_utils::metadata::ByteString metaDataStr =
3101 audio_utils::metadata::byteStringFromData(metadata);
3102 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hungf8635b62023-08-31 16:13:39 -07003103 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003104 for (const auto& callbackPair : mAudioTrackCallbacks) {
3105 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003106 }
3107 }).detach();
3108}
3109
Andy Hung4b17e882023-07-07 13:47:37 -07003110void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003111{
Andy Hungf8635b62023-08-31 16:13:39 -07003112 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003113 // reject out of sequence requests
3114 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3115 mWriteAckSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003116 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117 }
3118}
3119
Andy Hung4b17e882023-07-07 13:47:37 -07003120void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003121{
Andy Hungf8635b62023-08-31 16:13:39 -07003122 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003123 // reject out of sequence requests
3124 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003125 // Register discontinuity when HW drain is completed because that can cause
3126 // the timestamp frame position to reset to 0 for direct and offload threads.
3127 // (Out of sequence requests are ignored, since the discontinuity would be handled
3128 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003129 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003130 mDrainSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003131 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003132 }
3133}
3134
Andy Hung4b17e882023-07-07 13:47:37 -07003135void PlaybackThread::readOutputParameters_l()
Andy Hungf8635b62023-08-31 16:13:39 -07003136NO_THREAD_SAFETY_ANALYSIS
3137// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003138{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003139 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003140 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3141 mSampleRate = audioConfig.sample_rate;
3142 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003143 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003144 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003145 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003146 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003147 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3148 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003149 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003150
3151 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3152 mMixerChannelMask = mChannelMask;
3153 }
3154
Andy Hunge5412692014-05-16 11:25:07 -07003155 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003156 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003157
Eric Laurentf1f22e72021-07-13 14:04:14 +02003158 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3159
Phil Burkca5e6142015-07-14 09:42:29 -07003160 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003161 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003162 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003163 // Get format from the shim, which will be different than the HAL format
3164 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003165 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003166 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003167 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003168 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003169 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003170 LOG_FATAL("HAL format %#x not supported for mixed output",
3171 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003172 }
Phil Burk062e67a2015-02-11 13:40:50 -08003173 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003174 result = mOutput->stream->getBufferSize(&mBufferSize);
3175 LOG_ALWAYS_FATAL_IF(result != OK,
3176 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003177 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003178 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003179 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003180 mFrameCount);
3181 }
3182
Eric Laurentd1f69b02014-12-15 14:33:13 -08003183 mHwSupportsPause = false;
3184 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003185 bool supportsPause = false, supportsResume = false;
3186 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3187 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003188 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003189 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003190 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003191 } else if (supportsResume) {
3192 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003193 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003194 }
3195 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003196 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3197 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3198 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003199
Andy Hungfbfc3952015-01-15 13:33:51 -08003200 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3201 // For best precision, we use float instead of the associated output
3202 // device format (typically PCM 16 bit).
3203
3204 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3205 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3206 mBufferSize = mFrameSize * mFrameCount;
3207
3208 // TODO: We currently use the associated output device channel mask and sample rate.
3209 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3210 // (if a valid mask) to avoid premature downmix.
3211 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3212 // instead of the output device sample rate to avoid loss of high frequency information.
3213 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3214 }
3215
Andy Hung09a50072014-02-27 14:30:47 -08003216 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003217 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003218 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003219 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3220 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003221 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3222 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003223
Eric Laurent81784c32012-11-19 14:55:58 -08003224 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3225 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3226 maxNormalFrameCount = maxNormalFrameCount & ~15;
3227 if (maxNormalFrameCount < minNormalFrameCount) {
3228 maxNormalFrameCount = minNormalFrameCount;
3229 }
3230 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3231 if (multiplier <= 1.0) {
3232 multiplier = 1.0;
3233 } else if (multiplier <= 2.0) {
3234 if (2 * mFrameCount <= maxNormalFrameCount) {
3235 multiplier = 2.0;
3236 } else {
3237 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3238 }
3239 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003240 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003241 }
3242 }
3243 mNormalFrameCount = multiplier * mFrameCount;
3244 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003245 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003246 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3247 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003248 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3249 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003250
Andy Hung08fb1742015-05-31 23:22:10 -07003251 // Check if we want to throttle the processing to no more than 2x normal rate
3252 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003253 mThreadThrottleTimeMs = 0;
3254 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003255 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3256
Andy Hung010a1a12014-03-13 13:57:33 -07003257 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3258 // Originally this was int16_t[] array, need to remove legacy implications.
3259 free(mSinkBuffer);
3260 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003261
Andy Hung5b10a202014-03-13 13:59:29 -07003262 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3263 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3264 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003265 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003266
Andy Hung69aed5f2014-02-25 17:24:40 -08003267 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3268 // drives the output.
3269 free(mMixerBuffer);
3270 mMixerBuffer = NULL;
3271 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003272 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003273 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003274 * audio_bytes_per_sample(mMixerBufferFormat);
3275 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3276 }
Andy Hung98ef9782014-03-04 14:46:50 -08003277 free(mEffectBuffer);
3278 mEffectBuffer = NULL;
3279 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003280 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003281 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003282 * audio_bytes_per_sample(mEffectBufferFormat);
3283 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3284 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003285
Eric Laurentb62d0362021-10-26 17:40:18 +02003286 if (mType == SPATIALIZER) {
3287 free(mPostSpatializerBuffer);
3288 mPostSpatializerBuffer = nullptr;
3289 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3290 * audio_bytes_per_sample(mEffectBufferFormat);
3291 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3292 }
3293
Mikhail Naganov55773032020-10-01 15:08:13 -07003294 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3295 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003296 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3297 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003298 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003299
Eric Laurent81784c32012-11-19 14:55:58 -08003300 // force reconfiguration of effect chains and engines to take new buffer size and audio
3301 // parameters into account
Andy Hungb17d24b2023-08-29 14:26:09 -07003302 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003303 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3304 // matter.
Andy Hungf8635b62023-08-31 16:13:39 -07003305 // create a copy of mEffectChains as calling moveEffectChain_ll()
3306 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003307 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003308 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hungf8635b62023-08-31 16:13:39 -07003309 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003310 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003311 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003312
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003313 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003314 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003315 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07003316 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003317 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3318 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3319 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3320 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3321 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3322 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3323 (int32_t)mHapticChannelMask)
3324 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3325 (int32_t)mHapticChannelCount)
3326 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -07003327 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003328 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3329 (int32_t)mFrameCount) // sic - added HAL
3330 ;
3331 uint32_t latencyMs;
3332 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3333 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3334 }
3335 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003336}
3337
Andy Hung4b17e882023-07-07 13:47:37 -07003338ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003339{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003340 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003341 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003342 }
3343 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003344 static const bool stereo_spatialization_property =
3345 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3346 const bool stereo_spatialization_enabled =
3347 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3348 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003349 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3350 for (const sp<IAfTrack>& track : mActiveTracks) {
3351 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3352 allSessionsMetadata[track->sessionId()];
3353 auto backInserter = std::back_inserter(sessionMetadata);
3354 // No track is invalid as this is called after prepareTrack_l in the same
3355 // critical section
3356 track->copyMetadataTo(backInserter);
3357 }
3358 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3359 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3360 metadata.tracks.insert(metadata.tracks.end(),
3361 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3362 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3363 chain->sendMetadata_l(sessionTrackMetadata, {});
3364 }
3365 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3366 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3367 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3368 }
3369 }
3370 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3371 chain->sendMetadata_l(metadata.tracks, {});
3372 }
3373 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3374 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3375 }
3376 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3377 chain->sendMetadata_l(metadata.tracks, {});
3378 }
3379 } else {
3380 auto backInserter = std::back_inserter(metadata.tracks);
3381 for (const sp<IAfTrack>& track : mActiveTracks) {
3382 // No track is invalid as this is called after prepareTrack_l in the same
3383 // critical section
3384 track->copyMetadataTo(backInserter);
3385 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003386 }
Kevin Rocard12381092018-04-11 09:19:59 -07003387 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003388 MetadataUpdate change;
3389 change.playbackMetadataUpdate = metadata.tracks;
3390 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003391}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003392
Andy Hung4b17e882023-07-07 13:47:37 -07003393void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003394 const StreamOutHalInterface::SourceMetadata& metadata)
3395{
3396 mOutput->stream->updateSourceMetadata(metadata);
3397};
3398
Andy Hung4b17e882023-07-07 13:47:37 -07003399status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003400 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003401{
3402 if (halFrames == NULL || dspFrames == NULL) {
3403 return BAD_VALUE;
3404 }
Andy Hungf8635b62023-08-31 16:13:39 -07003405 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003406 if (initCheck() != NO_ERROR) {
3407 return INVALID_OPERATION;
3408 }
Andy Hung818e7a32016-02-16 18:08:07 -08003409 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003410 *halFrames = framesWritten;
3411
3412 if (isSuspended()) {
3413 // return an estimation of rendered frames when the output is suspended
3414 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003415 *dspFrames = (uint32_t)
3416 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003417 return NO_ERROR;
3418 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003419 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003420 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003421 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003422 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003423 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003424 }
3425}
3426
Andy Hung4b17e882023-07-07 13:47:37 -07003427product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003428{
3429 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3430 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3431 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003432 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003433 }
3434 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003435 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003436 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003437 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003438 }
3439 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003440 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003441}
3442
3443
Andy Hung4b17e882023-07-07 13:47:37 -07003444AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003445{
Andy Hungf8635b62023-08-31 16:13:39 -07003446 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003447 return mOutput;
3448}
3449
Andy Hung4b17e882023-07-07 13:47:37 -07003450AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003451{
Andy Hungf8635b62023-08-31 16:13:39 -07003452 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003453 AudioStreamOut *output = mOutput;
3454 mOutput = NULL;
3455 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3456 // must push a NULL and wait for ack
3457 mOutputSink.clear();
3458 mPipeSink.clear();
3459 mNormalSink.clear();
3460 return output;
3461}
3462
Andy Hungb17d24b2023-08-29 14:26:09 -07003463// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003464sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003465{
3466 if (mOutput == NULL) {
3467 return NULL;
3468 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003469 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003470}
3471
Andy Hung4b17e882023-07-07 13:47:37 -07003472uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003473{
3474 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3475}
3476
Andy Hung4b17e882023-07-07 13:47:37 -07003477status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003478{
3479 if (!isValidSyncEvent(event)) {
3480 return BAD_VALUE;
3481 }
3482
Andy Hungf8635b62023-08-31 16:13:39 -07003483 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003484
3485 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003486 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003487 if (event->triggerSession() == track->sessionId()) {
3488 (void) track->setSyncEvent(event);
3489 return NO_ERROR;
3490 }
3491 }
3492
3493 return NAME_NOT_FOUND;
3494}
3495
Andy Hung4b17e882023-07-07 13:47:37 -07003496bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003497{
3498 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3499}
3500
Andy Hung4b17e882023-07-07 13:47:37 -07003501void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003502 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003503{
Andy Hungfe726a62018-09-27 15:17:25 -07003504 // Miscellaneous track cleanup when removed from the active list,
3505 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003506#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003507 for (const auto& track : tracksToRemove) {
3508 if (track->isExternalTrack()) {
3509 // to track the speaker usage
3510 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003511 }
3512 }
Andy Hungfe726a62018-09-27 15:17:25 -07003513#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003514}
3515
Andy Hung4b17e882023-07-07 13:47:37 -07003516void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003517{
3518 if (!mMasterMute) {
3519 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003520 if (mOutDeviceTypeAddrs.empty()) {
3521 ALOGD("ro.audio.silent is ignored since no output device is set");
3522 return;
3523 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003524 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003525 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3526 return;
3527 }
Eric Laurent81784c32012-11-19 14:55:58 -08003528 if (property_get("ro.audio.silent", value, "0") > 0) {
3529 char *endptr;
3530 unsigned long ul = strtoul(value, &endptr, 0);
3531 if (*endptr == '\0' && ul != 0) {
3532 ALOGD("Silence is golden");
3533 // The setprop command will not allow a property to be changed after
3534 // the first time it is set, so we don't have to worry about un-muting.
3535 setMasterMute_l(true);
3536 }
3537 }
3538 }
3539}
3540
3541// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003542ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003543{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003544 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003545 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003546 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003547 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003548
3549 // If an NBAIO sink is present, use it to write the normal mixer's submix
3550 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003551
Andy Hung010a1a12014-03-13 13:57:33 -07003552 const size_t count = mBytesRemaining / mFrameSize;
3553
Simon Wilson2d590962012-11-29 15:18:50 -08003554 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003555 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003556 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003557 if (screenState != mScreenState) {
3558 mScreenState = screenState;
3559 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3560 if (pipe != NULL) {
3561 pipe->setAvgFrames((mScreenState & 1) ?
3562 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3563 }
3564 }
Andy Hung010a1a12014-03-13 13:57:33 -07003565 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003566 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003567
Eric Laurent81784c32012-11-19 14:55:58 -08003568 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003569 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003570
Andy Hung8946a282018-04-19 20:04:56 -07003571#ifdef TEE_SINK
3572 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3573#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003574 } else {
3575 bytesWritten = framesWritten;
3576 }
3577 // otherwise use the HAL / AudioStreamOut directly
3578 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003579 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003580
Eric Laurentbfb1b832013-01-07 09:53:42 -08003581 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003582 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3583 mWriteAckSequence += 2;
3584 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003585 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003586 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003588 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003589 // FIXME We should have an implementation of timestamps for direct output threads.
3590 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003591 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003592 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003593
Eric Laurentbfb1b832013-01-07 09:53:42 -08003594 if (mUseAsyncWrite &&
3595 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3596 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003597 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003598 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003599 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003600 }
Eric Laurent81784c32012-11-19 14:55:58 -08003601 }
3602
Eric Laurent81784c32012-11-19 14:55:58 -08003603 mNumWrites++;
3604 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003605 if (mStandby) {
3606 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003607 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003608 mStandby = false;
3609 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003610 return bytesWritten;
3611}
3612
Andy Hungb17d24b2023-08-29 14:26:09 -07003613// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003614void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003615 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003616{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003617 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003618 if (outputSink != nullptr) {
3619 outputSink->startMelComputation(processor);
3620 }
Vlad Popab042ee62022-10-20 18:05:00 +02003621}
3622
Andy Hungb17d24b2023-08-29 14:26:09 -07003623// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003624void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003625{
3626 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003627 if (outputSink != nullptr) {
3628 outputSink->stopMelComputation();
3629 }
Vlad Popab042ee62022-10-20 18:05:00 +02003630}
3631
Andy Hung4b17e882023-07-07 13:47:37 -07003632void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003633{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003634 bool supportsDrain = false;
3635 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003636 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3637 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003638 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3639 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003640 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003641 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003642 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003643 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003644 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003645 }
3646}
3647
Andy Hung4b17e882023-07-07 13:47:37 -07003648void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649{
Eric Laurent275e8e92014-11-30 15:14:47 -08003650 {
Andy Hungf8635b62023-08-31 16:13:39 -07003651 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003652 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003653 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003654 track->invalidate();
3655 }
Andy Hungdae27702016-10-31 14:01:16 -07003656 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3657 // After we exit there are no more track changes sent to BatteryNotifier
3658 // because that requires an active threadLoop.
3659 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3660 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003661 }
Eric Laurent81784c32012-11-19 14:55:58 -08003662}
3663
3664/*
3665The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003666 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003667 - mActiveSleepTimeUs from activeSleepTimeUs()
3668 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003669 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3670 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003671 - maxPeriod from frame count and sample rate (MIXER only)
3672
3673The parameters that affect these derived values are:
3674 - frame count
3675 - frame size
3676 - sample rate
3677 - device type: A2DP or not
3678 - device latency
3679 - format: PCM or not
3680 - active sleep time
3681 - idle sleep time
3682*/
3683
Andy Hung4b17e882023-07-07 13:47:37 -07003684void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003685{
Andy Hung25c2dac2014-02-27 14:56:00 -08003686 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003687 mActiveSleepTimeUs = activeSleepTimeUs();
3688 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003689
Andy Hungd58c4732023-07-20 21:31:38 -07003690 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003691
Eric Laurent42537be2016-01-08 17:16:42 -08003692 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3693 // truncating audio when going to standby.
Andy Hung94dfbb42023-09-06 19:41:47 -07003694 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003695 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3696 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3697 }
3698 }
Eric Laurent81784c32012-11-19 14:55:58 -08003699}
3700
Andy Hung4b17e882023-07-07 13:47:37 -07003701bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003702{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003703 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003704 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003705 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003706 size_t size = mTracks.size();
3707 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003708 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003709 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003710 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003711 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003712 }
3713 }
Eric Laurent13084622016-05-17 10:51:49 -07003714 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003715}
3716
Andy Hung4b17e882023-07-07 13:47:37 -07003717void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003718{
Andy Hungf8635b62023-08-31 16:13:39 -07003719 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003720 invalidateTracks_l(streamType);
3721}
3722
Andy Hung4b17e882023-07-07 13:47:37 -07003723void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07003724 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003725 invalidateTracks_l(portIds);
3726}
3727
Andy Hung4b17e882023-07-07 13:47:37 -07003728bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003729 bool trackMatch = false;
3730 const size_t size = mTracks.size();
3731 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003732 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003733 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3734 t->invalidate();
3735 portIds.erase(t->portId());
3736 trackMatch = true;
3737 }
3738 if (portIds.empty()) {
3739 break;
3740 }
3741 }
3742 return trackMatch;
3743}
3744
jiabinf042b9b2021-05-07 23:46:28 +00003745// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003746IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003747 audio_port_handle_t trackPortId) {
3748 for (size_t i = 0; i < mTracks.size(); i++) {
3749 if (mTracks[i]->portId() == trackPortId) {
3750 return mTracks[i].get();
3751 }
3752 }
3753 return nullptr;
3754}
3755
Andy Hung4b17e882023-07-07 13:47:37 -07003756status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003757{
Glenn Kastend848eb42016-03-08 13:42:11 -08003758 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003759 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003760 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003761
Andy Hungd3639922022-04-28 18:00:49 -07003762 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003763 if (!audio_is_global_session(session)) {
3764 // player sessions on a spatializer output will use a dedicated input buffer and
3765 // will either output multi channel to mEffectBuffer if the track is spatilaized
3766 // or stereo to mPostSpatializerBuffer if not spatialized.
3767 uint32_t channelMask;
3768 bool isSessionSpatialized =
3769 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3770 if (isSessionSpatialized) {
3771 channelMask = mMixerChannelMask;
3772 } else {
3773 channelMask = mChannelMask;
3774 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003775 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003776 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003777 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003778 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003779 &halInBuffer);
3780 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003781
Andy Hung7535ed92023-07-17 17:05:00 -07003782 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003783 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3784 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3785 &halOutBuffer);
3786 if (result != OK) return result;
3787
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003788 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003789
Mikhail Naganov022b9952017-01-04 16:36:51 -08003790 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3791 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003792 } else {
3793 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3794 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3795 // mPostSpatializerBuffer as output buffer
3796 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003797 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003798 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3799 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003800 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003801 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3802 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003803
Eric Laurentb62d0362021-10-26 17:40:18 +02003804 if (session == AUDIO_SESSION_DEVICE) {
3805 halInBuffer = halOutBuffer;
3806 }
3807 }
3808 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003809 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003810 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3811 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3812 &halInBuffer);
3813 if (result != OK) return result;
3814 halOutBuffer = halInBuffer;
3815 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3816 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003817 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003818 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003819 // Only one effect chain can be present in direct output thread and it uses
3820 // the sink buffer as input
3821 if (mType != DIRECT) {
3822 size_t numSamples = mNormalFrameCount
3823 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3824 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003825 const status_t allocateStatus =
3826 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003827 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003828 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003829 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003830
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003831 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003832 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3833 buffer, session);
3834 }
3835 }
3836 }
3837
3838 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003839 // Attach all tracks with same session ID to this chain.
3840 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003841 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003842 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003843 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3844 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003845 track->setMainBuffer(buffer);
3846 chain->incTrackCnt();
3847 }
3848 }
3849
3850 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003851 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003852 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003853 ALOGV("addEffectChain_l() activating track %p on session %d",
3854 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003855 chain->incActiveTrackCnt();
3856 }
3857 }
3858 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003859
Eric Laurentaaa44472014-09-12 17:41:50 -07003860 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003861 chain->setInBuffer(halInBuffer);
3862 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003863 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3864 // chains list in order to be processed last as it contains output device effects.
3865 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3866 // processing effects specific to an output stream before effects applied to all streams
3867 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003868 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3869 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003870 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003871 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003872 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003873 // Effect chain for other sessions are inserted at beginning of effect
3874 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003875 // sessions is not important.
3876 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003877 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3878 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003879 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003880 size_t size = mEffectChains.size();
3881 size_t i = 0;
3882 for (i = 0; i < size; i++) {
3883 if (mEffectChains[i]->sessionId() < session) {
3884 break;
3885 }
3886 }
3887 mEffectChains.insertAt(chain, i);
3888 checkSuspendOnAddEffectChain_l(chain);
3889
3890 return NO_ERROR;
3891}
3892
Andy Hung4b17e882023-07-07 13:47:37 -07003893size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003894{
Glenn Kastend848eb42016-03-08 13:42:11 -08003895 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003896
3897 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3898
3899 for (size_t i = 0; i < mEffectChains.size(); i++) {
3900 if (chain == mEffectChains[i]) {
3901 mEffectChains.removeAt(i);
3902 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003903 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003904 if (session == track->sessionId()) {
3905 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3906 chain.get(), session);
3907 chain->decActiveTrackCnt();
3908 }
3909 }
3910
3911 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003912 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003913 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003914 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003915 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003916 chain->decTrackCnt();
3917 }
3918 }
3919 break;
3920 }
3921 }
3922 return mEffectChains.size();
3923}
3924
Andy Hung4b17e882023-07-07 13:47:37 -07003925status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003926 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003927{
Andy Hungf8635b62023-08-31 16:13:39 -07003928 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003929 return attachAuxEffect_l(track, EffectId);
3930}
3931
Andy Hung4b17e882023-07-07 13:47:37 -07003932status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003933 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003934{
3935 status_t status = NO_ERROR;
3936
3937 if (EffectId == 0) {
3938 track->setAuxBuffer(0, NULL);
3939 } else {
3940 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003941 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003942 if (effect != 0) {
3943 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3944 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3945 } else {
3946 status = INVALID_OPERATION;
3947 }
3948 } else {
3949 status = BAD_VALUE;
3950 }
3951 }
3952 return status;
3953}
3954
Andy Hung4b17e882023-07-07 13:47:37 -07003955void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003956{
3957 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003958 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003959 if (track->auxEffectId() == effectId) {
3960 attachAuxEffect_l(track, 0);
3961 }
3962 }
3963}
3964
Andy Hung4b17e882023-07-07 13:47:37 -07003965bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003966NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003967{
Andy Hung78d8d952023-05-30 18:10:23 -07003968 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003969
Andy Hung45a38f22023-10-03 10:49:34 -07003970 if (mType == SPATIALIZER) {
3971 const pid_t tid = getTid();
3972 if (tid == -1) { // odd: we are here, we must be a running thread.
3973 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3974 } else {
3975 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3976 if (priorityBoost > 0) {
3977 stream()->setHalThreadPriority(priorityBoost);
3978 }
3979 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003980 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3981 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3982 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3983 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3984 // only on ARC.
3985 const pid_t tid = getTid();
3986 if (tid == -1) {
3987 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
3988 } else {
3989 const status_t status = requestPriority(getpid(),
3990 tid,
3991 kPriorityPlaybackThreadArc,
3992 false /* isForApp */,
3993 true /* asynchronous */);
3994 if (status != OK) {
3995 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
3996 status);
3997 } else {
3998 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
3999 }
4000 }
Andy Hung45a38f22023-10-03 10:49:34 -07004001 }
4002
Andy Hung11e74242023-06-26 19:20:57 -07004003 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004004
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004005 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004006 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004007
4008 // MIXER
4009 nsecs_t lastWarning = 0;
4010
4011 // DUPLICATING
4012 // FIXME could this be made local to while loop?
4013 writeFrames = 0;
4014
4015 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004016 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004017
Andy Hungd3639922022-04-28 18:00:49 -07004018 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004019 sleepTimeShift = 0;
4020 }
4021
4022 CpuStats cpuStats;
4023 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4024
4025 acquireWakeLock();
4026
Glenn Kasteneef598c2017-04-03 14:41:13 -07004027 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4028 // thread associated with this PlaybackThread.
4029 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4030 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004031 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4032 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004033 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004034 const char *logString = NULL;
4035
rago1bb90822017-05-02 18:31:48 -07004036 // Estimated time for next buffer to be written to hal. This is used only on
4037 // suspended mode (for now) to help schedule the wait time until next iteration.
4038 nsecs_t timeLoopNextNs = 0;
4039
Eric Laurent664539d2013-09-23 18:24:31 -07004040 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004041
Andy Hung2dbffc22018-08-08 18:50:41 -07004042 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004043
Eric Laurentb3f315a2021-07-13 15:09:05 +02004044 sendCheckOutputStageEffectsEvent();
4045
Andy Hung446f4df2019-02-21 12:26:41 -08004046 // loopCount is used for statistics and diagnostics.
4047 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004048 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004049 // Log merge requests are performed during AudioFlinger binder transactions, but
4050 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07004051 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004052
Eric Laurent81784c32012-11-19 14:55:58 -08004053 cpuStats.sample(myName);
4054
Andy Hung116bc262023-06-20 18:56:17 -07004055 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004056 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004057 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07004058 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004059
Andy Hung2dbffc22018-08-08 18:50:41 -07004060 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4061 //
Andy Hungb17d24b2023-08-29 14:26:09 -07004062 // Note: we access outDeviceTypes() outside of mutex().
Andy Hung94dfbb42023-09-06 19:41:47 -07004063 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004064 // Here, we try for the AF lock, but do not block on it as the latency
4065 // is more informational.
Andy Hung85a07452023-08-28 18:36:53 -07004066 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd25fe392023-07-13 16:52:46 -07004067 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004068 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004069 status_t status = INVALID_OPERATION;
4070 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07004071 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07004072 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004073 && swPatches.size() > 0) {
4074 status = swPatches[0].getLatencyMs_l(&latencyMs);
4075 downstreamPatchHandle = swPatches[0].getPatchHandle();
4076 }
4077 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004078 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004079 lastDownstreamPatchHandle = downstreamPatchHandle;
4080 }
4081 if (status == OK) {
4082 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004083 // latency of 5 seconds).
4084 const double minLatency = 0., maxLatency = 5000.;
4085 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004086 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004087 } else {
4088 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004089 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004090 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004091 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004092 }
Andy Hung7535ed92023-07-17 17:05:00 -07004093 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004094 }
4095 } else {
4096 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4097 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004098 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004099 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4100 }
4101 }
4102
Eric Laurentb3f315a2021-07-13 15:09:05 +02004103 if (mCheckOutputStageEffects.exchange(false)) {
4104 checkOutputStageEffects();
4105 }
4106
Vlad Popa7e81cea2023-01-19 16:34:16 +01004107 MetadataUpdate metadataUpdate;
Andy Hungb17d24b2023-08-29 14:26:09 -07004108 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004109
Andy Hungb17d24b2023-08-29 14:26:09 -07004110 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004111
Eric Laurent021cf962014-05-13 10:18:14 -07004112 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004113 if (mCheckOutputStageEffects.load()) {
4114 continue;
4115 }
Eric Laurent10351942014-05-08 18:49:52 -07004116
Andy Hungb17d24b2023-08-29 14:26:09 -07004117 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004118 if (logString != NULL) {
4119 mNBLogWriter->logTimestamp();
4120 mNBLogWriter->log(logString);
4121 logString = NULL;
4122 }
4123
Dean Wheatley12473e92021-03-18 23:00:55 +11004124 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004125
Eric Laurent81784c32012-11-19 14:55:58 -08004126 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004127 if (mSignalPending) {
4128 // A signal was raised while we were unlocked
4129 mSignalPending = false;
4130 } else if (waitingAsyncCallback_l()) {
4131 if (exitPending()) {
4132 break;
4133 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004134 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004135 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004136 releaseWakeLock_l();
4137 released = true;
4138 }
Andy Hung10cbff12017-02-21 17:30:14 -08004139
4140 const int64_t waitNs = computeWaitTimeNs_l();
4141 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungb17d24b2023-08-29 14:26:09 -07004142 std::cv_status cvstatus =
4143 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4144 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004145 mSignalPending = true; // if timeout recheck everything
4146 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004147 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004148 if (released) {
4149 acquireWakeLock_l();
4150 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004151 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4152 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004153
4154 continue;
4155 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004156 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004157 isSuspended()) {
4158 // put audio hardware into standby after short delay
4159 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004160
4161 threadLoop_standby();
4162
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004163 // This is where we go into standby
4164 if (!mStandby) {
4165 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004166 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004167 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004168 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004169 }
Andy Hungd0979812019-02-21 15:51:44 -08004170 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004171 }
4172
Eric Tan39ec8d62018-07-24 09:49:29 -07004173 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004174 // we're about to wait, flush the binder command buffer
4175 IPCThreadState::self()->flushCommands();
4176
4177 clearOutputTracks();
4178
4179 if (exitPending()) {
4180 break;
4181 }
4182
4183 releaseWakeLock_l();
4184 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004185 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -07004186 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004187 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004188 acquireWakeLock_l();
4189
4190 mMixerStatus = MIXER_IDLE;
4191 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4192 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004194 checkSilentMode_l();
4195
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004196 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4197 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004198 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004199 sleepTimeShift = 0;
4200 }
4201
4202 continue;
4203 }
4204 }
Eric Laurent81784c32012-11-19 14:55:58 -08004205 // mMixerStatusIgnoringFastTracks is also updated internally
4206 mMixerStatus = prepareTracks_l(&tracksToRemove);
4207
Andy Hung94dfbb42023-09-06 19:41:47 -07004208 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004209
Vlad Popa7e81cea2023-01-19 16:34:16 +01004210 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004211
Andy Hungf302e812024-01-26 11:55:15 -08004212 // Acquire a local copy of active tracks with lock (release w/o lock).
4213 //
4214 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4215 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4216 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4217 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4218
4219 setHalLatencyMode_l();
4220
4221 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4222 // so this is done before we lock our effect chains.
4223 for (const auto& track : mActiveTracks) {
4224 track->updateTeePatches_l();
4225 }
4226
4227 // signal actual start of output stream when the render position reported by
4228 // the kernel starts moving.
4229 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4230 && (mKernelPositionOnStandby
4231 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4232 mHalStarted = true;
4233 mWaitHalStartCV.notify_all();
4234 }
4235
Eric Laurent81784c32012-11-19 14:55:58 -08004236 // prevent any changes in effect chain list and in each effect chain
4237 // during mixing and effect process as the audio buffers could be deleted
4238 // or modified if an effect is created or deleted
4239 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004240
4241 // Determine which session to pick up haptic data.
4242 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004243 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004244 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004245 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004246 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004247 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004248 if (effectChain != nullptr
4249 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004250 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004251 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004252 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004253 break;
4254 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004255 if (activeHapticSessionId == AUDIO_SESSION_NONE
4256 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004257 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004258 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004259 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004260 }
4261 }
4262 }
Andy Hungb17d24b2023-08-29 14:26:09 -07004263 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004264
Eric Laurentbfb1b832013-01-07 09:53:42 -08004265 if (mBytesRemaining == 0) {
4266 mCurrentWriteLength = 0;
4267 if (mMixerStatus == MIXER_TRACKS_READY) {
4268 // threadLoop_mix() sets mCurrentWriteLength
4269 threadLoop_mix();
4270 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4271 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004272 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273 // must be written to HAL
4274 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004275 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004276 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004277
4278 // Tally underrun frames as we are inserting 0s here.
4279 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004280 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004281 && !track->isStopped()
4282 && !track->isPaused()
4283 && !track->isTerminated()) {
4284 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4285 __func__, track->id(), track->getTrackStateAsString(),
4286 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004287 track->audioTrackServerProxy()->tallyUnderrunFrames(
4288 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004289 }
4290 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004291 }
4292 }
Andy Hung98ef9782014-03-04 14:46:50 -08004293 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004294 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004295 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004296 // or mSinkBuffer (if there are no effects and there is no data already copied to
4297 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004298 //
4299 // This is done pre-effects computation; if effects change to
4300 // support higher precision, this needs to move.
4301 //
4302 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004303 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004304 uint32_t mixerChannelCount = mEffectBufferValid ?
4305 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004306 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004307 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4308 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4309
David Li88ee0902022-06-22 10:01:21 +08004310 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4311 // do these processes after effects are applied.
4312 if (!mEffectBufferValid) {
4313 // mono blend occurs for mixer threads only (not direct or offloaded)
4314 // and is handled here if we're going directly to the sink.
4315 if (requireMonoBlend()) {
4316 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4317 mNormalFrameCount, true /*limit*/);
4318 }
Andy Hung2ddee192015-12-18 17:34:44 -08004319
David Li88ee0902022-06-22 10:01:21 +08004320 if (!hasFastMixer()) {
4321 // Balance must take effect after mono conversion.
4322 // We do it here if there is no FastMixer.
4323 // mBalance detects zero balance within the class for speed
4324 // (not needed here).
4325 mBalance.setBalance(mMasterBalance.load());
4326 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4327 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004328 }
4329
Andy Hung98ef9782014-03-04 14:46:50 -08004330 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004331 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004332
4333 // If we're going directly to the sink and there are haptic channels,
4334 // we should adjust channels as the sample data is partially interleaved
4335 // in this case.
4336 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4337 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4338 mChannelCount + mHapticChannelCount,
4339 audio_bytes_per_sample(format),
4340 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4341 }
Andy Hung98ef9782014-03-04 14:46:50 -08004342 }
4343
Eric Laurentbfb1b832013-01-07 09:53:42 -08004344 mBytesRemaining = mCurrentWriteLength;
4345 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004346 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4347 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4348 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4349 mBytesWritten += mBytesRemaining;
4350 mFramesWritten += framesRemaining;
4351 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004352 mBytesRemaining = 0;
4353 }
Eric Laurent81784c32012-11-19 14:55:58 -08004354
Eric Laurentbfb1b832013-01-07 09:53:42 -08004355 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004356 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004357 for (size_t i = 0; i < effectChains.size(); i ++) {
4358 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004359 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004360 if (activeHapticSessionId != AUDIO_SESSION_NONE
4361 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004362 // Haptic data is active in this case, copy it directly from
4363 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004364 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4365 audio_channel_count_from_out_mask(mMixerChannelMask) :
4366 mChannelCount;
4367 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4368 hapticSessionChannelCount = mChannelCount;
4369 }
4370
jiabin47affe52019-04-04 18:02:07 -07004371 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004372 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004373 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004374 memcpy_by_audio_format(
4375 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004376 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004377 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004378 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004379 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004380 }
Eric Laurent81784c32012-11-19 14:55:58 -08004381 }
4382 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004383 // Process effect chains for offloaded thread even if no audio
4384 // was read from audio track: process only updates effect state
4385 // and thus does have to be synchronized with audio writes but may have
4386 // to be called while waiting for async write callback
4387 if (mType == OFFLOAD) {
4388 for (size_t i = 0; i < effectChains.size(); i ++) {
4389 effectChains[i]->process_l();
4390 }
4391 }
Eric Laurent81784c32012-11-19 14:55:58 -08004392
Andy Hung98ef9782014-03-04 14:46:50 -08004393 // Only if the Effects buffer is enabled and there is data in the
4394 // Effects buffer (buffer valid), we need to
4395 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004396 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004397 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004398 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004399 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004400 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004401 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004402 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004403 }
4404
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004405 if (!hasFastMixer()) {
4406 // Balance must take effect after mono conversion.
4407 // We do it here if there is no FastMixer.
4408 // mBalance detects zero balance within the class for speed (not needed here).
4409 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004410 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004411 }
4412
Eric Laurentb62d0362021-10-26 17:40:18 +02004413 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4414 // mPostSpatializerBuffer if the haptics track is spatialized.
4415 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4416 // For other thread types, the haptics channels are already in mEffectBuffer.
4417 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4418 const size_t srcBufferSize = mNormalFrameCount *
4419 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4420 mEffectBufferFormat);
4421 const size_t dstBufferSize = mNormalFrameCount
4422 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4423
4424 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4425 mEffectBufferFormat,
4426 (uint8_t*)mEffectBuffer + srcBufferSize,
4427 mEffectBufferFormat,
4428 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004429 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004430 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4431 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4432 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4433 // Clamp PCM float values more than this distance from 0 to insulate
4434 // a HAL which doesn't handle NaN correctly.
4435 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4436 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4437 static_cast<const float*>(effectBuffer),
4438 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4439 } else {
4440 memcpy_by_audio_format(mSinkBuffer, mFormat,
4441 effectBuffer, mEffectBufferFormat, framesToCopy);
4442 }
jiabin245cdd92018-12-07 17:55:15 -08004443 // The sample data is partially interleaved when haptic channels exist,
4444 // we need to adjust channels here.
4445 if (mHapticChannelCount > 0) {
4446 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4447 mChannelCount + mHapticChannelCount,
4448 audio_bytes_per_sample(mFormat),
4449 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4450 }
Andy Hung98ef9782014-03-04 14:46:50 -08004451 }
4452
Eric Laurent81784c32012-11-19 14:55:58 -08004453 // enable changes in effect chain
4454 unlockEffectChains(effectChains);
4455
Vlad Popafce10862023-02-03 10:37:07 +01004456 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004457 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004458 metadataUpdate.playbackMetadataUpdate);
4459 }
4460
Eric Laurentbfb1b832013-01-07 09:53:42 -08004461 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004462 // mSleepTimeUs == 0 means we must write to audio hardware
4463 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004464 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004465 // writePeriodNs is updated >= 0 when ret > 0.
4466 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004467 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004468 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004469 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004470 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004471 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004472 if (ret < 0) {
4473 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004474 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004475 mBytesWritten += ret;
4476 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004477 const int64_t frames = ret / mFrameSize;
4478 mFramesWritten += frames;
4479
4480 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4481 // process information relating to write time.
4482 if (audio_has_proportional_frames(mFormat)) {
4483 // we are in a continuous mixing cycle
4484 if (mMixerStatus == MIXER_TRACKS_READY &&
4485 loopCount == lastLoopCountWritten + 1) {
4486
4487 const double jitterMs =
4488 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4489 {frames, writePeriodNs},
4490 {0, 0} /* lastTimestamp */, mSampleRate);
4491 const double processMs =
4492 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4493
Andy Hungf8635b62023-08-31 16:13:39 -07004494 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004495 mIoJitterMs.add(jitterMs);
4496 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004497
4498 if (mPipeSink.get() != nullptr) {
4499 // Using the Monopipe availableToWrite, we estimate the current
4500 // buffer size.
4501 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4502 const ssize_t
4503 availableToWrite = mPipeSink->availableToWrite();
4504 const size_t pipeFrames = monoPipe->maxFrames();
4505 const size_t
4506 remainingFrames = pipeFrames - max(availableToWrite, 0);
4507 mMonopipePipeDepthStats.add(remainingFrames);
4508 }
Andy Hung446f4df2019-02-21 12:26:41 -08004509 }
4510
4511 // write blocked detection
4512 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004513 if ((mType == MIXER || mType == SPATIALIZER)
4514 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004515 mNumDelayedWrites++;
4516 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4517 ATRACE_NAME("underrun");
4518 ALOGW("write blocked for %lld msecs, "
4519 "%d delayed writes, thread %d",
4520 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4521 mNumDelayedWrites, mId);
4522 lastWarning = lastIoEndNs;
4523 }
4524 }
4525 }
4526 // update timing info.
4527 mLastIoBeginNs = lastIoBeginNs;
4528 mLastIoEndNs = lastIoEndNs;
4529 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004530 }
4531 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4532 (mMixerStatus == MIXER_DRAIN_ALL)) {
4533 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004534 }
Andy Hungd3639922022-04-28 18:00:49 -07004535 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004536
4537 if (mThreadThrottle
4538 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004539 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004540 // Limit MixerThread data processing to no more than twice the
4541 // expected processing rate.
4542 //
4543 // This helps prevent underruns with NuPlayer and other applications
4544 // which may set up buffers that are close to the minimum size, or use
4545 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4546 //
4547 // The throttle smooths out sudden large data drains from the device,
4548 // e.g. when it comes out of standby, which often causes problems with
4549 // (1) mixer threads without a fast mixer (which has its own warm-up)
4550 // (2) minimum buffer sized tracks (even if the track is full,
4551 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004552 //
4553 // Total time spent in last processing cycle equals time spent in
4554 // 1. threadLoop_write, as well as time spent in
4555 // 2. threadLoop_mix (significant for heavy mixing, especially
4556 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004557
Andy Hung446f4df2019-02-21 12:26:41 -08004558 // it's OK if deltaMs is an overestimate.
4559
4560 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004561
Ivan Lozanoea04d392017-11-07 14:37:07 -08004562 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004563 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004564 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004565
Andy Hung08fb1742015-05-31 23:22:10 -07004566 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004567 // notify of throttle start on verbose log
4568 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4569 "mixer(%p) throttle begin:"
4570 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004571 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004572 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004573 // Throttle must be attributed to the previous mixer loop's write time
4574 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004575 // This also ensures proper timing statistics.
4576 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004577 } else {
4578 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4579 if (diff > 0) {
4580 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004581 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004582 ALOGD_IF(!isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004583 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004584 !isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004585 outDeviceTypes_l(),
4586 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004587 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004588 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4589 }
Andy Hung08fb1742015-05-31 23:22:10 -07004590 }
4591 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004592 }
Eric Laurent81784c32012-11-19 14:55:58 -08004593
Eric Laurentbfb1b832013-01-07 09:53:42 -08004594 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004595 ATRACE_BEGIN("sleep");
Andy Hungb17d24b2023-08-29 14:26:09 -07004596 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004597 // suspended requires accurate metering of sleep time.
4598 if (isSuspended()) {
4599 // advance by expected sleepTime
4600 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4601 const nsecs_t nowNs = systemTime();
4602
4603 // compute expected next time vs current time.
4604 // (negative deltas are treated as delays).
4605 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4606 if (deltaNs < -kMaxNextBufferDelayNs) {
4607 // Delays longer than the max allowed trigger a reset.
4608 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4609 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4610 timeLoopNextNs = nowNs + deltaNs;
4611 } else if (deltaNs < 0) {
4612 // Delays within the max delay allowed: zero the delta/sleepTime
4613 // to help the system catch up in the next iteration(s)
4614 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4615 deltaNs = 0;
4616 }
4617 // update sleep time (which is >= 0)
4618 mSleepTimeUs = deltaNs / 1000;
4619 }
Eric Laurente93cc032016-05-05 10:15:10 -07004620 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004621 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004622 }
Glenn Kastene7754022014-10-31 12:11:26 -07004623 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004624 }
Eric Laurent81784c32012-11-19 14:55:58 -08004625 }
4626
4627 // Finally let go of removed track(s), without the lock held
4628 // since we can't guarantee the destructors won't acquire that
4629 // same lock. This will also mutate and push a new fast mixer state.
4630 threadLoop_removeTracks(tracksToRemove);
4631 tracksToRemove.clear();
4632
4633 // FIXME I don't understand the need for this here;
4634 // it was in the original code but maybe the
4635 // assignment in saveOutputTracks() makes this unnecessary?
4636 clearOutputTracks();
4637
4638 // Effect chains will be actually deleted here if they were removed from
4639 // mEffectChains list during mixing or effects processing
4640 effectChains.clear();
4641
4642 // FIXME Note that the above .clear() is no longer necessary since effectChains
4643 // is now local to this block, but will keep it for now (at least until merge done).
4644 }
4645
Eric Laurentbfb1b832013-01-07 09:53:42 -08004646 threadLoop_exit();
4647
Eric Laurentcf817a22014-08-04 20:36:31 -07004648 if (!mStandby) {
4649 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004650 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004651 }
4652
4653 releaseWakeLock();
4654
4655 ALOGV("Thread %p type %d exiting", this, mType);
4656 return false;
4657}
4658
Andy Hung4b17e882023-07-07 13:47:37 -07004659void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004660{
Dean Wheatley12473e92021-03-18 23:00:55 +11004661 if (mStandby) {
4662 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4663 return;
4664 } else if (mHwPaused) {
4665 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4666 return;
4667 }
4668
4669 // Gather the framesReleased counters for all active tracks,
4670 // and associate with the sink frames written out. We need
4671 // this to convert the sink timestamp to the track timestamp.
4672 bool kernelLocationUpdate = false;
4673 ExtendedTimestamp timestamp; // use private copy to fetch
4674
4675 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4676 // HAL may be draining some small duration buffered data for fade out.
4677 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4678 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4679 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4680 mSampleRate);
4681
Andy Hung94dfbb42023-09-06 19:41:47 -07004682 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004683 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4684 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4685 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4686 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4687 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4688 = correctedTimestamp.mFrames;
4689 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4690 = correctedTimestamp.mTimeNs;
4691 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4692 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4693 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4694
4695 // Note: Downstream latency only added if timestamp correction enabled.
4696 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4697 const int64_t newPosition =
4698 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4699 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4700 // prevent retrograde
4701 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4702 newPosition,
4703 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4704 - mSuspendedFrames));
4705 }
4706 }
4707
4708 // We always fetch the timestamp here because often the downstream
4709 // sink will block while writing.
4710
4711 // We keep track of the last valid kernel position in case we are in underrun
4712 // and the normal mixer period is the same as the fast mixer period, or there
4713 // is some error from the HAL.
4714 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4715 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4716 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4717 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4718 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4719
4720 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4721 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4722 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4723 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4724 }
4725
4726 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4727 kernelLocationUpdate = true;
4728 } else {
4729 ALOGVV("getTimestamp error - no valid kernel position");
4730 }
4731
4732 // copy over kernel info
4733 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4734 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4735 + mSuspendedFrames; // add frames discarded when suspended
4736 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4737 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4738 } else {
4739 mTimestampVerifier.error();
4740 }
4741
4742 // mFramesWritten for non-offloaded tracks are contiguous
4743 // even after standby() is called. This is useful for the track frame
4744 // to sink frame mapping.
4745 bool serverLocationUpdate = false;
4746 if (mFramesWritten != mLastFramesWritten) {
4747 serverLocationUpdate = true;
4748 mLastFramesWritten = mFramesWritten;
4749 }
4750 // Only update timestamps if there is a meaningful change.
4751 // Either the kernel timestamp must be valid or we have written something.
4752 if (kernelLocationUpdate || serverLocationUpdate) {
4753 if (serverLocationUpdate) {
4754 // use the time before we called the HAL write - it is a bit more accurate
4755 // to when the server last read data than the current time here.
4756 //
4757 // If we haven't written anything, mLastIoBeginNs will be -1
4758 // and we use systemTime().
4759 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4760 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung160664b2023-09-15 18:19:28 -07004761 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004762 }
4763
Andy Hung11e74242023-06-26 19:20:57 -07004764 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004765 if (!t->isFastTrack()) {
4766 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004767 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004768 mFramesWritten,
4769 mSampleRate,
4770 mTimestamp);
4771 }
4772 }
4773 }
4774
4775 if (audio_has_proportional_frames(mFormat)) {
4776 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4777 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4778 mLatencyMs.add(latencyMs);
4779 }
4780 }
4781#if 0
4782 // logFormat example
4783 if (z % 100 == 0) {
4784 timespec ts;
4785 clock_gettime(CLOCK_MONOTONIC, &ts);
4786 LOGT("This is an integer %d, this is a float %f, this is my "
4787 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4788 LOGT("A deceptive null-terminated string %\0");
4789 }
4790 ++z;
4791#endif
4792}
4793
Andy Hungb17d24b2023-08-29 14:26:09 -07004794// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07004795void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungb17d24b2023-08-29 14:26:09 -07004796NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004797{
Andy Hunga7187712023-12-05 17:28:17 -08004798 if (tracksToRemove.empty()) return;
4799
4800 // Block all incoming TrackHandle requests until we are finished with the release.
4801 setThreadBusy_l(true);
4802
Andy Hungfe726a62018-09-27 15:17:25 -07004803 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004804 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004805 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004806 if (chain != 0) {
4807 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4808 __func__, track->id(), chain.get(), track->sessionId());
4809 chain->decActiveTrackCnt();
4810 }
Andy Hunga7187712023-12-05 17:28:17 -08004811
Andy Hungfe726a62018-09-27 15:17:25 -07004812 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hunga7187712023-12-05 17:28:17 -08004813 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004814 if (track->isExternalTrack()) {
Andy Hunga7187712023-12-05 17:28:17 -08004815 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004816 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004818 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819 }
Andy Hunga7187712023-12-05 17:28:17 -08004820 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004821 }
jiabineb3bda02020-06-30 14:07:03 -07004822 if (mHapticChannelCount > 0 &&
4823 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4824 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004825 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004826 // Unlock due to VibratorService will lock for this call and will
4827 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004828 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungb17d24b2023-08-29 14:26:09 -07004829 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004830
4831 // When the track is stop, set the haptic intensity as MUTE
4832 // for the HapticGenerator effect.
4833 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004834 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004835 }
jiabin245cdd92018-12-07 17:55:15 -08004836 }
Andy Hunga7187712023-12-05 17:28:17 -08004837
4838 // Under lock, the track is removed from the active tracks list.
4839 //
4840 // Once the track is no longer active, the TrackHandle may directly
4841 // modify it as the threadLoop() is no longer responsible for its maintenance.
4842 // Do not modify the track from threadLoop after the mutex is unlocked
4843 // if it is not active.
4844 mActiveTracks.remove(track);
4845
4846 if (track->isTerminated()) {
4847 // remove from our tracks vector
4848 removeTrack_l(track);
4849 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004850 }
Andy Hunga7187712023-12-05 17:28:17 -08004851
4852 // Allow incoming TrackHandle requests. We still hold the mutex,
4853 // so pending TrackHandle requests will occur after we unlock it.
4854 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004855}
Eric Laurent81784c32012-11-19 14:55:58 -08004856
Andy Hung4b17e882023-07-07 13:47:37 -07004857status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004858{
4859 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004860 ExtendedTimestamp ets;
4861 status_t status = mNormalSink->getTimestamp(ets);
4862 if (status == NO_ERROR) {
4863 status = ets.getBestTimestamp(&timestamp);
4864 }
4865 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004866 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004867 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004868 collectTimestamps_l();
4869 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4870 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004871 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004872 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4873 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4874 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4875 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4876 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004877 }
4878 return INVALID_OPERATION;
4879}
Eric Laurent1c333e22014-05-20 10:48:17 -07004880
Eric Laurenteab90452019-06-24 15:17:46 -07004881// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4882// still applied by the mixer.
4883// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4884// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4885// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004886status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004887{
4888 status_t result = NO_ERROR;
4889 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4890 if (*volume != mLeftVolFloat) {
4891 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004892 // HAL can return INVALID_OPERATION if operation is not supported.
4893 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004894 "Error when setting output stream volume: %d", result);
4895 if (result == NO_ERROR) {
4896 mLeftVolFloat = *volume;
4897 }
4898 }
4899 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4900 // remove stream volume contribution from software volume.
4901 if (mLeftVolFloat == *volume) {
4902 *volume = 1.0f;
4903 }
4904 }
4905 return result;
4906}
4907
Andy Hung4b17e882023-07-07 13:47:37 -07004908status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004909 audio_patch_handle_t *handle)
4910{
Andy Hungf60abce2016-08-26 11:37:54 -07004911 status_t status;
4912 if (property_get_bool("af.patch_park", false /* default_value */)) {
4913 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4914 // or if HAL does not properly lock against access.
4915 AutoPark<FastMixer> park(mFastMixer);
4916 status = PlaybackThread::createAudioPatch_l(patch, handle);
4917 } else {
4918 status = PlaybackThread::createAudioPatch_l(patch, handle);
4919 }
Eric Laurentb0463942022-12-20 16:31:10 +01004920
4921 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004922 return status;
4923}
4924
Andy Hung4b17e882023-07-07 13:47:37 -07004925status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004926 audio_patch_handle_t *handle)
4927{
4928 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004929
4930 // store new device and send to effects
4931 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004932 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004933 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004934 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4935 && !mOutput->audioHwDev->supportsAudioPatches(),
4936 "Enumerated device type(%#x) must not be used "
4937 "as it does not support audio patches",
4938 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004939 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004940 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4941 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004942 }
4943
François Gaffie0c280aa2018-07-25 10:02:15 +02004944 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004945#ifdef ADD_BATTERY_DATA
4946 // when changing the audio output device, call addBatteryData to notify
4947 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004948 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004949 uint32_t params = 0;
4950 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004951 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004952 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004953 }
4954
Eric Laurent054d9d32015-04-24 08:48:48 -07004955 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004956 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004957 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4958 }
4959
4960 if (params != 0) {
4961 addBatteryData(params);
4962 }
4963 }
4964#endif
4965
4966 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004967 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004968 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004969
jiabinc52b1ff2019-10-31 17:20:42 -07004970 // mPatch.num_sinks is not set when the thread is created so that
4971 // the first patch creation triggers an ioConfigChanged callback
4972 bool configChanged = (mPatch.num_sinks == 0) ||
4973 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004974 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004975 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004976 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004977
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004978 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004979 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4980 status = hwDevice->createAudioPatch(patch->num_sources,
4981 patch->sources,
4982 patch->num_sinks,
4983 patch->sinks,
4984 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004986 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004987 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004988 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004989 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004990
4991 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004992 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004993 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004994 // also dispatch to active AudioTracks for MediaMetrics
4995 for (const auto &track : mActiveTracks) {
4996 track->logEndInterval();
4997 track->logBeginInterval(patchSinksAsString);
4998 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004999
Eric Laurente8726fe2015-06-26 09:39:24 -07005000 if (configChanged) {
5001 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5002 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005003 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005004 mActiveTracks.setHasChanged();
5005
Eric Laurent1c333e22014-05-20 10:48:17 -07005006 return status;
5007}
5008
Andy Hung4b17e882023-07-07 13:47:37 -07005009status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005010{
Andy Hungf60abce2016-08-26 11:37:54 -07005011 status_t status;
5012 if (property_get_bool("af.patch_park", false /* default_value */)) {
5013 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5014 // or if HAL does not properly lock against access.
5015 AutoPark<FastMixer> park(mFastMixer);
5016 status = PlaybackThread::releaseAudioPatch_l(handle);
5017 } else {
5018 status = PlaybackThread::releaseAudioPatch_l(handle);
5019 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005020 return status;
5021}
5022
Andy Hung4b17e882023-07-07 13:47:37 -07005023status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005024{
5025 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005026
jiabinc52b1ff2019-10-31 17:20:42 -07005027 mPatch = audio_patch{};
5028 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005029
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005030 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005031 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5032 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005033 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005034 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005035 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005036 // Force meteadata update after a route change
5037 mActiveTracks.setHasChanged();
5038
Eric Laurent1c333e22014-05-20 10:48:17 -07005039 return status;
5040}
5041
Andy Hung4b17e882023-07-07 13:47:37 -07005042void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005043{
Andy Hungf8635b62023-08-31 16:13:39 -07005044 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005045 mTracks.add(track);
5046}
5047
Andy Hung4b17e882023-07-07 13:47:37 -07005048void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005049{
Andy Hungf8635b62023-08-31 16:13:39 -07005050 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005051 destroyTrack_l(track);
5052}
5053
Andy Hung4b17e882023-07-07 13:47:37 -07005054void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005055{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005056 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005057 config->role = AUDIO_PORT_ROLE_SOURCE;
5058 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5059 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005060 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5061 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5062 config->flags.output = mOutput->flags;
5063 }
Eric Laurent83b88082014-06-20 18:31:16 -07005064}
5065
Eric Laurent81784c32012-11-19 14:55:58 -08005066// ----------------------------------------------------------------------------
5067
Andy Hung4b17e882023-07-07 13:47:37 -07005068/* static */
5069sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07005070 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07005071 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07005072 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07005073}
5074
Andy Hung7535ed92023-07-17 17:05:00 -07005075MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005076 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07005077 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005078 // mAudioMixer below
5079 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005080 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005081 mFastMixerFutex(0),
5082 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005083 // mOutputSink below
5084 // mPipeSink below
5085 // mNormalSink below
5086{
Andy Hung7535ed92023-07-17 17:05:00 -07005087 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005088 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005089 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005090 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005091 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5092 mNormalFrameCount);
5093 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5094
Andy Hungfbfc3952015-01-15 13:33:51 -08005095 if (type == DUPLICATING) {
5096 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5097 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5098 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5099 return;
5100 }
Eric Laurent81784c32012-11-19 14:55:58 -08005101 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005102 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005103 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005104 const NBAIO_Format offers[1] = {Format_from_SR_C(
5105 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005106#if !LOG_NDEBUG
5107 ssize_t index =
5108#else
5109 (void)
5110#endif
5111 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005112 ALOG_ASSERT(index == 0);
5113
5114 // initialize fast mixer depending on configuration
5115 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005116 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005117 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005118 } else {
5119 switch (kUseFastMixer) {
5120 case FastMixer_Never:
5121 initFastMixer = false;
5122 break;
5123 case FastMixer_Always:
5124 initFastMixer = true;
5125 break;
5126 case FastMixer_Static:
5127 case FastMixer_Dynamic:
5128 initFastMixer = mFrameCount < mNormalFrameCount;
5129 break;
5130 }
5131 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5132 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5133 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005134 }
5135 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005136 audio_format_t fastMixerFormat;
5137 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5138 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5139 } else {
5140 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5141 }
5142 if (mFormat != fastMixerFormat) {
5143 // change our Sink format to accept our intermediate precision
5144 mFormat = fastMixerFormat;
5145 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005146 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005147 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5148 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5149 }
Eric Laurent81784c32012-11-19 14:55:58 -08005150
5151 // create a MonoPipe to connect our submix to FastMixer
5152 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005153
Andy Hung1258c1a2014-05-23 21:22:17 -07005154 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005155 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005156 format.mFormat = fastMixerFormat;
5157 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5158
Eric Laurent81784c32012-11-19 14:55:58 -08005159 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5160 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5161 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5162 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005163 const NBAIO_Format offersFast[1] = {format};
5164 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005165#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005166 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005167#else
5168 (void)
5169#endif
Andy Hung920f6572022-10-06 12:09:49 -07005170 monoPipe->negotiate(offersFast, std::size(offersFast),
5171 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005172 ALOG_ASSERT(index == 0);
5173 monoPipe->setAvgFrames((mScreenState & 1) ?
5174 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5175 mPipeSink = monoPipe;
5176
Eric Laurent81784c32012-11-19 14:55:58 -08005177 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005178 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005179 FastMixerStateQueue *sq = mFastMixer->sq();
5180#ifdef STATE_QUEUE_DUMP
5181 sq->setObserverDump(&mStateQueueObserverDump);
5182 sq->setMutatorDump(&mStateQueueMutatorDump);
5183#endif
5184 FastMixerState *state = sq->begin();
5185 FastTrack *fastTrack = &state->mFastTracks[0];
5186 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5187 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5188 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005189 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5190 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5191 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005192 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005193 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005194 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005195 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005196 fastTrack->mGeneration++;
5197 state->mFastTracksGen++;
5198 state->mTrackMask = 1;
5199 // fast mixer will use the HAL output sink
5200 state->mOutputSink = mOutputSink.get();
5201 state->mOutputSinkGen++;
5202 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005203 // specify sink channel mask when haptic channel mask present as it can not
5204 // be calculated directly from channel count
5205 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005206 ? AUDIO_CHANNEL_NONE
5207 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005208 state->mCommand = FastMixerState::COLD_IDLE;
5209 // already done in constructor initialization list
5210 //mFastMixerFutex = 0;
5211 state->mColdFutexAddr = &mFastMixerFutex;
5212 state->mColdGen++;
5213 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005214 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005215 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005216 sq->end();
5217 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5218
Eric Tan0513b5d2018-09-17 10:32:48 -07005219 NBLog::thread_info_t info;
5220 info.id = mId;
5221 info.type = NBLog::FASTMIXER;
5222 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5223
Eric Laurent81784c32012-11-19 14:55:58 -08005224 // start the fast mixer
5225 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5226 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005227 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005228 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005229
5230#ifdef AUDIO_WATCHDOG
5231 // create and start the watchdog
5232 mAudioWatchdog = new AudioWatchdog();
5233 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5234 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5235 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005236 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005237#endif
Andy Hung8946a282018-04-19 20:04:56 -07005238 } else {
5239#ifdef TEE_SINK
5240 // Only use the MixerThread tee if there is no FastMixer.
5241 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5242 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5243#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005244 }
5245
5246 switch (kUseFastMixer) {
5247 case FastMixer_Never:
5248 case FastMixer_Dynamic:
5249 mNormalSink = mOutputSink;
5250 break;
5251 case FastMixer_Always:
5252 mNormalSink = mPipeSink;
5253 break;
5254 case FastMixer_Static:
5255 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5256 break;
5257 }
5258}
5259
Andy Hung4b17e882023-07-07 13:47:37 -07005260MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005261{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005262 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005263 FastMixerStateQueue *sq = mFastMixer->sq();
5264 FastMixerState *state = sq->begin();
5265 if (state->mCommand == FastMixerState::COLD_IDLE) {
5266 int32_t old = android_atomic_inc(&mFastMixerFutex);
5267 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005268 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005269 }
5270 }
5271 state->mCommand = FastMixerState::EXIT;
5272 sq->end();
5273 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5274 mFastMixer->join();
5275 // Though the fast mixer thread has exited, it's state queue is still valid.
5276 // We'll use that extract the final state which contains one remaining fast track
5277 // corresponding to our sub-mix.
5278 state = sq->begin();
5279 ALOG_ASSERT(state->mTrackMask == 1);
5280 FastTrack *fastTrack = &state->mFastTracks[0];
5281 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5282 delete fastTrack->mBufferProvider;
5283 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005284 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005285#ifdef AUDIO_WATCHDOG
5286 if (mAudioWatchdog != 0) {
5287 mAudioWatchdog->requestExit();
5288 mAudioWatchdog->requestExitAndWait();
5289 mAudioWatchdog.clear();
5290 }
5291#endif
5292 }
Andy Hung7535ed92023-07-17 17:05:00 -07005293 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005294 delete mAudioMixer;
5295}
5296
Andy Hung4b17e882023-07-07 13:47:37 -07005297void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005298 PlaybackThread::onFirstRef();
5299
Andy Hungf8635b62023-08-31 16:13:39 -07005300 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005301 if (mOutput != nullptr && mOutput->stream != nullptr) {
5302 status_t status = mOutput->stream->setLatencyModeCallback(this);
5303 if (status != INVALID_OPERATION) {
5304 updateHalSupportedLatencyModes_l();
5305 }
5306 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5307 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5308 mBluetoothLatencyModesEnabled.store(
5309 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5310 }
5311}
Eric Laurent81784c32012-11-19 14:55:58 -08005312
Andy Hung4b17e882023-07-07 13:47:37 -07005313uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005314{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005315 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005316 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5317 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5318 }
5319 return latency;
5320}
5321
Andy Hung4b17e882023-07-07 13:47:37 -07005322ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005323{
5324 // FIXME we should only do one push per cycle; confirm this is true
5325 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005326 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005327 FastMixerStateQueue *sq = mFastMixer->sq();
5328 FastMixerState *state = sq->begin();
5329 if (state->mCommand != FastMixerState::MIX_WRITE &&
5330 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5331 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005332
5333 // FIXME workaround for first HAL write being CPU bound on some devices
5334 ATRACE_BEGIN("write");
5335 mOutput->write((char *)mSinkBuffer, 0);
5336 ATRACE_END();
5337
Eric Laurent81784c32012-11-19 14:55:58 -08005338 int32_t old = android_atomic_inc(&mFastMixerFutex);
5339 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005340 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005341 }
5342#ifdef AUDIO_WATCHDOG
5343 if (mAudioWatchdog != 0) {
5344 mAudioWatchdog->resume();
5345 }
5346#endif
5347 }
5348 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005349#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005350 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005351 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005352#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005353 sq->end();
5354 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5355 if (kUseFastMixer == FastMixer_Dynamic) {
5356 mNormalSink = mPipeSink;
5357 }
5358 } else {
5359 sq->end(false /*didModify*/);
5360 }
5361 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005363}
5364
Andy Hung4b17e882023-07-07 13:47:37 -07005365void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005366{
5367 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005368 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005369 FastMixerStateQueue *sq = mFastMixer->sq();
5370 FastMixerState *state = sq->begin();
5371 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005372 // Report any frames trapped in the Monopipe
5373 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5374 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5375 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5376 "monoPipeWritten:%lld monoPipeLeft:%lld",
5377 (long long)mFramesWritten, (long long)mSuspendedFrames,
5378 (long long)mPipeSink->framesWritten(), pipeFrames);
5379 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5380
Eric Laurent81784c32012-11-19 14:55:58 -08005381 state->mCommand = FastMixerState::COLD_IDLE;
5382 state->mColdFutexAddr = &mFastMixerFutex;
5383 state->mColdGen++;
5384 mFastMixerFutex = 0;
5385 sq->end();
5386 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5387 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5388 if (kUseFastMixer == FastMixer_Dynamic) {
5389 mNormalSink = mOutputSink;
5390 }
5391#ifdef AUDIO_WATCHDOG
5392 if (mAudioWatchdog != 0) {
5393 mAudioWatchdog->pause();
5394 }
5395#endif
5396 } else {
5397 sq->end(false /*didModify*/);
5398 }
5399 }
5400 PlaybackThread::threadLoop_standby();
5401}
5402
Andy Hung4b17e882023-07-07 13:47:37 -07005403bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005404{
5405 return false;
5406}
5407
Andy Hung4b17e882023-07-07 13:47:37 -07005408bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005409{
5410 return !mStandby;
5411}
5412
Andy Hung4b17e882023-07-07 13:47:37 -07005413bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005414{
Andy Hungf8635b62023-08-31 16:13:39 -07005415 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416 return waitingAsyncCallback_l();
5417}
5418
Eric Laurent81784c32012-11-19 14:55:58 -08005419// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005420void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005421{
Andy Hung160664b2023-09-15 18:19:28 -07005422 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5423 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005424 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005425 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005426 // discard any pending drain or write ack by incrementing sequence
5427 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5428 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005430 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5431 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005433 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005434 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005435}
5436
Andy Hung4b17e882023-07-07 13:47:37 -07005437void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005438{
5439 ALOGV("signal playback thread");
5440 broadcast_l();
5441}
5442
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005443void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005444{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005445 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005446 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5447 invalidateTracks((audio_stream_type_t)i);
5448 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005449 if (isHardError) {
5450 mAfThreadCallback->onHardError(allTrackPortIds);
5451 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005452}
5453
Andy Hung4b17e882023-07-07 13:47:37 -07005454void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005455{
Eric Laurent81784c32012-11-19 14:55:58 -08005456 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005457 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005458 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005459 // increase sleep time progressively when application underrun condition clears.
5460 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5461 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5462 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005463 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005464 sleepTimeShift--;
5465 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005466 mSleepTimeUs = 0;
5467 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005468 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005469
Eric Laurent81784c32012-11-19 14:55:58 -08005470}
5471
Andy Hung4b17e882023-07-07 13:47:37 -07005472void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005473{
5474 // If no tracks are ready, sleep once for the duration of an output
5475 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005476 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005477 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005478 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5479 // Using the Monopipe availableToWrite, we estimate the
5480 // sleep time to retry for more data (before we underrun).
5481 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5482 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5483 const size_t pipeFrames = monoPipe->maxFrames();
5484 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5485 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5486 const size_t framesDelay = std::min(
5487 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5488 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5489 pipeFrames, framesLeft, framesDelay);
5490 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5491 } else {
5492 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5493 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5494 mSleepTimeUs = kMinThreadSleepTimeUs;
5495 }
5496 // reduce sleep time in case of consecutive application underruns to avoid
5497 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5498 // duration we would end up writing less data than needed by the audio HAL if
5499 // the condition persists.
5500 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5501 sleepTimeShift++;
5502 }
Eric Laurent81784c32012-11-19 14:55:58 -08005503 }
5504 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005505 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005506 }
5507 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005508 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5509 // before effects processing or output.
5510 if (mMixerBufferValid) {
5511 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005512 if (mType == SPATIALIZER) {
5513 memset(mSinkBuffer, 0, mSinkBufferSize);
5514 }
Andy Hung98ef9782014-03-04 14:46:50 -08005515 } else {
5516 memset(mSinkBuffer, 0, mSinkBufferSize);
5517 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005518 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005519 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5520 "anticipated start");
5521 }
5522 // TODO add standby time extension fct of effect tail
5523}
5524
Andy Hungb17d24b2023-08-29 14:26:09 -07005525// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07005526PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005527 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005528{
Andy Hungc0691382018-09-12 18:01:57 -07005529 // clean up deleted track ids in AudioMixer before allocating new tracks
5530 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5531 // for each trackId, destroy it in the AudioMixer
5532 if (mAudioMixer->exists(trackId)) {
5533 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005534 }
5535 });
Andy Hungc0691382018-09-12 18:01:57 -07005536 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005537
5538 mixer_state mixerStatus = MIXER_IDLE;
5539 // find out which tracks need to be processed
5540 size_t count = mActiveTracks.size();
5541 size_t mixedTracks = 0;
5542 size_t tracksWithEffect = 0;
5543 // counts only _active_ fast tracks
5544 size_t fastTracks = 0;
5545 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5546
5547 float masterVolume = mMasterVolume;
5548 bool masterMute = mMasterMute;
5549
5550 if (masterMute) {
5551 masterVolume = 0;
5552 }
5553 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005554 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005555 if (chain != 0) {
5556 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005557 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005558 masterVolume = (float)((v + (1 << 23)) >> 24);
5559 chain.clear();
5560 }
5561
5562 // prepare a new state to push
5563 FastMixerStateQueue *sq = NULL;
5564 FastMixerState *state = NULL;
5565 bool didModify = false;
5566 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005567 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005568 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005569 sq = mFastMixer->sq();
5570 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005571 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005572 }
5573
Andy Hung69aed5f2014-02-25 17:24:40 -08005574 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005575 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005576
Andy Hungbd3b2b02018-05-21 10:53:11 -07005577 // DeferredOperations handles statistics after setting mixerStatus.
5578 class DeferredOperations {
5579 public:
Andy Hungea840382020-05-05 21:50:17 -07005580 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5581 : mMixerStatus(mixerStatus)
5582 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005583
5584 // when leaving scope, tally frames properly.
5585 ~DeferredOperations() {
5586 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5587 // because that is when the underrun occurs.
5588 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005589 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005590 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005591 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005592 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005593 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005594 }
5595 }
Andy Hungea840382020-05-05 21:50:17 -07005596 // send the max underrun frames for this mixer period
5597 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005598 }
5599
5600 // tallyUnderrunFrames() is called to update the track counters
5601 // with the number of underrun frames for a particular mixer period.
5602 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005603 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005604 mUnderrunFrames.emplace_back(track, underrunFrames);
5605 }
5606
5607 private:
5608 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005609 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005610 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005611 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005612 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005613
jiabin245cdd92018-12-07 17:55:15 -08005614 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005615 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005616 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005617
5618 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005619 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005620
5621 // process fast tracks
5622 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005623 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5624 "%s(%d): FastTrack(%d) present without FastMixer",
5625 __func__, id(), track->id());
5626
jiabin245cdd92018-12-07 17:55:15 -08005627 if (track->getHapticPlaybackEnabled()) {
5628 noFastHapticTrack = false;
5629 }
Eric Laurent81784c32012-11-19 14:55:58 -08005630
5631 // It's theoretically possible (though unlikely) for a fast track to be created
5632 // and then removed within the same normal mix cycle. This is not a problem, as
5633 // the track never becomes active so it's fast mixer slot is never touched.
5634 // The converse, of removing an (active) track and then creating a new track
5635 // at the identical fast mixer slot within the same normal mix cycle,
5636 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005637 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005638 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005639 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5640 FastTrack *fastTrack = &state->mFastTracks[j];
5641
5642 // Determine whether the track is currently in underrun condition,
5643 // and whether it had a recent underrun.
5644 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5645 FastTrackUnderruns underruns = ftDump->mUnderruns;
5646 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005647 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005648 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005649 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005650 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005651 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005652 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005653 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005654 // don't count underruns that occur while stopping or pausing
5655 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005656 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005657 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5658 recentUnderruns > 0) {
5659 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005660 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005661 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005662 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005663 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005664
5665 // This is similar to the state machine for normal tracks,
5666 // with a few modifications for fast tracks.
5667 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005668 switch (track->state()) {
5669 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005670 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005671 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005672 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005673 }
5674 break;
Andy Hung11e74242023-06-26 19:20:57 -07005675 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005676 // ramp down is not yet implemented
5677 track->setPaused();
5678 break;
Andy Hung11e74242023-06-26 19:20:57 -07005679 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005680 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005681 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005682 break;
Andy Hung11e74242023-06-26 19:20:57 -07005683 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005684 if (recentFull > 0 || recentPartial > 0) {
5685 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005686 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005687 }
5688 if (recentUnderruns == 0) {
5689 // no recent underruns: stay active
5690 break;
5691 }
5692 // there has recently been an underrun of some kind
5693 if (track->sharedBuffer() == 0) {
5694 // were any of the recent underruns "empty" (no frames available)?
5695 if (recentEmpty == 0) {
5696 // no, then ignore the partial underruns as they are allowed indefinitely
5697 break;
5698 }
5699 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005700 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005701 break;
5702 }
5703 // indicate to client process that the track was disabled because of underrun;
5704 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005705 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005706 // remove from active list, but state remains ACTIVE [confusing but true]
5707 isActive = false;
5708 break;
5709 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005710 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005711 case IAfTrackBase::STOPPING_2:
5712 case IAfTrackBase::PAUSED:
5713 case IAfTrackBase::STOPPED:
5714 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005715 // Check for presentation complete if track is inactive
5716 // We have consumed all the buffers of this track.
5717 // This would be incomplete if we auto-paused on underrun
5718 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005719 uint32_t latency = 0;
5720 status_t result = mOutput->stream->getLatency(&latency);
5721 ALOGE_IF(result != OK,
5722 "Error when retrieving output stream latency: %d", result);
5723 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005724 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005725 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5726 // track stays in active list until presentation is complete
5727 break;
5728 }
5729 }
5730 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005731 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005732 }
5733 if (track->isStopped()) {
5734 // Can't reset directly, as fast mixer is still polling this track
5735 // track->reset();
5736 // So instead mark this track as needing to be reset after push with ack
5737 resetMask |= 1 << i;
5738 }
5739 isActive = false;
5740 break;
Andy Hung11e74242023-06-26 19:20:57 -07005741 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005742 default:
Andy Hung11e74242023-06-26 19:20:57 -07005743 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005744 }
5745
5746 if (isActive) {
5747 // was it previously inactive?
5748 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005749 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5750 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005751 fastTrack->mBufferProvider = eabp;
5752 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005753 fastTrack->mChannelMask = track->channelMask();
5754 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005755 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005756 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005757 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005758 fastTrack->mGeneration++;
5759 state->mTrackMask |= 1 << j;
5760 didModify = true;
5761 // no acknowledgement required for newly active tracks
5762 }
Andy Hung11e74242023-06-26 19:20:57 -07005763 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005764 float volume;
5765 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5766 volume = 0.f;
5767 } else {
5768 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5769 }
5770
5771 handleVoipVolume_l(&volume);
5772
Eric Laurent81784c32012-11-19 14:55:58 -08005773 // cache the combined master volume and stream type volume for fast mixer; this
5774 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005775 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005776 proxy->framesReleased()).first;
5777 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005778 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005779 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005780 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5781 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5782
Andy Hung7535ed92023-07-17 17:05:00 -07005783 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005784 /*muteState=*/{masterVolume == 0.f,
5785 mStreamTypes[track->streamType()].volume == 0.f,
5786 mStreamTypes[track->streamType()].mute,
5787 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005788 vlf == 0.f && vrf == 0.f,
5789 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005790
5791 vlf *= volume;
5792 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005793
jiabin76d94692022-12-15 21:51:21 +00005794 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005795 ++fastTracks;
5796 } else {
5797 // was it previously active?
5798 if (state->mTrackMask & (1 << j)) {
5799 fastTrack->mBufferProvider = NULL;
5800 fastTrack->mGeneration++;
5801 state->mTrackMask &= ~(1 << j);
5802 didModify = true;
5803 // If any fast tracks were removed, we must wait for acknowledgement
5804 // because we're about to decrement the last sp<> on those tracks.
5805 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5806 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005807 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5808 // AudioTrack may start (which may not be with a start() but with a write()
5809 // after underrun) and immediately paused or released. In that case the
5810 // FastTrack state hasn't had time to update.
5811 // TODO Remove the ALOGW when this theory is confirmed.
5812 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005813 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005814 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005815 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005816 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005817 }
5818 tracksToRemove->add(track);
5819 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005820 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005821 }
jiabin245cdd92018-12-07 17:55:15 -08005822 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5823 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5824 didModify = true;
5825 }
Eric Laurent81784c32012-11-19 14:55:58 -08005826 continue;
5827 }
5828
5829 { // local variable scope to avoid goto warning
5830
5831 audio_track_cblk_t* cblk = track->cblk();
5832
5833 // The first time a track is added we wait
5834 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005835 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005836
5837 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005838 // use the trackId as the AudioMixer name.
5839 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005840 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005841 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005842 track->channelMask(),
5843 track->format(),
5844 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005845 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005846 ALOGW("%s(): AudioMixer cannot create track(%d)"
5847 " mask %#x, format %#x, sessionId %d",
5848 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005849 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005850 tracksToRemove->add(track);
5851 track->invalidate(); // consider it dead.
5852 continue;
5853 }
5854 }
5855
Eric Laurent81784c32012-11-19 14:55:58 -08005856 // make sure that we have enough frames to mix one full buffer.
5857 // enforce this condition only once to enable draining the buffer in case the client
5858 // app does not call stop() and relies on underrun to stop:
5859 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5860 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005861 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005862 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5863 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005864
5865 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005866 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005867 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5868 // add frames already consumed but not yet released by the resampler
5869 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005870 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005871
Eric Laurent81784c32012-11-19 14:55:58 -08005872 uint32_t minFrames = 1;
5873 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5874 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005875 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005876 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005877
5878 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005879 if (ATRACE_ENABLED()) {
5880 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005881 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005882 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005883 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005884 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005885 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005886 !track->isPaused() && !track->isTerminated())
5887 {
Andy Hungc0691382018-09-12 18:01:57 -07005888 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005889
5890 mixedTracks++;
5891
Shunkai Yaof4847652024-01-12 00:25:20 +00005892 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005893 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005894 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005895 if (track->mainBuffer() != mSinkBuffer &&
5896 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005897 if (mEffectBufferEnabled) {
5898 mEffectBufferValid = true; // Later can set directly.
5899 }
Eric Laurent81784c32012-11-19 14:55:58 -08005900 chain = getEffectChain_l(track->sessionId());
5901 // Delegate volume control to effect in track effect chain if needed
5902 if (chain != 0) {
5903 tracksWithEffect++;
5904 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005905 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005906 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005907 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005908 }
5909 }
5910
5911
5912 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005913 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005914 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005915 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5916 if (track->state() == IAfTrackBase::RESUMING) {
5917 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005918 // If a new track is paused immediately after start, do not ramp on resume.
5919 if (cblk->mServer != 0) {
5920 param = AudioMixer::RAMP_VOLUME;
5921 }
Eric Laurent81784c32012-11-19 14:55:58 -08005922 }
Andy Hungc0691382018-09-12 18:01:57 -07005923 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005924 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005925 // FIXME should not make a decision based on mServer
5926 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005927 // If the track is stopped before the first frame was mixed,
5928 // do not apply ramp
5929 param = AudioMixer::RAMP_VOLUME;
5930 }
5931
5932 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005933 uint32_t vl, vr; // in U8.24 integer format
5934 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005935 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005936 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005937 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005938 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005939 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005940 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005941
Eric Laurenteab90452019-06-24 15:17:46 -07005942 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5943 v = 0;
5944 }
5945
5946 handleVoipVolume_l(&v);
5947
5948 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005949 vl = vr = 0;
5950 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005951 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005952 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005953 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005954 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5955 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005956 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005957 if (vlf > GAIN_FLOAT_UNITY) {
5958 ALOGV("Track left volume out of range: %.3g", vlf);
5959 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005960 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005961 if (vrf > GAIN_FLOAT_UNITY) {
5962 ALOGV("Track right volume out of range: %.3g", vrf);
5963 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005964 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005965
Andy Hung7535ed92023-07-17 17:05:00 -07005966 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005967 /*muteState=*/{masterVolume == 0.f,
5968 mStreamTypes[track->streamType()].volume == 0.f,
5969 mStreamTypes[track->streamType()].mute,
5970 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005971 vlf == 0.f && vrf == 0.f,
5972 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005973
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005974 // now apply the master volume and stream type volume and shaper volume
5975 vlf *= v * vh;
5976 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005977 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005978 // then derive vl and vr as U8.24 versions for the effect chain
5979 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5980 vl = (uint32_t) (scaleto8_24 * vlf);
5981 vr = (uint32_t) (scaleto8_24 * vrf);
5982 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005983 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005984 // send level comes from shared memory and so may be corrupt
5985 if (sendLevel > MAX_GAIN_INT) {
5986 ALOGV("Track send level out of range: %04X", sendLevel);
5987 sendLevel = MAX_GAIN_INT;
5988 }
Andy Hung6be49402014-05-30 10:42:03 -07005989 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5990 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005991 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005992
Jiabin Huang66aa1e32024-05-13 20:33:29 +00005993 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07005994
Eric Laurent81784c32012-11-19 14:55:58 -08005995 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00005996 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005997 // Do not ramp volume if volume is controlled by effect
5998 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005999 // Update remaining floating point volume levels
6000 vlf = (float)vl / (1 << 24);
6001 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07006002 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006003 } else {
6004 // force no volume ramp when volume controller was just disabled or removed
6005 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07006006 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006007 param = AudioMixer::VOLUME;
6008 }
Andy Hung11e74242023-06-26 19:20:57 -07006009 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006010 }
6011
Eric Laurent81784c32012-11-19 14:55:58 -08006012 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07006013 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006014 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006015
Andy Hungc0691382018-09-12 18:01:57 -07006016 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6017 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6018 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006019 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006020 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006021 AudioMixer::TRACK,
6022 AudioMixer::FORMAT, (void *)track->format());
6023 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006024 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006025 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006026 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006027
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006028 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006029 mAudioMixer->setParameter(
6030 trackId,
6031 AudioMixer::TRACK,
6032 AudioMixer::MIXER_CHANNEL_MASK,
6033 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6034 } else {
6035 mAudioMixer->setParameter(
6036 trackId,
6037 AudioMixer::TRACK,
6038 AudioMixer::MIXER_CHANNEL_MASK,
6039 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6040 }
6041
Glenn Kastene3aa6592012-12-04 12:22:46 -08006042 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006043 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006044 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006045 if (reqSampleRate == 0) {
6046 reqSampleRate = mSampleRate;
6047 } else if (reqSampleRate > maxSampleRate) {
6048 reqSampleRate = maxSampleRate;
6049 }
Eric Laurent81784c32012-11-19 14:55:58 -08006050 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006051 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006052 AudioMixer::RESAMPLE,
6053 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006054 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006055
Andy Hung8edb8dc2015-03-26 19:13:55 -07006056 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006057 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006058 AudioMixer::TIMESTRETCH,
6059 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006060 // cast away constness for this generic API.
6061 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006062
Andy Hung69aed5f2014-02-25 17:24:40 -08006063 /*
6064 * Select the appropriate output buffer for the track.
6065 *
Andy Hung98ef9782014-03-04 14:46:50 -08006066 * Tracks with effects go into their own effects chain buffer
6067 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006068 *
6069 * Other tracks can use mMixerBuffer for higher precision
6070 * channel accumulation. If this buffer is enabled
6071 * (mMixerBufferEnabled true), then selected tracks will accumulate
6072 * into it.
6073 *
6074 */
6075 if (mMixerBufferEnabled
6076 && (track->mainBuffer() == mSinkBuffer
6077 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006078 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006079 mAudioMixer->setParameter(
6080 trackId,
6081 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006082 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006083 mAudioMixer->setParameter(
6084 trackId,
6085 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006086 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006087 } else {
6088 mAudioMixer->setParameter(
6089 trackId,
6090 AudioMixer::TRACK,
6091 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6092 mAudioMixer->setParameter(
6093 trackId,
6094 AudioMixer::TRACK,
6095 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6096 // TODO: override track->mainBuffer()?
6097 mMixerBufferValid = true;
6098 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006099 } else {
6100 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006101 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006102 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006103 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006104 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006105 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006106 AudioMixer::TRACK,
6107 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6108 }
Eric Laurent81784c32012-11-19 14:55:58 -08006109 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006110 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006111 AudioMixer::TRACK,
6112 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006113 mAudioMixer->setParameter(
6114 trackId,
6115 AudioMixer::TRACK,
6116 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006117 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006118 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006119 trackId,
6120 AudioMixer::TRACK,
6121 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung11e74242023-06-26 19:20:57 -07006122 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006123 mAudioMixer->setParameter(
6124 trackId,
6125 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07006126 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006127
6128 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006129 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006130
6131 // If one track is ready, set the mixer ready if:
6132 // - the mixer was not ready during previous round OR
6133 // - no other track is not ready
6134 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6135 mixerStatus != MIXER_TRACKS_ENABLED) {
6136 mixerStatus = MIXER_TRACKS_READY;
6137 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006138
6139 // Enable the next few lines to instrument a test for underrun log handling.
6140 // TODO: Remove when we have a better way of testing the underrun log.
6141#if 0
6142 static int i;
6143 if ((++i & 0xf) == 0) {
6144 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6145 }
6146#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006147 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006148 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006149 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006150 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6151 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006152 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006153 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006154 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006155
Eric Laurent81784c32012-11-19 14:55:58 -08006156 // clear effect chain input buffer if an active track underruns to avoid sending
6157 // previous audio buffer again to effects
6158 chain = getEffectChain_l(track->sessionId());
6159 if (chain != 0) {
6160 chain->clearInputBuffer();
6161 }
6162
Andy Hungc0691382018-09-12 18:01:57 -07006163 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006164 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6165 track->isStopped() || track->isPaused()) {
6166 // We have consumed all the buffers of this track.
6167 // Remove it from the list of active tracks.
6168 // TODO: use actual buffer filling status instead of latency when available from
6169 // audio HAL
6170 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006171 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006172 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6173 if (track->isStopped()) {
6174 track->reset();
6175 }
6176 tracksToRemove->add(track);
6177 }
6178 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006179 // No buffers for this track. Give it a few chances to
6180 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07006181 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006182 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6183 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006184 tracksToRemove->add(track);
6185 // indicate to client process that the track was disabled because of underrun;
6186 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006187 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006188 // If one track is not ready, mark the mixer also not ready if:
6189 // - the mixer was ready during previous round OR
6190 // - no other track is ready
6191 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6192 mixerStatus != MIXER_TRACKS_READY) {
6193 mixerStatus = MIXER_TRACKS_ENABLED;
6194 }
6195 }
Andy Hungc0691382018-09-12 18:01:57 -07006196 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006197 }
6198
6199 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006200
6201 }
6202
jiabin245cdd92018-12-07 17:55:15 -08006203 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6204 // When there is no fast track playing haptic and FastMixer exists,
6205 // enabling the first FastTrack, which provides mixed data from normal
6206 // tracks, to play haptic data.
6207 FastTrack *fastTrack = &state->mFastTracks[0];
6208 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6209 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6210 didModify = true;
6211 }
6212 }
6213
Eric Laurent81784c32012-11-19 14:55:58 -08006214 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006215 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006216 if (didModify) {
6217 state->mFastTracksGen++;
6218 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6219 if (kUseFastMixer == FastMixer_Dynamic &&
6220 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6221 state->mCommand = FastMixerState::COLD_IDLE;
6222 state->mColdFutexAddr = &mFastMixerFutex;
6223 state->mColdGen++;
6224 mFastMixerFutex = 0;
6225 if (kUseFastMixer == FastMixer_Dynamic) {
6226 mNormalSink = mOutputSink;
6227 }
6228 // If we go into cold idle, need to wait for acknowledgement
6229 // so that fast mixer stops doing I/O.
6230 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6231 pauseAudioWatchdog = true;
6232 }
Eric Laurent81784c32012-11-19 14:55:58 -08006233 }
6234 if (sq != NULL) {
6235 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006236 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6237 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6238 // when bringing the output sink into standby.)
6239 //
6240 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6241 //
6242 // This occurs with BT suspend when we idle the FastMixer with
6243 // active tracks, which may be added or removed.
6244 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
6246#ifdef AUDIO_WATCHDOG
6247 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6248 mAudioWatchdog->pause();
6249 }
6250#endif
6251
6252 // Now perform the deferred reset on fast tracks that have stopped
6253 while (resetMask != 0) {
6254 size_t i = __builtin_ctz(resetMask);
6255 ALOG_ASSERT(i < count);
6256 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006257 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006258 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6259 track->reset();
6260 }
6261
Andy Hung80d03d22018-04-10 10:32:11 -07006262 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6263 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6264 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6265 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6266 // See also the implementation of destroyTrack_l().
6267 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006268 const int trackId = track->id();
6269 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6270 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006271 }
6272 }
6273
Eric Laurent81784c32012-11-19 14:55:58 -08006274 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006275 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006276
Eric Laurentb3f315a2021-07-13 15:09:05 +02006277 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6278 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006279 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006280 }
6281
6282 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006283 // as long as there are effects we should clear the effects buffer, to avoid
6284 // passing a non-clean buffer to the effect chain
6285 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006286 if (mType == SPATIALIZER) {
6287 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6288 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006289 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006290 // sink or mix buffer must be cleared if all tracks are connected to an
6291 // effect chain as in this case the mixer will not write to the sink or mix buffer
6292 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006293 // always clear sink buffer for spatializer output as the output of the spatializer
6294 // effect will be accumulated into it
6295 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6296 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006297 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006298 if (mMixerBufferValid) {
6299 memset(mMixerBuffer, 0, mMixerBufferSize);
6300 // TODO: In testing, mSinkBuffer below need not be cleared because
6301 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6302 // after mixing.
6303 //
6304 // To enforce this guarantee:
6305 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6306 // (mixedTracks == 0 && fastTracks > 0))
6307 // must imply MIXER_TRACKS_READY.
6308 // Later, we may clear buffers regardless, and skip much of this logic.
6309 }
Andy Hung98ef9782014-03-04 14:46:50 -08006310 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006311 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006312 }
6313
6314 // if any fast tracks, then status is ready
6315 mMixerStatusIgnoringFastTracks = mixerStatus;
6316 if (fastTracks > 0) {
6317 mixerStatus = MIXER_TRACKS_READY;
6318 }
6319 return mixerStatus;
6320}
6321
Andy Hungb17d24b2023-08-29 14:26:09 -07006322// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006323uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006324{
6325 uint32_t trackCount = 0;
6326 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006327 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006328 trackCount++;
6329 }
6330 }
6331 return trackCount;
6332}
6333
Andy Hung4b17e882023-07-07 13:47:37 -07006334bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006335{
Brian Lindahl65e90012022-07-27 18:01:07 +02006336 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6337 // could falsely detect that the frame position has stalled due to underrun because we haven't
6338 // given the Audio HAL enough time to update.
6339 const nsecs_t nowNs = systemTime();
6340 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6341 return mLatchedValue;
6342 }
6343 mPreviousNs = nowNs;
6344 mLatchedValue = false;
6345 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006346 uint64_t position = 0;
6347 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006348 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006349 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006350 if (position != mPreviousPosition) {
6351 mPreviousPosition = position;
6352 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006353 }
6354 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006355 return mLatchedValue;
6356}
6357
Andy Hung4b17e882023-07-07 13:47:37 -07006358void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006359{
6360 mLatchedValue = true;
6361 mPreviousPosition = 0;
6362 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006363}
6364
Andy Hungb17d24b2023-08-29 14:26:09 -07006365// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006366bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006367 audio_channel_mask_t channelMask, audio_format_t format,
6368 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006369{
Andy Hung1bc088a2018-02-09 15:57:31 -08006370 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6371 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006372 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006373 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006374 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006375 ALOGW("%s: invalid format: %#x", __func__, format);
6376 return false;
6377 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006378 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006379 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6380 return false;
6381 }
6382 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006383}
6384
Andy Hungb17d24b2023-08-29 14:26:09 -07006385// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006386bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006387 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006388{
Eric Laurent81784c32012-11-19 14:55:58 -08006389 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006390 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006391
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006392 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006393
Eric Laurent10351942014-05-08 18:49:52 -07006394 AudioParameter param = AudioParameter(keyValuePair);
6395 int value;
6396 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6397 reconfig = true;
6398 }
6399 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006400 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006401 status = BAD_VALUE;
6402 } else {
6403 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006404 reconfig = true;
6405 }
Eric Laurent10351942014-05-08 18:49:52 -07006406 }
6407 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006408 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006409 status = BAD_VALUE;
6410 } else {
6411 // no need to save value, since it's constant
6412 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006413 }
Eric Laurent10351942014-05-08 18:49:52 -07006414 }
6415 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6416 // do not accept frame count changes if tracks are open as the track buffer
6417 // size depends on frame count and correct behavior would not be guaranteed
6418 // if frame count is changed after track creation
6419 if (!mTracks.isEmpty()) {
6420 status = INVALID_OPERATION;
6421 } else {
6422 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006423 }
Eric Laurent10351942014-05-08 18:49:52 -07006424 }
6425 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006426 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006427 }
Eric Laurent81784c32012-11-19 14:55:58 -08006428
Eric Laurent10351942014-05-08 18:49:52 -07006429 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006430 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006431 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006432 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6433 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006434 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006435 mThreadMetrics.logEndInterval();
6436 mThreadSnapshot.onEnd();
6437 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006438 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006439 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006440 }
Eric Laurent10351942014-05-08 18:49:52 -07006441 if (status == NO_ERROR && reconfig) {
6442 readOutputParameters_l();
6443 delete mAudioMixer;
6444 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006445 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006446 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006447 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006448 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006449 track->channelMask(),
6450 track->format(),
6451 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006452 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006453 "%s(): AudioMixer cannot create track(%d)"
6454 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006455 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006456 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006457 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006458 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006459 }
Eric Laurent81784c32012-11-19 14:55:58 -08006460 }
6461
Dean Wheatley68918102021-03-19 22:09:19 +11006462 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006463}
6464
6465
Andy Hung4b17e882023-07-07 13:47:37 -07006466void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006467{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006468 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung160664b2023-09-15 18:19:28 -07006469 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006470 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006471 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006472 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6473 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6474 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006475 if (hasFastMixer()) {
6476 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6477
6478 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6479 // while we are dumping it. It may be inconsistent, but it won't mutate!
6480 // This is a large object so we place it on the heap.
6481 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006482 const std::unique_ptr<FastMixerDumpState> copy =
6483 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006484 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006485
6486#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006487 // Similar for state queue
6488 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6489 observerCopy.dump(fd);
6490 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6491 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006492#endif
6493
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006494#ifdef AUDIO_WATCHDOG
6495 if (mAudioWatchdog != 0) {
6496 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6497 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6498 wdCopy.dump(fd);
6499 }
6500#endif
6501
6502 } else {
6503 dprintf(fd, " No FastMixer\n");
6504 }
Eric Laurent90cea102023-05-15 15:08:27 +02006505
6506 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6507 mBluetoothLatencyModesEnabled ? "" : "not ");
6508 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6509 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6510 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006511}
6512
Andy Hung4b17e882023-07-07 13:47:37 -07006513uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006514{
6515 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6516}
6517
Andy Hung4b17e882023-07-07 13:47:37 -07006518uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006519{
6520 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6521}
6522
Andy Hung4b17e882023-07-07 13:47:37 -07006523void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006524{
6525 PlaybackThread::cacheParameters_l();
6526
6527 // FIXME: Relaxed timing because of a certain device that can't meet latency
6528 // Should be reduced to 2x after the vendor fixes the driver issue
6529 // increase threshold again due to low power audio mode. The way this warning
6530 // threshold is calculated and its usefulness should be reconsidered anyway.
6531 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6532}
6533
Andy Hung4b17e882023-07-07 13:47:37 -07006534void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006535 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006536}
6537
Andy Hung4b17e882023-07-07 13:47:37 -07006538void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006539 // Only handle latency mode if:
6540 // - mBluetoothLatencyModesEnabled is true
6541 // - the HAL supports latency modes
6542 // - the selected device is Bluetooth LE or A2DP
6543 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6544 return;
6545 }
6546 if (mOutDeviceTypeAddrs.size() != 1
6547 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6548 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6549 return;
6550 }
6551
6552 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6553 if (mSupportedLatencyModes.size() == 1) {
6554 // If the HAL only support one latency mode currently, confirm the choice
6555 latencyMode = mSupportedLatencyModes[0];
6556 } else if (mSupportedLatencyModes.size() > 1) {
6557 // Request low latency if:
6558 // - At least one active track is either:
6559 // - a fast track with gaming usage or
6560 // - a track with acessibility usage
6561 for (const auto& track : mActiveTracks) {
6562 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6563 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6564 latencyMode = AUDIO_LATENCY_MODE_LOW;
6565 break;
6566 }
6567 }
6568 }
6569
6570 if (latencyMode != mSetLatencyMode) {
6571 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6572 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6573 __func__, mId, toString(latencyMode).c_str(), status);
6574 if (status == NO_ERROR) {
6575 mSetLatencyMode = latencyMode;
6576 }
6577 }
6578}
6579
Andy Hung4b17e882023-07-07 13:47:37 -07006580void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006581
6582 if (mOutput == nullptr || mOutput->stream == nullptr) {
6583 return;
6584 }
6585 std::vector<audio_latency_mode_t> latencyModes;
6586 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6587 if (status != NO_ERROR) {
6588 latencyModes.clear();
6589 }
6590 if (latencyModes != mSupportedLatencyModes) {
6591 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6592 __func__, mId, status, toString(latencyModes).c_str());
6593 mSupportedLatencyModes.swap(latencyModes);
6594 sendHalLatencyModesChangedEvent_l();
6595 }
6596}
6597
Andy Hung4b17e882023-07-07 13:47:37 -07006598status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006599 std::vector<audio_latency_mode_t>* modes) {
6600 if (modes == nullptr) {
6601 return BAD_VALUE;
6602 }
Andy Hungf8635b62023-08-31 16:13:39 -07006603 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006604 *modes = mSupportedLatencyModes;
6605 return NO_ERROR;
6606}
6607
Andy Hung4b17e882023-07-07 13:47:37 -07006608void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006609 std::vector<audio_latency_mode_t> modes) {
Andy Hungf8635b62023-08-31 16:13:39 -07006610 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006611 if (modes != mSupportedLatencyModes) {
6612 ALOGD("%s: thread(%d) supported latency modes: %s",
6613 __func__, mId, toString(modes).c_str());
6614 mSupportedLatencyModes.swap(modes);
6615 sendHalLatencyModesChangedEvent_l();
6616 }
6617}
6618
Andy Hung4b17e882023-07-07 13:47:37 -07006619status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006620 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6621 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6622 return INVALID_OPERATION;
6623 }
6624 mBluetoothLatencyModesEnabled.store(enabled);
6625 return NO_ERROR;
6626}
6627
Eric Laurent81784c32012-11-19 14:55:58 -08006628// ----------------------------------------------------------------------------
6629
Andy Hung4b17e882023-07-07 13:47:37 -07006630/* static */
6631sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006632 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006633 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6634 const audio_offload_info_t& offloadInfo) {
6635 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006636 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006637}
6638
Andy Hung7535ed92023-07-17 17:05:00 -07006639DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006640 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6641 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006642 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006643 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006644{
Andy Hung7535ed92023-07-17 17:05:00 -07006645 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006646}
6647
Andy Hung4b17e882023-07-07 13:47:37 -07006648DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006649{
6650}
6651
Andy Hung4b17e882023-07-07 13:47:37 -07006652void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006653{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006654 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006655 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6656 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6657}
6658
Andy Hung4b17e882023-07-07 13:47:37 -07006659void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006660{
Andy Hungf8635b62023-08-31 16:13:39 -07006661 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006662 if (mMasterBalance != balance) {
6663 mMasterBalance.store(balance);
6664 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6665 broadcast_l();
6666 }
6667}
6668
Andy Hung4b17e882023-07-07 13:47:37 -07006669void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006670{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006671 float left, right;
6672
Andy Hung333ab962019-05-28 20:23:35 -07006673 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006674 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006675
Andy Hung398ffa22022-12-13 19:19:53 -08006676 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6677 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6678
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006679 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6680 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006681
6682 const int64_t volumeShaperFrames =
6683 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6684 const auto [shaperVolume, shaperActive] =
6685 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006686 mVolumeShaperActive = shaperActive;
6687
Vlad Popae2f5aef2022-07-25 16:00:20 +02006688 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6689 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6690 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6691
6692 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6693
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006694 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006695 left = right = 0;
6696 } else {
6697 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006698 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006699
Glenn Kastenc56f3422014-03-21 17:53:17 -07006700 if (left > GAIN_FLOAT_UNITY) {
6701 left = GAIN_FLOAT_UNITY;
6702 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006703 if (right > GAIN_FLOAT_UNITY) {
6704 right = GAIN_FLOAT_UNITY;
6705 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006706 left *= v;
6707 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006708 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006709 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6710 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6711 right *= mMasterBalanceRight;
6712 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006713 }
6714
Andy Hung7535ed92023-07-17 17:05:00 -07006715 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006716 /*muteState=*/{mMasterMute,
6717 mStreamTypes[track->streamType()].volume == 0.f,
6718 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006719 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006720 clientVolumeMute,
6721 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006722
Eric Laurentbfb1b832013-01-07 09:53:42 -08006723 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006724 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006725 if (left != mLeftVolFloat || right != mRightVolFloat) {
6726 mLeftVolFloat = left;
6727 mRightVolFloat = right;
6728
Eric Laurentbfb1b832013-01-07 09:53:42 -08006729 // Delegate volume control to effect in track effect chain if needed
6730 // only one effect chain can be present on DirectOutputThread, so if
6731 // there is one, the track is connected to it
6732 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006733 // if effect chain exists, volume is handled by it.
6734 // Convert volumes from float to 8.24
6735 uint32_t vl = (uint32_t)(left * (1 << 24));
6736 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006737 // Direct/Offload effect chains set output volume in setVolume().
6738 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006739 } else {
6740 // otherwise we directly set the volume.
6741 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006742 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006743 }
6744 }
6745}
6746
Andy Hung4b17e882023-07-07 13:47:37 -07006747void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006748{
Andy Hung11e74242023-06-26 19:20:57 -07006749 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6750 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006751
Eric Laurent0f0631e2015-07-06 18:01:25 -07006752 if (previousTrack != 0 && latestTrack != 0) {
6753 if (mType == DIRECT) {
6754 if (previousTrack.get() != latestTrack.get()) {
6755 mFlushPending = true;
6756 }
6757 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006758 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6759 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006760 mFlushPending = true;
6761 }
6762 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006763 } else if (previousTrack == 0) {
6764 // there could be an old track added back during track transition for direct
6765 // output, so always issues flush to flush data of the previous track if it
6766 // was already destroyed with HAL paused, then flush can resume the playback
6767 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006768 }
6769 PlaybackThread::onAddNewTrack_l();
6770}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006771
Andy Hung4b17e882023-07-07 13:47:37 -07006772PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006773 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006774)
6775{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006776 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006777 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006778 bool doHwPause = false;
6779 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006780
6781 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006782 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006783 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006784 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006785 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006786 continue;
6787 }
6788
Andy Hung11e74242023-06-26 19:20:57 -07006789 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006790#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006791 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006792#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006793 // Only consider last track started for volume and mixer state control.
6794 // In theory an older track could underrun and restart after the new one starts
6795 // but as we only care about the transition phase between two tracks on a
6796 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006797 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006798 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006799
Kuowei Li23666472021-01-20 10:23:25 +08006800 if (track->isPausePending()) {
6801 track->pauseAck();
6802 // It is possible a track might have been flushed or stopped.
6803 // Other operations such as flush pending might occur on the next prepare.
6804 if (track->isPausing()) {
6805 track->setPaused();
6806 }
6807 // Always perform pause, as an immediate flush will change
6808 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006809 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006810 doHwPause = true;
6811 mHwPaused = true;
6812 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006813 } else if (track->isFlushPending()) {
6814 track->flushAck();
6815 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006816 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006817 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006818 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006819 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006820 if (last) {
6821 mLeftVolFloat = mRightVolFloat = -1.0;
6822 if (mHwPaused) {
6823 doHwResume = true;
6824 mHwPaused = false;
6825 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006826 }
6827 }
6828
Eric Laurent81784c32012-11-19 14:55:58 -08006829 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006830 // for all its buffers to be filled before processing it.
6831 // Allow draining the buffer in case the client
6832 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006833 // hence the test on (track->retryCount() > 1).
6834 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006835 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6836 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006837 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006838
6839 // target retry count that we will use is based on the time we wait for retries.
6840 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6841 // the retry threshold is when we accept any size for PCM data. This is slightly
6842 // smaller than the retry count so we can push small bits of data without a glitch.
6843 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006844 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006845 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006846 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006847 minFrames = mNormalFrameCount;
6848 } else {
6849 minFrames = 1;
6850 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006851
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006852 const size_t framesReady = track->framesReady();
6853 const int trackId = track->id();
6854 if (ATRACE_ENABLED()) {
6855 std::string traceName("nRdy");
6856 traceName += std::to_string(trackId);
6857 ATRACE_INT(traceName.c_str(), framesReady);
6858 }
6859 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006860 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006861 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006862 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006863
Andy Hung11e74242023-06-26 19:20:57 -07006864 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6865 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006866 if (last) {
6867 // make sure processVolume_l() will apply new volume even if 0
6868 mLeftVolFloat = mRightVolFloat = -1.0;
6869 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006870 if (!mHwSupportsPause) {
6871 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006872 }
6873 }
6874
6875 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006876 processVolume_l(track, last);
6877 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006878 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006879 if (previousTrack != 0) {
6880 if (track != previousTrack.get()) {
6881 // Flush any data still being written from last track
6882 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006883 // Invalidate previous track to force a seek when resuming.
6884 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006885 }
6886 }
6887 mPreviousTrack = track;
6888
Eric Laurentd595b7c2013-04-03 17:27:56 -07006889 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006890 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006891 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006892 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006893 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006894 doHwResume = true;
6895 mHwPaused = false;
6896 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006897 }
Eric Laurent81784c32012-11-19 14:55:58 -08006898 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006899 // clear effect chain input buffer if the last active track started underruns
6900 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006901 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006902 mEffectChains[0]->clearInputBuffer();
6903 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006904 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006905 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006906 if (last && mHwPaused) {
6907 doHwResume = true;
6908 mHwPaused = false;
6909 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006910 }
6911 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6912 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006913 // We have consumed all the buffers of this track.
6914 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006915 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006916 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006917 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006918 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006919 if (presComplete) {
6920 mOutput->presentationComplete();
6921 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006922 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006923 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006924 }
Eric Laurent81784c32012-11-19 14:55:58 -08006925 if (track->isStopped()) {
6926 track->reset();
6927 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006928 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006929 }
6930 } else {
6931 // No buffers for this track. Give it a few chances to
6932 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006933 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006934 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006935 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006936 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006937 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006938 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006939 } else {
6940 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6941 tracksToRemove->add(track);
6942 // indicate to client process that the track was disabled because of
6943 // underrun; it will then automatically call start() when data is available
6944 track->disable();
6945 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6946 // unlike mixerthread, HAL can be paused for direct output
6947 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6948 "minFrames = %u, mFormat = %#x",
6949 framesReady, minFrames, mFormat);
6950 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6951 doHwPause = true;
6952 mHwPaused = true;
6953 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006954 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006955 } else if (last) {
6956 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006957 }
6958 }
6959 }
6960 }
6961
Eric Laurentd1f69b02014-12-15 14:33:13 -08006962 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006963 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006964 for (size_t i = 0; i < mTracks.size(); i++) {
6965 if (mTracks[i]->isFlushPending()) {
6966 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006967 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006968 }
6969 }
6970 }
6971
6972 // make sure the pause/flush/resume sequence is executed in the right order.
6973 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6974 // before flush and then resume HW. This can happen in case of pause/flush/resume
6975 // if resume is received before pause is executed.
6976 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006977 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006978 status_t result = mOutput->stream->pause();
6979 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006980 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006981 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006982 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006983 flushHw_l();
6984 }
6985 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006986 status_t result = mOutput->stream->resume();
6987 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006988 }
Eric Laurent81784c32012-11-19 14:55:58 -08006989 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006990 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006991
6992 return mixerStatus;
6993}
6994
Andy Hung4b17e882023-07-07 13:47:37 -07006995void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006996{
Eric Laurent81784c32012-11-19 14:55:58 -08006997 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006998 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006999 // output audio to hardware
7000 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007001 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007002 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007003 status_t status = mActiveTrack->getNextBuffer(&buffer);
7004 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007005 // no need to pad with 0 for compressed audio
7006 if (audio_has_proportional_frames(mFormat)) {
7007 memset(curBuf, 0, frameCount * mFrameSize);
7008 }
Eric Laurent81784c32012-11-19 14:55:58 -08007009 break;
7010 }
7011 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7012 frameCount -= buffer.frameCount;
7013 curBuf += buffer.frameCount * mFrameSize;
7014 mActiveTrack->releaseBuffer(&buffer);
7015 }
Andy Hung2098f272014-02-27 14:00:06 -08007016 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007017 mSleepTimeUs = 0;
7018 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007019 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007020}
7021
Andy Hung4b17e882023-07-07 13:47:37 -07007022void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007023{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007024 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007025 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007026 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007027 return;
7028 }
Andy Hung85ba3332021-04-27 17:40:26 -07007029 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7030 mSleepTimeUs = mActiveSleepTimeUs;
7031 } else {
7032 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007033 }
Andy Hung85ba3332021-04-27 17:40:26 -07007034 // Note: In S or later, we do not write zeroes for
7035 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007036}
7037
Andy Hung4b17e882023-07-07 13:47:37 -07007038void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007039{
7040 {
Andy Hungf8635b62023-08-31 16:13:39 -07007041 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007042 for (size_t i = 0; i < mTracks.size(); i++) {
7043 if (mTracks[i]->isFlushPending()) {
7044 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007045 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007046 }
7047 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007048 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007049 flushHw_l();
7050 }
7051 }
7052 PlaybackThread::threadLoop_exit();
7053}
7054
7055// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007056bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007057{
7058 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007059 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007060
7061 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
7062 // after a timeout and we will enter standby then.
7063 if (mTracks.size() > 0) {
7064 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07007065 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07007066 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007067 }
7068
Eric Laurent5cff4032015-05-26 13:49:58 -07007069 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08007070}
7071
Andy Hungb17d24b2023-08-29 14:26:09 -07007072// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07007073bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007074 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007075{
7076 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007077 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007078
Eric Laurent10351942014-05-08 18:49:52 -07007079 AudioParameter param = AudioParameter(keyValuePair);
7080 int value;
7081 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007082 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007083 }
Eric Laurent10351942014-05-08 18:49:52 -07007084 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7085 // do not accept frame count changes if tracks are open as the track buffer
7086 // size depends on frame count and correct behavior would not be garantied
7087 // if frame count is changed after track creation
7088 if (!mTracks.isEmpty()) {
7089 status = INVALID_OPERATION;
7090 } else {
7091 reconfig = true;
7092 }
7093 }
7094 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007095 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007096 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007097 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007098 if (!mStandby) {
7099 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007100 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007101 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007102 }
Eric Laurent10351942014-05-08 18:49:52 -07007103 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007104 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007105 }
7106 if (status == NO_ERROR && reconfig) {
7107 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007108 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007109 }
7110 }
7111
Dean Wheatley68918102021-03-19 22:09:19 +11007112 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007113}
7114
Andy Hung4b17e882023-07-07 13:47:37 -07007115uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007116{
7117 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007118 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007119 time = PlaybackThread::activeSleepTimeUs();
7120 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007121 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007122 }
7123 return time;
7124}
7125
Andy Hung4b17e882023-07-07 13:47:37 -07007126uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007127{
7128 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007129 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007130 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7131 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007132 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007133 }
7134 return time;
7135}
7136
Andy Hung4b17e882023-07-07 13:47:37 -07007137uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007138{
7139 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007140 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007141 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7142 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007143 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007144 }
7145 return time;
7146}
7147
Andy Hung4b17e882023-07-07 13:47:37 -07007148void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007149{
7150 PlaybackThread::cacheParameters_l();
7151
7152 // use shorter standby delay as on normal output to release
7153 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007154 // no delay on outputs with HW A/V sync
7155 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007156 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007157 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007158 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007159 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007160 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007161 }
Eric Laurent81784c32012-11-19 14:55:58 -08007162}
7163
Andy Hung4b17e882023-07-07 13:47:37 -07007164void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007165{
ziyangch8f194f12021-12-01 13:48:04 -08007166 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007167 mOutput->flush();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007168 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007169 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007170 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007171 mMonotonicFrameCounter.onFlush();
Gareth Fenn5db373e2024-06-06 15:38:23 +00007172 // We do not reset mHwPaused which is hidden from the Track client.
7173 // Note: the client track in Tracks.cpp and AudioTrack.cpp
7174 // has a FLUSHED state but the DirectOutputThread does not;
7175 // those tracks will continue to show isStopped().
Eric Laurente659ef42014-09-29 13:06:46 -07007176}
7177
Andy Hung4b17e882023-07-07 13:47:37 -07007178int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007179 // If a VolumeShaper is active, we must wake up periodically to update volume.
7180 const int64_t NS_PER_MS = 1000000;
7181 return mVolumeShaperActive ?
7182 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7183}
7184
Eric Laurent81784c32012-11-19 14:55:58 -08007185// ----------------------------------------------------------------------------
7186
Andy Hung4b17e882023-07-07 13:47:37 -07007187AsyncCallbackThread::AsyncCallbackThread(
7188 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007189 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007190 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007191 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007192 mDrainSequence(0),
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007193 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007194{
7195}
7196
Andy Hung4b17e882023-07-07 13:47:37 -07007197void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007198{
7199 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7200}
7201
Andy Hung4b17e882023-07-07 13:47:37 -07007202bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007203{
7204 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007205 uint32_t writeAckSequence;
7206 uint32_t drainSequence;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007207 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007208
7209 {
Andy Hungb17d24b2023-08-29 14:26:09 -07007210 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007211 while (!((mWriteAckSequence & 1) ||
7212 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007213 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007214 exitPending())) {
Andy Hungb17d24b2023-08-29 14:26:09 -07007215 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007216 }
7217
Eric Laurentbfb1b832013-01-07 09:53:42 -08007218 if (exitPending()) {
7219 break;
7220 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007221 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7222 mWriteAckSequence, mDrainSequence);
7223 writeAckSequence = mWriteAckSequence;
7224 mWriteAckSequence &= ~1;
7225 drainSequence = mDrainSequence;
7226 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007227 asyncError = mAsyncError;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007228 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007229 }
7230 {
Andy Hung4b17e882023-07-07 13:47:37 -07007231 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007232 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007233 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007234 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007235 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007236 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007237 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007238 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007239 if (asyncError != ASYNC_ERROR_NONE) {
7240 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007241 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007242 }
7243 }
7244 }
7245 return false;
7246}
7247
Andy Hung4b17e882023-07-07 13:47:37 -07007248void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007249{
7250 ALOGV("AsyncCallbackThread::exit");
Andy Hungf8635b62023-08-31 16:13:39 -07007251 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007252 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -07007253 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007254}
7255
Andy Hung4b17e882023-07-07 13:47:37 -07007256void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007257{
Andy Hungf8635b62023-08-31 16:13:39 -07007258 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007259 // bit 0 is cleared
7260 mWriteAckSequence = sequence << 1;
7261}
7262
Andy Hung4b17e882023-07-07 13:47:37 -07007263void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007264{
Andy Hungf8635b62023-08-31 16:13:39 -07007265 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007266 // ignore unexpected callbacks
7267 if (mWriteAckSequence & 2) {
7268 mWriteAckSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007269 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007270 }
7271}
7272
Andy Hung4b17e882023-07-07 13:47:37 -07007273void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007274{
Andy Hungf8635b62023-08-31 16:13:39 -07007275 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007276 // bit 0 is cleared
7277 mDrainSequence = sequence << 1;
7278}
7279
Andy Hung4b17e882023-07-07 13:47:37 -07007280void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007281{
Andy Hungf8635b62023-08-31 16:13:39 -07007282 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007283 // ignore unexpected callbacks
7284 if (mDrainSequence & 2) {
7285 mDrainSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007286 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007287 }
7288}
7289
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007290void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007291{
Andy Hungf8635b62023-08-31 16:13:39 -07007292 audio_utils::lock_guard _l(mutex());
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007293 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungb17d24b2023-08-29 14:26:09 -07007294 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007295}
7296
Eric Laurentbfb1b832013-01-07 09:53:42 -08007297
7298// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007299
7300/* static */
7301sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007302 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007303 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7304 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007305 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007306}
7307
Andy Hung7535ed92023-07-17 17:05:00 -07007308OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007309 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7310 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007311 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007312 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007313{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007314 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007315 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007316 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007317}
7318
Andy Hung4b17e882023-07-07 13:47:37 -07007319void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007320{
7321 if (mFlushPending || mHwPaused) {
7322 // If a flush is pending or track was paused, just discard buffered data
Andy Hung94dfbb42023-09-06 19:41:47 -07007323 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007324 flushHw_l();
7325 } else {
7326 mMixerStatus = MIXER_DRAIN_ALL;
7327 threadLoop_drain();
7328 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007329 if (mUseAsyncWrite) {
7330 ALOG_ASSERT(mCallbackThread != 0);
7331 mCallbackThread->exit();
7332 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007333 PlaybackThread::threadLoop_exit();
7334}
7335
Andy Hung4b17e882023-07-07 13:47:37 -07007336PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007337 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007338)
7339{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007340 size_t count = mActiveTracks.size();
7341
7342 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007343 bool doHwPause = false;
7344 bool doHwResume = false;
7345
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007346 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007347
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007349 for (const sp<IAfTrack>& t : mActiveTracks) {
7350 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007351#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007352 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007353#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007354 // Only consider last track started for volume and mixer state control.
7355 // In theory an older track could underrun and restart after the new one starts
7356 // but as we only care about the transition phase between two tracks on a
7357 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007358 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007359 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007360
Haynes Mathew George7844f672014-01-15 12:32:55 -08007361 if (track->isInvalid()) {
7362 ALOGW("An invalidated track shouldn't be in active list");
7363 tracksToRemove->add(track);
7364 continue;
7365 }
7366
Andy Hung11e74242023-06-26 19:20:57 -07007367 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007368 ALOGW("An idle track shouldn't be in active list");
7369 continue;
7370 }
7371
Kuowei Li23666472021-01-20 10:23:25 +08007372 if (track->isPausePending()) {
7373 track->pauseAck();
7374 // It is possible a track might have been flushed or stopped.
7375 // Other operations such as flush pending might occur on the next prepare.
7376 if (track->isPausing()) {
7377 track->setPaused();
7378 }
7379 // Always perform pause if last, as an immediate flush will change
7380 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007382 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007383 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007384 mHwPaused = true;
7385 }
7386 // If we were part way through writing the mixbuffer to
7387 // the HAL we must save this until we resume
7388 // BUG - this will be wrong if a different track is made active,
7389 // in that case we want to discard the pending data in the
7390 // mixbuffer and tell the client to present it again when the
7391 // track is resumed
7392 mPausedWriteLength = mCurrentWriteLength;
7393 mPausedBytesRemaining = mBytesRemaining;
7394 mBytesRemaining = 0; // stop writing
7395 }
7396 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007397 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007398 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007399 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007400 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007401 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007402 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007403 track->flushAck();
7404 if (last) {
7405 mFlushPending = true;
7406 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007407 } else if (track->isResumePending()){
7408 track->resumeAck();
7409 if (last) {
7410 if (mPausedBytesRemaining) {
7411 // Need to continue write that was interrupted
7412 mCurrentWriteLength = mPausedWriteLength;
7413 mBytesRemaining = mPausedBytesRemaining;
7414 mPausedBytesRemaining = 0;
7415 }
7416 if (mHwPaused) {
7417 doHwResume = true;
7418 mHwPaused = false;
7419 // threadLoop_mix() will handle the case that we need to
7420 // resume an interrupted write
7421 }
7422 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007423 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007424
Eric Laurent3df841a2016-07-15 15:15:40 -07007425 mLeftVolFloat = mRightVolFloat = -1.0;
7426
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007427 // Do not handle new data in this iteration even if track->framesReady()
7428 mixerStatus = MIXER_TRACKS_ENABLED;
7429 }
7430 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007431 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007432 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007433 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7434 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007435 if (last) {
7436 // make sure processVolume_l() will apply new volume even if 0
7437 mLeftVolFloat = mRightVolFloat = -1.0;
7438 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007439 }
7440
7441 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007442 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007443 if (previousTrack != 0) {
7444 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007445 // Flush any data still being written from last track
7446 mBytesRemaining = 0;
7447 if (mPausedBytesRemaining) {
7448 // Last track was paused so we also need to flush saved
7449 // mixbuffer state and invalidate track so that it will
7450 // re-submit that unwritten data when it is next resumed
7451 mPausedBytesRemaining = 0;
7452 // Invalidate is a bit drastic - would be more efficient
7453 // to have a flag to tell client that some of the
7454 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007455 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007456 }
7457 // flush data already sent to the DSP if changing audio session as audio
7458 // comes from a different source. Also invalidate previous track to force a
7459 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007460 if (previousTrack->sessionId() != track->sessionId()) {
7461 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007462 }
7463 }
7464 }
7465 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007466 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007467 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007468 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007469 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007470 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007471 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007472 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007473 mixerStatus = MIXER_TRACKS_READY;
7474 }
7475 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007476 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007477 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007478 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007479 // Hardware buffer can hold a large amount of audio so we must
7480 // wait for all current track's data to drain before we say
7481 // that the track is stopped.
7482 if (mBytesRemaining == 0) {
7483 // Only start draining when all data in mixbuffer
7484 // has been written
7485 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007486 track->setState(IAfTrackBase::STOPPING_2);
7487 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007488 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7489 if (last && !mStandby) {
7490 // do not modify drain sequence if we are already draining. This happens
7491 // when resuming from pause after drain.
7492 if ((mDrainSequence & 1) == 0) {
7493 mSleepTimeUs = 0;
7494 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7495 mixerStatus = MIXER_DRAIN_TRACK;
7496 mDrainSequence += 2;
7497 }
7498 if (mHwPaused) {
7499 // It is possible to move from PAUSED to STOPPING_1 without
7500 // a resume so we must ensure hardware is running
7501 doHwResume = true;
7502 mHwPaused = false;
7503 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007504 }
7505 }
Eric Laurente93cc032016-05-05 10:15:10 -07007506 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007507 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007508 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007509 }
7510 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007511 // Drain has completed or we are in standby, signal presentation complete
7512 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007513 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007514 mOutput->presentationComplete();
7515 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007516 track->reset();
7517 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007518 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007519 if (!mUseAsyncWrite) {
7520 // If we don't get explicit drain notification we must
7521 // register discontinuity regardless of whether this is
7522 // the previous (!last) or the upcoming (last) track
7523 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007524 mTimestampVerifier.discontinuity(
7525 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007526 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007527 }
7528 } else {
7529 // No buffers for this track. Give it a few chances to
7530 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007531 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007532 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007533 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007534 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007535 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007536 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007537 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7538 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007539 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007540 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007541 // it will then automatically call start() when data is available
7542 track->disable();
7543 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007544 } else if (last){
7545 mixerStatus = MIXER_TRACKS_ENABLED;
7546 }
7547 }
7548 }
7549 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007550 if (track->isReady()) { // check ready to prevent premature start.
7551 processVolume_l(track, last);
7552 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007553 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007554
Eric Laurentea0fade2013-10-04 16:23:48 -07007555 // make sure the pause/flush/resume sequence is executed in the right order.
7556 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7557 // before flush and then resume HW. This can happen in case of pause/flush/resume
7558 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007559 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007560 status_t result = mOutput->stream->pause();
7561 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007562 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007563 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007564 if (mFlushPending) {
7565 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007566 }
Eric Laurentfd477972013-10-25 18:10:40 -07007567 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007568 status_t result = mOutput->stream->resume();
7569 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007570 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007571
Eric Laurentbfb1b832013-01-07 09:53:42 -08007572 // remove all the tracks that need to be...
7573 removeTracks_l(*tracksToRemove);
7574
7575 return mixerStatus;
7576}
7577
Eric Laurentbfb1b832013-01-07 09:53:42 -08007578// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007579bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007580{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007581 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7582 mWriteAckSequence, mDrainSequence);
7583 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007584 return true;
7585 }
7586 return false;
7587}
7588
Andy Hung4b17e882023-07-07 13:47:37 -07007589bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007590{
Andy Hungf8635b62023-08-31 16:13:39 -07007591 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007592 return waitingAsyncCallback_l();
7593}
7594
Andy Hung4b17e882023-07-07 13:47:37 -07007595void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007596{
Eric Laurente659ef42014-09-29 13:06:46 -07007597 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007598 // Flush anything still waiting in the mixbuffer
7599 mCurrentWriteLength = 0;
7600 mBytesRemaining = 0;
7601 mPausedWriteLength = 0;
7602 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007603 // reset bytes written count to reflect that DSP buffers are empty after flush.
7604 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007605
Eric Laurentbfb1b832013-01-07 09:53:42 -08007606 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007607 // discard any pending drain or write ack by incrementing sequence
7608 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7609 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007610 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007611 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7612 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007613 }
7614}
7615
Andy Hung4b17e882023-07-07 13:47:37 -07007616void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007617{
Andy Hungf8635b62023-08-31 16:13:39 -07007618 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007619 if (PlaybackThread::invalidateTracks_l(streamType)) {
7620 mFlushPending = true;
7621 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007622}
7623
Andy Hung4b17e882023-07-07 13:47:37 -07007624void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07007625 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007626 if (PlaybackThread::invalidateTracks_l(portIds)) {
7627 mFlushPending = true;
7628 }
7629}
7630
Eric Laurentbfb1b832013-01-07 09:53:42 -08007631// ----------------------------------------------------------------------------
7632
Andy Hung4b17e882023-07-07 13:47:37 -07007633/* static */
7634sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007635 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007636 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007637 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007638}
7639
Andy Hung7535ed92023-07-17 17:05:00 -07007640DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007641 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007642 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007643 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007644 mWaitTimeMs(UINT_MAX)
7645{
7646 addOutputTrack(mainThread);
7647}
7648
Andy Hung4b17e882023-07-07 13:47:37 -07007649DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007650{
7651 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7652 mOutputTracks[i]->destroy();
7653 }
7654}
7655
Andy Hung4b17e882023-07-07 13:47:37 -07007656void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007657{
7658 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007659 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007660 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007661 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007662 if (mMixerBufferValid) {
7663 memset(mMixerBuffer, 0, mMixerBufferSize);
7664 } else {
7665 memset(mSinkBuffer, 0, mSinkBufferSize);
7666 }
Eric Laurent81784c32012-11-19 14:55:58 -08007667 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007668 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007669 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007670 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007671 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007672}
7673
Andy Hung4b17e882023-07-07 13:47:37 -07007674void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007675{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007676 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007677 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007678 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007679 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007680 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007681 }
7682 } else if (mBytesWritten != 0) {
7683 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7684 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007685 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007686 } else {
7687 // flush remaining overflow buffers in output tracks
7688 writeFrames = 0;
7689 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007690 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007691 }
7692}
7693
Andy Hung4b17e882023-07-07 13:47:37 -07007694ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007695{
7696 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007697 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7698
7699 // Consider the first OutputTrack for timestamp and frame counting.
7700
7701 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7702 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7703 // we always claim success.
7704 if (i == 0) {
7705 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7706 ALOGD_IF(correction != 0 && writeFrames != 0,
7707 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7708 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7709 mFramesWritten -= correction;
7710 }
7711
7712 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007713 }
Andy Hungcf10d742020-04-28 15:38:24 -07007714 if (mStandby) {
7715 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007716 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007717 mStandby = false;
7718 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007719 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007720}
7721
Andy Hung4b17e882023-07-07 13:47:37 -07007722void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007723{
7724 // DuplicatingThread implements standby by stopping all tracks
7725 for (size_t i = 0; i < outputTracks.size(); i++) {
7726 outputTracks[i]->stop();
7727 }
7728}
7729
Andy Hung8a5abfd2023-12-07 19:35:12 -08007730void DuplicatingThread::threadLoop_exit()
7731{
7732 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7733 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7734 // Do so here in the threadLoop_exit().
7735
7736 SortedVector <sp<IAfOutputTrack>> localTracks;
7737 {
7738 audio_utils::lock_guard l(mutex());
7739 localTracks = std::move(mOutputTracks);
7740 mOutputTracks.clear();
7741 }
7742 localTracks.clear();
7743 outputTracks.clear();
7744 PlaybackThread::threadLoop_exit();
7745}
7746
Andy Hung4b17e882023-07-07 13:47:37 -07007747void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007748{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007749 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007750
7751 std::stringstream ss;
7752 const size_t numTracks = mOutputTracks.size();
7753 ss << " " << numTracks << " OutputTracks";
7754 if (numTracks > 0) {
7755 ss << ":";
7756 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007757 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007758 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007759 if (thread.get() != nullptr) {
7760 ss << thread.get() << ", " << thread->id();
7761 } else {
7762 ss << "null";
7763 }
7764 ss << ")";
7765 }
7766 }
7767 ss << "\n";
7768 std::string result = ss.str();
7769 write(fd, result.c_str(), result.size());
7770}
7771
Andy Hung4b17e882023-07-07 13:47:37 -07007772void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007773{
7774 outputTracks = mOutputTracks;
7775}
7776
Andy Hung4b17e882023-07-07 13:47:37 -07007777void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007778{
7779 outputTracks.clear();
7780}
7781
Andy Hung4b17e882023-07-07 13:47:37 -07007782void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007783{
Andy Hungf8635b62023-08-31 16:13:39 -07007784 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007785 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7786 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7787 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7788 const size_t frameCount =
7789 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7790 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7791 // from different OutputTracks and their associated MixerThreads (e.g. one may
7792 // nearly empty and the other may be dropping data).
7793
Svet Ganov33761132021-05-13 22:51:08 +00007794 // TODO b/182392769: use attribution source util, move to server edge
7795 AttributionSourceState attributionSource = AttributionSourceState();
7796 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007797 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007798 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007799 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007800 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007801 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007802 this,
7803 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007804 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007805 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007806 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007807 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007808 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7809 if (status != NO_ERROR) {
7810 ALOGE("addOutputTrack() initCheck failed %d", status);
7811 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007812 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007813 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7814 mOutputTracks.add(outputTrack);
7815 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7816 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007817}
7818
Andy Hung4b17e882023-07-07 13:47:37 -07007819void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007820{
Andy Hungf8635b62023-08-31 16:13:39 -07007821 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007822 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7823 if (mOutputTracks[i]->thread() == thread) {
7824 mOutputTracks[i]->destroy();
7825 mOutputTracks.removeAt(i);
7826 updateWaitTime_l();
Andy Hung160664b2023-09-15 18:19:28 -07007827 // NO_THREAD_SAFETY_ANALYSIS
7828 // Lambda workaround: as thread != this
7829 // we can safely call the remote thread getOutput.
7830 const bool equalOutput =
7831 [&](){ return thread->getOutput() == mOutput; }();
7832 if (equalOutput) {
7833 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007834 }
Eric Laurent81784c32012-11-19 14:55:58 -08007835 return;
7836 }
7837 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007838 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007839}
7840
Andy Hungb17d24b2023-08-29 14:26:09 -07007841// caller must hold mutex()
Andy Hung4b17e882023-07-07 13:47:37 -07007842void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007843{
7844 mWaitTimeMs = UINT_MAX;
7845 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007846 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007847 if (strong != 0) {
7848 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7849 if (waitTimeMs < mWaitTimeMs) {
7850 mWaitTimeMs = waitTimeMs;
7851 }
7852 }
7853 }
7854}
7855
Andy Hung4b17e882023-07-07 13:47:37 -07007856bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007857{
7858 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007859 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007860 if (thread == 0) {
7861 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7862 outputTracks[i].get());
7863 return false;
7864 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007865 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007866 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007867 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007868 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7869 thread.get());
7870 return false;
7871 }
7872 }
7873 return true;
7874}
7875
Andy Hung4b17e882023-07-07 13:47:37 -07007876void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007877 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007878{
Kevin Rocard12381092018-04-11 09:19:59 -07007879 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7880 outputTrack->setMetadatas(metadata.tracks);
7881 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007882}
7883
Andy Hung4b17e882023-07-07 13:47:37 -07007884uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007885{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007886 // return half the wait time in microseconds.
7887 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007888}
7889
Andy Hung4b17e882023-07-07 13:47:37 -07007890void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007891{
7892 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7893 updateWaitTime_l();
7894
7895 MixerThread::cacheParameters_l();
7896}
7897
Eric Laurentb3f315a2021-07-13 15:09:05 +02007898// ----------------------------------------------------------------------------
7899
Andy Hung4b17e882023-07-07 13:47:37 -07007900/* static */
7901sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007902 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007903 AudioStreamOut* output,
7904 audio_io_handle_t id,
7905 bool systemReady,
7906 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007907 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007908}
7909
Andy Hung7535ed92023-07-17 17:05:00 -07007910SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007911 AudioStreamOut* output,
7912 audio_io_handle_t id,
7913 bool systemReady,
7914 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007915 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007916{
7917}
7918
Andy Hung4b17e882023-07-07 13:47:37 -07007919void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007920 // if mSupportedLatencyModes is empty, the HAL stream does not support
7921 // latency mode control and we can exit.
7922 if (mSupportedLatencyModes.empty()) {
7923 return;
7924 }
7925 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7926 if (mSupportedLatencyModes.size() == 1) {
7927 // If the HAL only support one latency mode currently, confirm the choice
7928 latencyMode = mSupportedLatencyModes[0];
7929 } else if (mSupportedLatencyModes.size() > 1) {
7930 // Request low latency if:
7931 // - The low latency mode is requested by the spatializer controller
7932 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7933 // AND
7934 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007935 for (const auto& track : mActiveTracks) {
7936 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007937 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007938 break;
7939 }
7940 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007941 }
7942
7943 if (latencyMode != mSetLatencyMode) {
7944 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007945 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7946 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007947 if (status == NO_ERROR) {
7948 mSetLatencyMode = latencyMode;
7949 }
7950 }
7951}
7952
Andy Hung4b17e882023-07-07 13:47:37 -07007953status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01007954 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007955 return BAD_VALUE;
7956 }
Andy Hungf8635b62023-08-31 16:13:39 -07007957 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007958 mRequestedLatencyMode = mode;
7959 return NO_ERROR;
7960}
7961
Andy Hung4b17e882023-07-07 13:47:37 -07007962void SpatializerThread::checkOutputStageEffects()
Andy Hungf8635b62023-08-31 16:13:39 -07007963NO_THREAD_SAFETY_ANALYSIS
7964// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007965{
7966 bool hasVirtualizer = false;
7967 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007968 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007969 {
Andy Hungf8635b62023-08-31 16:13:39 -07007970 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007971 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007972 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007973 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007974 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7975 }
7976
7977 finalDownMixer = mFinalDownMixer;
7978 mFinalDownMixer.clear();
7979 }
7980
7981 if (hasVirtualizer) {
7982 if (finalDownMixer != nullptr) {
7983 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007984 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007985 }
7986 finalDownMixer.clear();
7987 } else if (!hasDownMixer) {
7988 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07007989 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007990 EFFECT_UIID_DOWNMIX, &descriptors);
7991 if (status != NO_ERROR) {
7992 return;
7993 }
7994 ALOG_ASSERT(!descriptors.empty(),
7995 "%s getDescriptors() returned no error but empty list", __func__);
7996
7997 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7998 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007999 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008000
8001 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8002 ALOGW("%s error creating downmixer %d", __func__, status);
8003 finalDownMixer.clear();
8004 } else {
8005 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008006 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008007 }
8008 }
8009
8010 {
Andy Hungf8635b62023-08-31 16:13:39 -07008011 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008012 mFinalDownMixer = finalDownMixer;
8013 }
8014}
8015
Andy Hunge2514462023-12-06 14:59:24 -08008016void SpatializerThread::threadLoop_exit()
8017{
8018 // The Spatializer EffectHandle must be released on the PlaybackThread
8019 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8020 mFinalDownMixer.clear();
8021
8022 PlaybackThread::threadLoop_exit();
8023}
8024
Eric Laurent81784c32012-11-19 14:55:58 -08008025// ----------------------------------------------------------------------------
8026// Record
8027// ----------------------------------------------------------------------------
8028
Andy Hung7535ed92023-07-17 17:05:00 -07008029sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07008030 AudioStreamIn* input,
8031 audio_io_handle_t id,
8032 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07008033 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07008034}
8035
Andy Hung7535ed92023-07-17 17:05:00 -07008036RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008037 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008038 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008039 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008040 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07008041 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008042 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008043 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008044 mActiveTracks(&this->mLocalLog),
8045 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008046 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008047 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008048 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8049 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008050 // mFastCapture below
8051 , mFastCaptureFutex(0)
8052 // mInputSource
8053 // mPipeSink
8054 // mPipeSource
8055 , mPipeFramesP2(0)
8056 // mPipeMemory
8057 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008058 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008059 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008060{
Glenn Kastend7dca052015-03-05 16:05:54 -08008061 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07008062 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008063
George Burgess IVa8f90c12020-05-14 11:27:19 -07008064 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008065 mIsMsdDevice = strcmp(
8066 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8067 }
8068
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008069 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008070
Andy Hungc8fddf32018-08-08 18:32:37 -07008071 // TODO: We may also match on address as well as device type for
8072 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008073 // TODO: This property should be ensure that only contains one single device type.
8074 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8075 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008076 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8077 : AUDIO_DEVICE_NONE));
8078
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008079 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008080 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008081 size_t numCounterOffers = 0;
8082 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008083#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008084 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008085#else
8086 (void)
8087#endif
8088 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008089 ALOG_ASSERT(index == 0);
8090
8091 // initialize fast capture depending on configuration
8092 bool initFastCapture;
8093 switch (kUseFastCapture) {
8094 case FastCapture_Never:
8095 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008096 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008097 break;
8098 case FastCapture_Always:
8099 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008100 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008101 break;
8102 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008103 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008104 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008105 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008106 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8107 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8108 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008109 break;
8110 // case FastCapture_Dynamic:
8111 }
8112
8113 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008114 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008115 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008116 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8117 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008118 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008119 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008120 const sp<MemoryDealer> roHeap(readOnlyHeap());
8121 sp<IMemory> pipeMemory;
8122 if ((roHeap == 0) ||
8123 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008124 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008125 ALOGE("not enough memory for pipe buffer size=%zu; "
8126 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8127 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8128 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008129 goto failed;
8130 }
8131 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8132 memset(pipeBuffer, 0, pipeSize);
8133 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008134 const NBAIO_Format offersFast[1] = {format};
8135 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008136 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008137 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008138 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008139 mPipeSink = pipe;
8140 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008141 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008142 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008143 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008144 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008145 mPipeSource = pipeReader;
8146 mPipeFramesP2 = pipeFramesP2;
8147 mPipeMemory = pipeMemory;
8148
8149 // create fast capture
8150 mFastCapture = new FastCapture();
8151 FastCaptureStateQueue *sq = mFastCapture->sq();
8152#ifdef STATE_QUEUE_DUMP
8153 // FIXME
8154#endif
8155 FastCaptureState *state = sq->begin();
8156 state->mCblk = NULL;
8157 state->mInputSource = mInputSource.get();
8158 state->mInputSourceGen++;
8159 state->mPipeSink = pipe;
8160 state->mPipeSinkGen++;
8161 state->mFrameCount = mFrameCount;
8162 state->mCommand = FastCaptureState::COLD_IDLE;
8163 // already done in constructor initialization list
8164 //mFastCaptureFutex = 0;
8165 state->mColdFutexAddr = &mFastCaptureFutex;
8166 state->mColdGen++;
8167 state->mDumpState = &mFastCaptureDumpState;
8168#ifdef TEE_SINK
8169 // FIXME
8170#endif
Andy Hung7535ed92023-07-17 17:05:00 -07008171 mFastCaptureNBLogWriter =
8172 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008173 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8174 sq->end();
8175 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8176
8177 // start the fast capture
8178 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8179 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008180 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008181 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008182#ifdef AUDIO_WATCHDOG
8183 // FIXME
8184#endif
8185
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008186 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008187 }
Andy Hung8946a282018-04-19 20:04:56 -07008188#ifdef TEE_SINK
8189 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8190 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8191#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008192failed: ;
8193
8194 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008195}
8196
Andy Hung4b17e882023-07-07 13:47:37 -07008197RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008198{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008199 if (mFastCapture != 0) {
8200 FastCaptureStateQueue *sq = mFastCapture->sq();
8201 FastCaptureState *state = sq->begin();
8202 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8203 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8204 if (old == -1) {
8205 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8206 }
8207 }
8208 state->mCommand = FastCaptureState::EXIT;
8209 sq->end();
8210 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8211 mFastCapture->join();
8212 mFastCapture.clear();
8213 }
Andy Hung7535ed92023-07-17 17:05:00 -07008214 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8215 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008216 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008217}
8218
Andy Hung4b17e882023-07-07 13:47:37 -07008219void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008220{
Glenn Kastend7dca052015-03-05 16:05:54 -08008221 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008222}
8223
Andy Hung4b17e882023-07-07 13:47:37 -07008224void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008225{
8226 ALOGV(" preExit()");
Andy Hungf8635b62023-08-31 16:13:39 -07008227 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008228 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008229 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008230 track->invalidate();
8231 }
8232 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008233 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008234}
8235
Andy Hung4b17e882023-07-07 13:47:37 -07008236bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008237{
Eric Laurent81784c32012-11-19 14:55:58 -08008238 nsecs_t lastWarning = 0;
8239
8240 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008241
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008242reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008243 {
Andy Hungf8635b62023-08-31 16:13:39 -07008244 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008245 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008246 }
8247
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008248 // used to request a deferred sleep, to be executed later while mutex is unlocked
8249 uint32_t sleepUs = 0;
8250
Andy Hung1381a072023-10-20 16:41:18 -07008251 // timestamp correction enable is determined under lock, used in processing step.
8252 bool timestampCorrectionEnabled = false;
8253
Andy Hung446f4df2019-02-21 12:26:41 -08008254 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8255
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008256 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008257 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungfdb84b92024-03-15 10:15:10 -07008258 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8259 sp<IAfRecordTrack> activeTrack;
Andy Hungb2b01c62024-04-23 13:56:19 -07008260 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008261 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008262
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008263 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008264 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008265
Glenn Kasten735f45f2014-08-18 15:51:59 -07008266 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008267 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008268
Glenn Kasten735f45f2014-08-18 15:51:59 -07008269 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008270 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008271
Eric Laurent33403f02020-05-29 18:35:06 -07008272 bool silenceFastCapture = false;
8273
Andy Hungb17d24b2023-08-29 14:26:09 -07008274 { // scope for mutex()
8275 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008276
Eric Laurent021cf962014-05-13 10:18:14 -07008277 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008278
Eric Laurent000a4192014-01-29 15:17:32 -08008279 // check exitPending here because checkForNewParameters_l() and
Andy Hungb17d24b2023-08-29 14:26:09 -07008280 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008281 if (exitPending()) {
8282 break;
8283 }
8284
Eric Laurent5c25d562016-07-13 17:17:45 -07008285 // sleep with mutex unlocked
8286 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008287 ATRACE_BEGIN("sleepC");
Andy Hungb17d24b2023-08-29 14:26:09 -07008288 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008289 ATRACE_END();
8290 sleepUs = 0;
8291 continue;
8292 }
8293
Glenn Kasten2b806402013-11-20 16:37:38 -08008294 // if no active track(s), then standby and release wakelock
8295 size_t size = mActiveTracks.size();
8296 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008297 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008298 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008299 releaseWakeLock_l();
8300 ALOGV("RecordThread: loop stopping");
8301 // go to sleep
Andy Hungb17d24b2023-08-29 14:26:09 -07008302 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008303 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008304 goto reacquire_wakelock;
8305 }
8306
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008307 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008308 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008309 for (size_t i = 0; i < size; ) {
Andy Hungb2b01c62024-04-23 13:56:19 -07008310 if (activeTrack) { // ensure track release is outside lock.
8311 oldActiveTracks.emplace_back(std::move(activeTrack));
8312 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008313 activeTrack = mActiveTracks[i];
8314 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008315 if (activeTrack->isFastTrack()) {
8316 ALOG_ASSERT(fastTrackToRemove == 0);
8317 fastTrackToRemove = activeTrack;
8318 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008319 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008320 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008321 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008322 continue;
8323 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008324
Andy Hung11e74242023-06-26 19:20:57 -07008325 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008326 switch (activeTrackState) {
8327
Andy Hung11e74242023-06-26 19:20:57 -07008328 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008329 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008330 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008331 if (activeTrack->isFastTrack()) {
8332 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8333 // Keep a ref on fast track to wait for FastCapture thread to get updated
8334 // state before potential track removal
8335 fastTrackToRemove = activeTrack;
8336 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008337 doBroadcast = true;
8338 size--;
8339 continue;
8340
Andy Hung11e74242023-06-26 19:20:57 -07008341 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008342 sleepUs = 10000;
8343 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008344 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008345 continue;
8346
Andy Hung11e74242023-06-26 19:20:57 -07008347 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008348 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008349 if (mStandby) {
8350 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008351 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008352 mStandby = false;
8353 }
Andy Hung11e74242023-06-26 19:20:57 -07008354 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008355 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008356 break;
8357
Andy Hung11e74242023-06-26 19:20:57 -07008358 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008359 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008360 break;
8361
Andy Hung11e74242023-06-26 19:20:57 -07008362 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8363 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8364 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008365 default:
Andy Hungce685402018-10-05 17:23:27 -07008366 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8367 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008368 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008369
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008370 if (activeTrack->isFastTrack()) {
8371 ALOG_ASSERT(!mFastTrackAvail);
8372 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008373 // if the active fast track is silenced either:
8374 // 1) silence the whole capture from fast capture buffer if this is
8375 // the only active track
8376 // 2) invalidate this track: this will cause the client to reconnect and possibly
8377 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008378 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008379 if (activeTrack->isSilenced()) {
8380 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008381 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008382 } else {
8383 silenceFastCapture = true;
8384 }
8385 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008386 // Invalidate fast tracks if access to audio history is required as this is not
8387 // possible with fast tracks. Once the fast track has been invalidated, no new
8388 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8389 if (mMaxSharedAudioHistoryMs != 0) {
8390 invalidate = true;
8391 }
8392 if (invalidate) {
8393 activeTrack->invalidate();
8394 ALOG_ASSERT(fastTrackToRemove == 0);
8395 fastTrackToRemove = activeTrack;
8396 removeTrack_l(activeTrack);
8397 mActiveTracks.remove(activeTrack);
8398 size--;
8399 continue;
8400 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008401 fastTrack = activeTrack;
8402 }
Eric Laurent33403f02020-05-29 18:35:06 -07008403
8404 activeTracks.add(activeTrack);
8405 i++;
8406
Glenn Kasten9e982352013-08-14 14:39:50 -07008407 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008408
Andy Hung94dfbb42023-09-06 19:41:47 -07008409 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008410
Kevin Rocard069c2712018-03-29 19:09:14 -07008411 updateMetadata_l();
8412
Eric Laurent5c25d562016-07-13 17:17:45 -07008413 if (allStopped) {
8414 standbyIfNotAlreadyInStandby();
8415 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008416 if (doBroadcast) {
Andy Hungb17d24b2023-08-29 14:26:09 -07008417 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008418 }
8419
8420 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008421 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008422 if (sleepUs == 0) {
8423 sleepUs = kRecordThreadSleepUs;
8424 }
8425 continue;
8426 }
8427 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008428
Andy Hung1381a072023-10-20 16:41:18 -07008429 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008430 lockEffectChains_l(effectChains);
8431 }
8432
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008433 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008434
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008435 size_t size = effectChains.size();
8436 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008437 // thread mutex is not locked, but effect chain is locked
8438 effectChains[i]->process_l();
8439 }
8440
Glenn Kasten735f45f2014-08-18 15:51:59 -07008441 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008442 if (mFastCapture != 0) {
8443 FastCaptureStateQueue *sq = mFastCapture->sq();
8444 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008445 bool didModify = false;
8446 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008447 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8448 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8449 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8450 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8451 if (old == -1) {
8452 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8453 }
8454 }
8455 state->mCommand = FastCaptureState::READ_WRITE;
8456#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008457 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008458 FastThreadDumpState::kSamplingNforLowRamDevice :
8459 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008460#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008461 didModify = true;
8462 }
8463 audio_track_cblk_t *cblkOld = state->mCblk;
8464 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8465 if (cblkNew != cblkOld) {
8466 state->mCblk = cblkNew;
8467 // block until acked if removing a fast track
8468 if (cblkOld != NULL) {
8469 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8470 }
8471 didModify = true;
8472 }
jiabin01c8f562018-07-19 17:47:28 -07008473 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8474 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8475 if (state->mFastPatchRecordBufferProvider != abp) {
8476 state->mFastPatchRecordBufferProvider = abp;
8477 state->mFastPatchRecordFormat = fastTrack == 0 ?
8478 AUDIO_FORMAT_INVALID : fastTrack->format();
8479 didModify = true;
8480 }
Eric Laurent33403f02020-05-29 18:35:06 -07008481 if (state->mSilenceCapture != silenceFastCapture) {
8482 state->mSilenceCapture = silenceFastCapture;
8483 didModify = true;
8484 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008485 sq->end(didModify);
8486 if (didModify) {
8487 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008488#if 0
8489 if (kUseFastCapture == FastCapture_Dynamic) {
8490 mNormalSource = mPipeSource;
8491 }
8492#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008493 }
8494 }
8495
Glenn Kasten735f45f2014-08-18 15:51:59 -07008496 // now run the fast track destructor with thread mutex unlocked
8497 fastTrackToRemove.clear();
8498
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008499 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8500 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8501 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8502 // If destination is non-contiguous, first read past the nominal end of buffer, then
8503 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008504
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008505 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008506 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008507 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008508
8509 // If an NBAIO source is present, use it to read the normal capture's data
8510 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008511 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008512
8513 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8514 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8515 // we immediately retry the read() to get data and prevent another overflow.
8516 for (int retries = 0; retries <= 2; ++retries) {
8517 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8518 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8519 framesToRead);
8520 if (framesRead != OVERRUN) break;
8521 }
8522
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008523 const ssize_t availableToRead = mPipeSource->availableToRead();
8524 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008525 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008526 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008527 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8528 "more frames to read than fifo size, %zd > %zu",
8529 availableToRead, mPipeFramesP2);
8530 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8531 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8532 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8533 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008534 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8535 }
8536 if (framesRead < 0) {
8537 status_t status = (status_t) framesRead;
8538 switch (status) {
8539 case OVERRUN:
8540 ALOGW("overrun on read from pipe");
8541 framesRead = 0;
8542 break;
8543 case NEGOTIATE:
8544 ALOGE("re-negotiation is needed");
8545 framesRead = -1; // Will cause an attempt to recover.
8546 break;
8547 default:
8548 ALOGE("unknown error %d on read from pipe", status);
8549 break;
8550 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008551 }
8552 // otherwise use the HAL / AudioStreamIn directly
8553 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008554 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008555 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008556 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008557 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008558 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008559 if (result < 0) {
8560 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008561 } else {
8562 framesRead = bytesRead / mFrameSize;
8563 }
8564 }
8565
Andy Hung446f4df2019-02-21 12:26:41 -08008566 const int64_t lastIoEndNs = systemTime(); // end IO timing
8567
Andy Hung3f0c9022016-01-15 17:49:46 -08008568 // Update server timestamp with server stats
8569 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008570 if (framesRead >= 0) {
8571 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8572 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8573 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008574
8575 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008576 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008577 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008578 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008579 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8580 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8581 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008582 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008583 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8584
8585 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hung94dfbb42023-09-06 19:41:47 -07008586 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008587 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008588 id(), (long long)time, (long long)position);
8589 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8590 position = correctedTimestamp.mFrames;
8591 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008592 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008593 id(), (long long)time, (long long)position);
8594 }
8595
Andy Hung3f0c9022016-01-15 17:49:46 -08008596 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8597 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8598 // Note: In general record buffers should tend to be empty in
8599 // a properly running pipeline.
8600 //
8601 // Also, it is not advantageous to call get_presentation_position during the read
8602 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008603 } else {
8604 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008605 }
8606 }
Andy Hunge6c37112019-02-26 17:38:10 -08008607
8608 // From the timestamp, input read latency is negative output write latency.
8609 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008610 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008611 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8612 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8613 mLatencyMs.add(latencyMs);
8614 }
8615
Andy Hung3f0c9022016-01-15 17:49:46 -08008616 // Use this to track timestamp information
8617 // ALOGD("%s", mTimestamp.toString().c_str());
8618
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008619 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008620 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008621 // Force input into standby so that it tries to recover at next read attempt
8622 inputStandBy();
8623 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008624 }
8625 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008626 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008627 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008628 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008629 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008630
Andy Hung8946a282018-04-19 20:04:56 -07008631#ifdef TEE_SINK
8632 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8633#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008634 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008635 {
8636 size_t part1 = mRsmpInFramesP2 - rear;
8637 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008638 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008639 (framesRead - part1) * mFrameSize);
8640 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008641 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008642 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008643
8644 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008645
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008646 // loop over each active track
8647 for (size_t i = 0; i < size; i++) {
8648 activeTrack = activeTracks[i];
8649
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008650 // skip fast tracks, as those are handled directly by FastCapture
8651 if (activeTrack->isFastTrack()) {
8652 continue;
8653 }
8654
Andy Hung73c02e42015-03-29 01:13:58 -07008655 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008656 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8657
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008658 enum {
8659 OVERRUN_UNKNOWN,
8660 OVERRUN_TRUE,
8661 OVERRUN_FALSE
8662 } overrun = OVERRUN_UNKNOWN;
8663
8664 // loop over getNextBuffer to handle circular sink
8665 for (;;) {
8666
Andy Hung11e74242023-06-26 19:20:57 -07008667 activeTrack->sinkBuffer().frameCount = ~0;
8668 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8669 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008670 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8671
Andy Hung73c02e42015-03-29 01:13:58 -07008672 // check available frames and handle overrun conditions
8673 // if the record track isn't draining fast enough.
8674 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008675 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008676 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008677 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008678 overrun = OVERRUN_TRUE;
8679 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008680 if (framesOut == 0 || framesIn == 0) {
8681 break;
8682 }
8683
Andy Hung6770c6f2015-04-07 13:43:36 -07008684 // Don't allow framesOut to be larger than what is possible with resampling
8685 // from framesIn.
8686 // This isn't strictly necessary but helps limit buffer resizing in
8687 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008688 if (audio_is_linear_pcm(activeTrack->format())) {
8689 framesOut = min(framesOut,
8690 destinationFramesPossible(
8691 framesIn, mSampleRate, activeTrack->sampleRate()));
8692 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008693
8694 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008695 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008696 // straight from RecordThread buffer to RecordTrack buffer.
8697 AudioBufferProvider::Buffer buffer;
8698 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008699 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008700 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008701 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008702 ALOGV_IF(buffer.frameCount != framesOut,
8703 "%s() read less than expected (%zu vs %zu)",
8704 __func__, buffer.frameCount, framesOut);
8705 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008706 memcpy(activeTrack->sinkBuffer().raw,
8707 buffer.raw, buffer.frameCount * mFrameSize);
8708 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008709 } else {
8710 framesOut = 0;
8711 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008712 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008713 }
8714 } else {
8715 // process frames from the RecordThread buffer provider to the RecordTrack
8716 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008717 framesOut = activeTrack->recordBufferConverter()->convert(
8718 activeTrack->sinkBuffer().raw,
8719 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008720 framesOut);
8721 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008722
8723 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8724 overrun = OVERRUN_FALSE;
8725 }
8726
Andy Hung93bb5732023-05-04 21:16:34 -07008727 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8728 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008729 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008730 if (framesToDrop == 0) {
8731 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008732 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008733 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008734 // Sanitize before releasing if the track has no access to the source data
8735 // An idle UID receives silence from non virtual devices until active
8736 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008737 memset(activeTrack->sinkBuffer().raw,
8738 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008739 }
Andy Hung11e74242023-06-26 19:20:57 -07008740 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008741 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008742 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008743 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008744 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008745 }
8746 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008747
8748 switch (overrun) {
8749 case OVERRUN_TRUE:
8750 // client isn't retrieving buffers fast enough
8751 if (!activeTrack->setOverflow()) {
8752 nsecs_t now = systemTime();
8753 // FIXME should lastWarning per track?
8754 if ((now - lastWarning) > kWarningThrottleNs) {
8755 ALOGW("RecordThread: buffer overflow");
8756 lastWarning = now;
8757 }
8758 }
8759 break;
8760 case OVERRUN_FALSE:
8761 activeTrack->clearOverflow();
8762 break;
8763 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008764 break;
8765 }
8766
Andy Hung3f0c9022016-01-15 17:49:46 -08008767 // update frame information and push timestamp out
8768 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008769 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008770 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8771 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008772 }
8773
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008774unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008775 // enable changes in effect chain
8776 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008777 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008778 if (audio_has_proportional_frames(mFormat)
8779 && loopCount == lastLoopCountRead + 1) {
8780 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8781 const double jitterMs =
8782 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8783 {framesRead, readPeriodNs},
8784 {0, 0} /* lastTimestamp */, mSampleRate);
8785 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8786
Andy Hungf8635b62023-08-31 16:13:39 -07008787 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008788 mIoJitterMs.add(jitterMs);
8789 mProcessTimeMs.add(processMs);
8790 }
8791 // update timing info.
8792 mLastIoBeginNs = lastIoBeginNs;
8793 mLastIoEndNs = lastIoEndNs;
8794 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008795 }
8796
Glenn Kasten93e471f2013-08-19 08:40:07 -07008797 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008798
8799 {
Andy Hungf8635b62023-08-31 16:13:39 -07008800 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008801 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008802 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008803 track->invalidate();
8804 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008805 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008806 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008807 }
8808
8809 releaseWakeLock();
8810
8811 ALOGV("RecordThread %p exiting", this);
8812 return false;
8813}
8814
Andy Hung4b17e882023-07-07 13:47:37 -07008815void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008816{
8817 if (!mStandby) {
8818 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008819 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008820 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008821 mStandby = true;
8822 }
8823}
8824
Andy Hung4b17e882023-07-07 13:47:37 -07008825void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008826{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008827 // Idle the fast capture if it's currently running
8828 if (mFastCapture != 0) {
8829 FastCaptureStateQueue *sq = mFastCapture->sq();
8830 FastCaptureState *state = sq->begin();
8831 if (!(state->mCommand & FastCaptureState::IDLE)) {
8832 state->mCommand = FastCaptureState::COLD_IDLE;
8833 state->mColdFutexAddr = &mFastCaptureFutex;
8834 state->mColdGen++;
8835 mFastCaptureFutex = 0;
8836 sq->end();
8837 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8838 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8839#if 0
8840 if (kUseFastCapture == FastCapture_Dynamic) {
8841 // FIXME
8842 }
8843#endif
8844#ifdef AUDIO_WATCHDOG
8845 // FIXME
8846#endif
8847 } else {
8848 sq->end(false /*didModify*/);
8849 }
8850 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008851 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008852 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008853
8854 // If going into standby, flush the pipe source.
8855 if (mPipeSource.get() != nullptr) {
8856 const ssize_t flushed = mPipeSource->flush();
8857 if (flushed > 0) {
8858 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8859 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8860 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8861 }
8862 }
Eric Laurent81784c32012-11-19 14:55:58 -08008863}
8864
Andy Hungb17d24b2023-08-29 14:26:09 -07008865// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07008866sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008867 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008868 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008869 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008870 audio_format_t format,
8871 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008872 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008873 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008874 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008875 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008876 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008877 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008878 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008879 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008880 audio_port_handle_t portId,
8881 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008882{
Glenn Kasten74935e42013-12-19 08:56:45 -08008883 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008884 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008885 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008886 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008887 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008888 audio_input_flags_t requestedFlags = *flags;
8889 uint32_t sampleRate;
8890
8891 lStatus = initCheck();
8892 if (lStatus != NO_ERROR) {
8893 ALOGE("createRecordTrack_l() audio driver not initialized");
8894 goto Exit;
8895 }
8896
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008897 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8898 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8899 lStatus = BAD_VALUE;
8900 goto Exit;
8901 }
8902
Eric Laurentec376dc2021-04-08 20:41:22 +02008903 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008904 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008905 lStatus = PERMISSION_DENIED;
8906 goto Exit;
8907 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008908 if (maxSharedAudioHistoryMs < 0
Andy Hung409572b2023-07-19 12:47:35 -07008909 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008910 lStatus = BAD_VALUE;
8911 goto Exit;
8912 }
8913 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008914 if (*pSampleRate == 0) {
8915 *pSampleRate = mSampleRate;
8916 }
8917 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008918
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008919 // special case for FAST flag considered OK if fast capture is present and access to
8920 // audio history is not required
8921 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008922 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8923 }
8924
Eric Laurentf14db3c2017-12-08 14:20:36 -08008925 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008926 if ((*flags & inputFlags) != *flags) {
8927 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8928 " input flags (%08x)",
8929 *flags, inputFlags);
8930 *flags = (audio_input_flags_t)(*flags & inputFlags);
8931 }
Eric Laurent81784c32012-11-19 14:55:58 -08008932
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008933 // client expresses a preference for FAST and no access to audio history,
8934 // but we get the final say
8935 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008936 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008937 // we formerly checked for a callback handler (non-0 tid),
8938 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008939 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008940 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008941 // Frame count is not specified (0), or is less than or equal the pipe depth.
8942 // It is OK to provide a higher capacity than requested.
8943 // We will force it to mPipeFramesP2 below.
8944 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008945 // PCM data
8946 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008947 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008948 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008949 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008950 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008951 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008952 hasFastCapture() &&
8953 // there are sufficient fast track slots available
8954 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008955 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008956 // check compatibility with audio effects.
Andy Hungf8635b62023-08-31 16:13:39 -07008957 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008958 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008959 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008960 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008961 audio_input_flags_t old = *flags;
8962 chain->checkInputFlagCompatibility(flags);
8963 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008964 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8965 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008966 }
8967 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008968 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008969 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8970 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008971 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008972 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8973 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008974 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008975 this, frameCount, mFrameCount, mPipeFramesP2,
8976 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008977 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008978 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008979 }
8980 }
8981
Eric Laurentf14db3c2017-12-08 14:20:36 -08008982 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8983 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8984 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8985 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8986 lStatus = BAD_TYPE;
8987 goto Exit;
8988 }
8989
Glenn Kasten74105912014-07-03 12:28:53 -07008990 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008991 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008992 // fast track: frame count is exactly the pipe depth
8993 frameCount = mPipeFramesP2;
8994 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008995 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008996 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008997 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8998 // or 20 ms if there is a fast capture
8999 // TODO This could be a roundupRatio inline, and const
9000 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9001 * sampleRate + mSampleRate - 1) / mSampleRate;
9002 // minimum number of notification periods is at least kMinNotifications,
9003 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9004 static const size_t kMinNotifications = 3;
9005 static const uint32_t kMinMs = 30;
9006 // TODO This could be a roundupRatio inline
9007 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9008 // TODO This could be a roundupRatio inline
9009 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9010 maxNotificationFrames;
9011 const size_t minFrameCount = maxNotificationFrames *
9012 max(kMinNotifications, minNotificationsByMs);
9013 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009014 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9015 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009016 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009017 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009018 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009019 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009020
Andy Hungb17d24b2023-08-29 14:26:09 -07009021 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07009022 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009023 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009024 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009025 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009026 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009027 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009028 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009029 }
Eric Laurent81784c32012-11-19 14:55:58 -08009030
Andy Hung11e74242023-06-26 19:20:57 -07009031 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009032 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009033 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07009034 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009035 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009036
Glenn Kasten03003332013-08-06 15:40:54 -07009037 lStatus = track->initCheck();
9038 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009039 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009040 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009041 goto Exit;
9042 }
9043 mTracks.add(track);
9044
Eric Laurent05067782016-06-01 18:27:28 -07009045 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009046 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9047 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9048 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009049 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009050 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009051
9052 if (maxSharedAudioHistoryMs != 0) {
9053 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9054 }
Eric Laurent81784c32012-11-19 14:55:58 -08009055 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009056
Eric Laurent81784c32012-11-19 14:55:58 -08009057 lStatus = NO_ERROR;
9058
9059Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009060 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009061 return track;
9062}
9063
Andy Hung4b17e882023-07-07 13:47:37 -07009064status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009065 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009066 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009067{
9068 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9069 sp<ThreadBase> strongMe = this;
9070 status_t status = NO_ERROR;
9071
9072 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009073 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009074 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07009075 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07009076 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009077 event, triggerSession,
9078 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009079 }
9080
9081 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009082 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hungf8635b62023-08-31 16:13:39 -07009083 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009084 if (recordTrack->isInvalid()) {
9085 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009086 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9087 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009088 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009089 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07009090 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009091 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9092 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009093 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07009094 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009095 } else {
Andy Hung11e74242023-06-26 19:20:57 -07009096 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009097 }
9098 return status;
9099 }
9100
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009101 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9102 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9103 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07009104 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009105 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009106 if (recordTrack->isExternalTrack()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009107 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009108 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07009109 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009110 if (recordTrack->isInvalid()) {
9111 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07009112 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9113 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009114 // STARTING_2 forces destroy to call stopInput.
9115 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009116 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9117 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009118 }
Andy Hung11e74242023-06-26 19:20:57 -07009119 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009120 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07009121 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009122 // Someone else has changed state, let them take over,
9123 // leave mState in the new state.
9124 recordTrack->clearSyncStartEvent();
9125 return INVALID_OPERATION;
9126 }
9127 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009128 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009129 ALOGW("%s(%d): startInput failed, status %d",
9130 __func__, recordTrack->id(), status);
9131 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9132 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009133 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009134 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009135 return status;
9136 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009137 sendIoConfigEvent_l(
9138 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009139 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009140
9141 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9142
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009143 // Catch up with current buffer indices if thread is already running.
9144 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9145 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9146 // see previously buffered data before it called start(), but with greater risk of overrun.
9147
Andy Hung11e74242023-06-26 19:20:57 -07009148 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009149 if (!recordTrack->isDirect()) {
9150 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07009151 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009152 }
Andy Hung11e74242023-06-26 19:20:57 -07009153 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009154 // signal thread to start
Andy Hungb17d24b2023-08-29 14:26:09 -07009155 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009156 return status;
9157 }
Eric Laurent81784c32012-11-19 14:55:58 -08009158}
9159
Andy Hung4b17e882023-07-07 13:47:37 -07009160void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009161{
Andy Hung4b17e882023-07-07 13:47:37 -07009162 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009163
9164 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07009165 sp<IAfTrackBase> ptr =
9166 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9167 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07009168 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07009169 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009170 }
Eric Laurent81784c32012-11-19 14:55:58 -08009171 }
9172}
9173
Andy Hung4b17e882023-07-07 13:47:37 -07009174bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009175 ALOGV("RecordThread::stop");
Andy Hungb17d24b2023-08-29 14:26:09 -07009176 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009177 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07009178 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009179 return false;
9180 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009181 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07009182 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009183
Andy Hungabfab202019-03-07 19:45:54 -08009184 // NOTE: Waiting here is important to keep stop synchronous.
9185 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07009186 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009187 mWaitWorkCV.notify_all(); // signal thread to stop
9188 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009189 }
Andy Hungce685402018-10-05 17:23:27 -07009190
Andy Hung11e74242023-06-26 19:20:57 -07009191 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009192 ALOGV("Record stopped OK");
9193 return true;
9194 }
Andy Hungce685402018-10-05 17:23:27 -07009195
9196 // don't handle anything - we've been invalidated or restarted and in a different state
9197 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07009198 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009199 return false;
9200}
9201
Andy Hung4b17e882023-07-07 13:47:37 -07009202bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009203{
9204 return false;
9205}
9206
Andy Hung4b17e882023-07-07 13:47:37 -07009207status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009208{
9209#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9210 if (!isValidSyncEvent(event)) {
9211 return BAD_VALUE;
9212 }
9213
Glenn Kastend848eb42016-03-08 13:42:11 -08009214 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009215 status_t ret = NAME_NOT_FOUND;
9216
Andy Hungf8635b62023-08-31 16:13:39 -07009217 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009218
9219 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009220 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009221 if (eventSession == track->sessionId()) {
9222 (void) track->setSyncEvent(event);
9223 ret = NO_ERROR;
9224 }
9225 }
9226 return ret;
9227#else
9228 return BAD_VALUE;
9229#endif
9230}
9231
Andy Hung4b17e882023-07-07 13:47:37 -07009232status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07009233 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009234{
9235 ALOGV("RecordThread::getActiveMicrophones");
Andy Hungf8635b62023-08-31 16:13:39 -07009236 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009237 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009238 return NO_INIT;
9239 }
jiabin9ff780e2018-03-19 18:19:52 -07009240 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9241 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009242}
9243
Andy Hung4b17e882023-07-07 13:47:37 -07009244status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009245 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009246{
Paul McLean12340082019-03-19 09:35:05 -06009247 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hungf8635b62023-08-31 16:13:39 -07009248 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009249 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009250 return NO_INIT;
9251 }
Paul McLean12340082019-03-19 09:35:05 -06009252 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009253}
9254
Andy Hung4b17e882023-07-07 13:47:37 -07009255status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009256{
Paul McLean12340082019-03-19 09:35:05 -06009257 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hungf8635b62023-08-31 16:13:39 -07009258 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009259 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009260 return NO_INIT;
9261 }
Paul McLean12340082019-03-19 09:35:05 -06009262 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009263}
9264
Andy Hung4b17e882023-07-07 13:47:37 -07009265status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009266 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9267 int64_t sharedAudioStartMs) {
Andy Hungf8635b62023-08-31 16:13:39 -07009268 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009269 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9270}
9271
Andy Hung4b17e882023-07-07 13:47:37 -07009272status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009273 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9274 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009275
Eric Laurentec376dc2021-04-08 20:41:22 +02009276 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9277 return BAD_VALUE;
9278 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009279
9280 if (sharedAudioStartMs < 0
9281 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009282 return BAD_VALUE;
9283 }
9284
Eric Laurent2407ce32021-04-26 14:56:03 +02009285 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9286 // As we cannot detect more than one wraparound, only accept values up current write position
9287 // after one wraparound
9288 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9289 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009290 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009291 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9292 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009293 // Bring the start frame position within the input buffer to match the documented
9294 // "best effort" behavior of the API.
9295 if (sharedOffset < 0) {
9296 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009297 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009298 sharedAudioStartFrames =
9299 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009300 }
9301
Eric Laurentec376dc2021-04-08 20:41:22 +02009302 mSharedAudioPackageName = sharedAudioPackageName;
9303 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009304 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009305 } else {
9306 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009307 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009308 }
9309 return NO_ERROR;
9310}
9311
Andy Hung4b17e882023-07-07 13:47:37 -07009312void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009313 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9314 mSharedAudioStartFrames = -1;
9315 mSharedAudioPackageName = "";
9316}
9317
Andy Hung4b17e882023-07-07 13:47:37 -07009318ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009319{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009320 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009321 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009322 }
9323 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009324 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009325 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009326 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009327 }
9328 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009329 MetadataUpdate change;
9330 change.recordMetadataUpdate = metadata.tracks;
9331 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009332}
9333
Andy Hungb17d24b2023-08-29 14:26:09 -07009334// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07009335void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009336{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009337 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009338 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009339
Eric Laurent81784c32012-11-19 14:55:58 -08009340 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009341 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009342 removeTrack_l(track);
9343 }
9344}
9345
Andy Hung4b17e882023-07-07 13:47:37 -07009346void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009347{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009348 String8 result;
9349 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009350 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009351
Eric Laurent81784c32012-11-19 14:55:58 -08009352 mTracks.remove(track);
9353 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009354 if (track->isFastTrack()) {
9355 ALOG_ASSERT(!mFastTrackAvail);
9356 mFastTrackAvail = true;
9357 }
Eric Laurent81784c32012-11-19 14:55:58 -08009358}
9359
Andy Hung4b17e882023-07-07 13:47:37 -07009360void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009361{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009362 AudioStreamIn *input = mInput;
9363 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9364 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009365 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009366 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009367 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009368 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009369 }
Andy Hungbfa64962017-06-12 14:43:19 -07009370
9371 if (input != nullptr) {
9372 dprintf(fd, " Hal stream dump:\n");
9373 (void)input->stream->dump(fd);
9374 }
9375
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009376 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009377 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009378
Glenn Kasten2f90c512015-12-02 11:40:09 -08009379 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9380 // while we are dumping it. It may be inconsistent, but it won't mutate!
9381 // This is a large object so we place it on the heap.
9382 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009383 const std::unique_ptr<FastCaptureDumpState> copy =
9384 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009385 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009386}
9387
Andy Hung4b17e882023-07-07 13:47:37 -07009388void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009389{
Eric Laurent81784c32012-11-19 14:55:58 -08009390 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009391 size_t numtracks = mTracks.size();
9392 size_t numactive = mActiveTracks.size();
9393 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009394 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009395 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009396 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009397 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009398 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009399 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009400 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009401 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009402 if (track != 0) {
9403 bool active = mActiveTracks.indexOf(track) >= 0;
9404 if (active) {
9405 numactiveseen++;
9406 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009407 result.append(prefix);
9408 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009409 }
Eric Laurent81784c32012-11-19 14:55:58 -08009410 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009411 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009412 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009413 }
9414
Marco Nelissenb2208842014-02-07 14:00:50 -08009415 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009416 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009417 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009418 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009419 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009420 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009421 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009422 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009423 result.append(prefix);
9424 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009425 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009426 }
Eric Laurent81784c32012-11-19 14:55:58 -08009427
9428 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009429 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009430}
9431
Andy Hung4b17e882023-07-07 13:47:37 -07009432void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009433{
Andy Hungf8635b62023-08-31 16:13:39 -07009434 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009435 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009436 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009437 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009438 track->setSilenced(silenced);
9439 }
9440 }
9441}
Andy Hung73c02e42015-03-29 01:13:58 -07009442
Andy Hung11e74242023-06-26 19:20:57 -07009443void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009444{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009445 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009446 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009447 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009448 const int32_t rear = recordThread->mRsmpInRear;
9449 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009450 if (mRecordTrack->startFrames() >= 0) {
9451 int32_t startFrames = mRecordTrack->startFrames();
9452 // Accept a recent wraparound of mRsmpInRear
9453 if (startFrames <= rear) {
9454 deltaFrames = rear - startFrames;
9455 } else {
9456 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009457 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009458 // start frame cannot be further in the past than start of resampling buffer
9459 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9460 deltaFrames = recordThread->mRsmpInFrames;
9461 }
9462 }
9463 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009464}
9465
Andy Hung11e74242023-06-26 19:20:57 -07009466void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009467 size_t *framesAvailable, bool *hasOverrun)
9468{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009469 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009470 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009471 const int32_t rear = recordThread->mRsmpInRear;
9472 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009473 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009474
9475 size_t framesIn;
9476 bool overrun = false;
9477 if (filled < 0) {
9478 // should not happen, but treat like a massive overrun and re-sync
9479 framesIn = 0;
9480 mRsmpInFront = rear;
9481 overrun = true;
9482 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9483 framesIn = (size_t) filled;
9484 } else {
9485 // client is not keeping up with server, but give it latest data
9486 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009487 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9488 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009489 overrun = true;
9490 }
9491 if (framesAvailable != NULL) {
9492 *framesAvailable = framesIn;
9493 }
9494 if (hasOverrun != NULL) {
9495 *hasOverrun = overrun;
9496 }
9497}
9498
Eric Laurent81784c32012-11-19 14:55:58 -08009499// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009500status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009501 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009502{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009503 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009504 if (threadBase == 0) {
9505 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009506 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009507 return NOT_ENOUGH_DATA;
9508 }
Andy Hung4b17e882023-07-07 13:47:37 -07009509 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009510 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009511 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009512 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009513 // FIXME should not be P2 (don't want to increase latency)
9514 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009515 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009516 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009517
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009518 front &= recordThread->mRsmpInFramesP2 - 1;
9519 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009520 if (part1 > (size_t) filled) {
9521 part1 = filled;
9522 }
9523 size_t ask = buffer->frameCount;
9524 ALOG_ASSERT(ask > 0);
9525 if (part1 > ask) {
9526 part1 = ask;
9527 }
9528 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009529 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009530 buffer->raw = NULL;
9531 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009532 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009533 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009534 }
9535
Andy Hung57446612015-04-19 23:56:46 -07009536 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009537 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009538 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009539 return NO_ERROR;
9540}
9541
9542// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009543void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009544 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009545{
Hongwei Wang95e37682019-04-12 11:13:36 -07009546 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009547 if (stepCount == 0) {
9548 return;
9549 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009550 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009551 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009552 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009553 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009554 buffer->frameCount = 0;
9555}
9556
Andy Hung4b17e882023-07-07 13:47:37 -07009557void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009558{
Andy Hungf8635b62023-08-31 16:13:39 -07009559 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009560 checkBtNrec_l();
9561}
9562
Andy Hung4b17e882023-07-07 13:47:37 -07009563void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009564{
9565 // disable AEC and NS if the device is a BT SCO headset supporting those
9566 // pre processings
Andy Hung94dfbb42023-09-06 19:41:47 -07009567 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009568 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009569 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9570 for (size_t i = 0; i < mEffectChains.size(); i++) {
9571 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9572 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9573 }
9574 }
9575}
9576
Andy Hung97a893e2015-03-29 01:03:07 -07009577
Andy Hung4b17e882023-07-07 13:47:37 -07009578bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009579 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009580{
9581 bool reconfig = false;
9582
Eric Laurent10351942014-05-08 18:49:52 -07009583 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009584
Eric Laurent10351942014-05-08 18:49:52 -07009585 audio_format_t reqFormat = mFormat;
9586 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009587 // 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 +08009588 [[maybe_unused]] audio_channel_mask_t channelMask =
9589 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009590
9591 AudioParameter param = AudioParameter(keyValuePair);
9592 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009593
9594 // scope for AutoPark extends to end of method
9595 AutoPark<FastCapture> park(mFastCapture);
9596
Eric Laurent10351942014-05-08 18:49:52 -07009597 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9598 // channel count change can be requested. Do we mandate the first client defines the
9599 // HAL sampling rate and channel count or do we allow changes on the fly?
9600 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9601 samplingRate = value;
9602 reconfig = true;
9603 }
9604 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009605 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009606 status = BAD_VALUE;
9607 } else {
9608 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009609 reconfig = true;
9610 }
Eric Laurent10351942014-05-08 18:49:52 -07009611 }
9612 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9613 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009614 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009615 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009616 status = BAD_VALUE;
9617 } else {
9618 channelMask = mask;
9619 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009620 }
Eric Laurent10351942014-05-08 18:49:52 -07009621 }
9622 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9623 // do not accept frame count changes if tracks are open as the track buffer
9624 // size depends on frame count and correct behavior would not be guaranteed
9625 // if frame count is changed after track creation
9626 if (mActiveTracks.size() > 0) {
9627 status = INVALID_OPERATION;
9628 } else {
9629 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009630 }
Eric Laurent10351942014-05-08 18:49:52 -07009631 }
9632 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009633 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009634 }
9635 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9636 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009637 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009638 }
Glenn Kastene198c362013-08-13 09:13:36 -07009639
Eric Laurent10351942014-05-08 18:49:52 -07009640 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009641 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009642 if (status == INVALID_OPERATION) {
9643 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009644 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009645 }
9646 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009647 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009648 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9649 if (mInput->stream->getAudioProperties(&config) == OK &&
9650 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9651 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009652 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009653 status = NO_ERROR;
9654 }
Eric Laurent81784c32012-11-19 14:55:58 -08009655 }
Eric Laurent10351942014-05-08 18:49:52 -07009656 if (status == NO_ERROR) {
9657 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009658 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009659 }
9660 }
Eric Laurent81784c32012-11-19 14:55:58 -08009661 }
Eric Laurent10351942014-05-08 18:49:52 -07009662
Eric Laurent81784c32012-11-19 14:55:58 -08009663 return reconfig;
9664}
9665
Andy Hung4b17e882023-07-07 13:47:37 -07009666String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009667{
Andy Hungf8635b62023-08-31 16:13:39 -07009668 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009669 if (initCheck() == NO_ERROR) {
9670 String8 out_s8;
9671 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9672 return out_s8;
9673 }
Eric Laurent81784c32012-11-19 14:55:58 -08009674 }
Andy Hung920f6572022-10-06 12:09:49 -07009675 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009676}
9677
Andy Hung94dfbb42023-09-06 19:41:47 -07009678void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009679 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009680 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009681 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009682 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009683 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009684 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009685 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9686 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009687 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009688 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009689 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009690 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009691 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009692 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009693 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009694 break;
9695 }
Andy Hung94dfbb42023-09-06 19:41:47 -07009696 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009697}
9698
Andy Hung4b17e882023-07-07 13:47:37 -07009699void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009700{
Dean Wheatley6c009512023-10-23 09:34:14 +11009701 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9702 mSampleRate = audioConfig.sample_rate;
9703 mChannelMask = audioConfig.channel_mask;
9704 if (!audio_is_input_channel(mChannelMask)) {
9705 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9706 }
9707
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009708 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009709
9710 // Get actual HAL format.
9711 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9712 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9713 // Get format from the shim, which will be different than the HAL format
9714 // if recording compressed audio from IEC61937 wrapped sources.
9715 mFormat = audioConfig.format;
9716 if (!audio_is_valid_format(mFormat)) {
9717 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9718 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009719 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009720 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9721 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009722 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009723 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009724 ALOGI("HAL format %#x is not linear pcm", mFormat);
9725 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009726 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009727 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9728 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009729 result = mInput->stream->getBufferSize(&mBufferSize);
9730 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009731 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009732 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9733 "mBufferSize=%zu, mFrameCount=%zu",
9734 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009735
Eric Laurentec376dc2021-04-08 20:41:22 +02009736 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9737 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009738 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009739
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009740 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9741 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009742
9743 audio_input_flags_t flags = mInput->flags;
9744 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9745 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07009746 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009747 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9748 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9749 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9750 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9751 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9752 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009753}
9754
Andy Hung4b17e882023-07-07 13:47:37 -07009755uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009756{
Andy Hungf8635b62023-08-31 16:13:39 -07009757 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009758 uint32_t result;
9759 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9760 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009761 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009762 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009763}
9764
Andy Hung4b17e882023-07-07 13:47:37 -07009765KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009766{
Glenn Kastend848eb42016-03-08 13:42:11 -08009767 KeyedVector<audio_session_t, bool> ids;
Andy Hungf8635b62023-08-31 16:13:39 -07009768 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009769 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009770 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009771 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009772 if (ids.indexOfKey(sessionId) < 0) {
9773 ids.add(sessionId, true);
9774 }
9775 }
9776 return ids;
9777}
9778
Andy Hung4b17e882023-07-07 13:47:37 -07009779AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009780{
Andy Hungf8635b62023-08-31 16:13:39 -07009781 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009782 AudioStreamIn *input = mInput;
9783 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009784 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009785 return input;
9786}
9787
Andy Hungb17d24b2023-08-29 14:26:09 -07009788// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009789sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009790{
9791 if (mInput == NULL) {
9792 return NULL;
9793 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009794 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009795}
9796
Andy Hung4b17e882023-07-07 13:47:37 -07009797status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009798{
Eric Laurent81784c32012-11-19 14:55:58 -08009799 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009800 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009801 chain->setInBuffer(NULL);
9802 chain->setOutBuffer(NULL);
9803
9804 checkSuspendOnAddEffectChain_l(chain);
9805
Eric Laurent1b928682014-10-02 19:41:47 -07009806 // make sure enabled pre processing effects state is communicated to the HAL as we
9807 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009808 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009809
Eric Laurent81784c32012-11-19 14:55:58 -08009810 mEffectChains.add(chain);
9811
9812 return NO_ERROR;
9813}
9814
Andy Hung4b17e882023-07-07 13:47:37 -07009815size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009816{
9817 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009818
9819 for (size_t i = 0; i < mEffectChains.size(); i++) {
9820 if (chain == mEffectChains[i]) {
9821 mEffectChains.removeAt(i);
9822 break;
9823 }
Eric Laurent81784c32012-11-19 14:55:58 -08009824 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009825 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009826}
9827
Andy Hung4b17e882023-07-07 13:47:37 -07009828status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009829 audio_patch_handle_t *handle)
9830{
9831 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009832
9833 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009834 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009835 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009836 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009837 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009838 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009839 }
9840
Eric Laurentd8365c52017-07-16 15:27:05 -07009841 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009842
9843 // store new source and send to effects
9844 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9845 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009846 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009847 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009848 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009849 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009850
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009851 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009852 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9853 status = hwDevice->createAudioPatch(patch->num_sources,
9854 patch->sources,
9855 patch->num_sinks,
9856 patch->sinks,
9857 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009858 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009859 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9860 patch->sinks[0].ext.mix.usecase.source,
9861 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009862 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009863 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009864
jiabinc52b1ff2019-10-31 17:20:42 -07009865 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009866 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009867 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009868 }
Eric Laurent296fb132015-05-01 11:38:42 -07009869
Andy Hungc2b11cb2020-04-22 09:04:01 -07009870 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009871 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009872 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009873 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009874 // also dispatch to active AudioRecords
9875 for (const auto &track : mActiveTracks) {
9876 track->logEndInterval();
9877 track->logBeginInterval(pathSourcesAsString);
9878 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009879 // Force meteadata update after a route change
9880 mActiveTracks.setHasChanged();
9881
Eric Laurent1c333e22014-05-20 10:48:17 -07009882 return status;
9883}
9884
Andy Hung4b17e882023-07-07 13:47:37 -07009885status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009886{
9887 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009888
jiabinc52b1ff2019-10-31 17:20:42 -07009889 mPatch = audio_patch{};
9890 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009891
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009892 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009893 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9894 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009895 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009896 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009897 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009898 // Force meteadata update after a route change
9899 mActiveTracks.setHasChanged();
9900
Eric Laurent1c333e22014-05-20 10:48:17 -07009901 return status;
9902}
9903
Andy Hung4b17e882023-07-07 13:47:37 -07009904void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009905{
Andy Hungf8635b62023-08-31 16:13:39 -07009906 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009907 mOutDevices = outDevices;
9908 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9909 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009910 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009911 }
9912}
9913
Andy Hung4b17e882023-07-07 13:47:37 -07009914int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009915{
9916 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009917 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009918 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009919 int32_t oldestFront = mRsmpInRear;
9920 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009921 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009922 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009923 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009924 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009925 if (filled > maxFilled) {
9926 oldestFront = front;
9927 maxFilled = filled;
9928 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009929 }
Andy Hung920f6572022-10-06 12:09:49 -07009930 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009931 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9932 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009933 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009934}
9935
Andy Hung4b17e882023-07-07 13:47:37 -07009936void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009937{
9938 if (offset == 0) {
9939 return;
9940 }
9941 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009942 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009943 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009944 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009945 }
9946}
9947
Andy Hung4b17e882023-07-07 13:47:37 -07009948void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009949{
9950 // This is the formula for calculating the temporary buffer size.
9951 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9952 // 1 full output buffer, regardless of the alignment of the available input.
9953 // The value is somewhat arbitrary, and could probably be even larger.
9954 // A larger value should allow more old data to be read after a track calls start(),
9955 // without increasing latency.
9956 //
9957 // Note this is independent of the maximum downsampling ratio permitted for capture.
9958 size_t minRsmpInFrames = mFrameCount * 7;
9959
9960 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9961 // capture history available to another client using the same session ID:
9962 // dimension the resampler input buffer accordingly.
9963
9964 // Get oldest client read position: getOldestFront_l() must be called before altering
9965 // mRsmpInRear, or mRsmpInFrames
9966 int32_t previousFront = getOldestFront_l();
9967 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9968 int32_t previousRear = mRsmpInRear;
9969 mRsmpInRear = 0;
9970
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009971 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009972 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009973 "resizeInputBuffer_l() called with invalid max shared history %d",
9974 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009975 if (maxSharedAudioHistoryMs != 0) {
9976 // resizeInputBuffer_l should never be called with a non zero shared history if the
9977 // buffer was not already allocated
9978 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9979 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9980 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9981 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009982 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009983 return;
9984 }
9985 mRsmpInFrames = rsmpInFrames;
9986 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009987 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009988 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9989 // initialized
9990 if (mRsmpInFrames < minRsmpInFrames) {
9991 mRsmpInFrames = minRsmpInFrames;
9992 }
9993 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9994
9995 // TODO optimize audio capture buffer sizes ...
9996 // Here we calculate the size of the sliding buffer used as a source
9997 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9998 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9999 // be better to have it derived from the pipe depth in the long term.
10000 // The current value is higher than necessary. However it should not add to latency.
10001
10002 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10003 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10004
10005 void *rsmpInBuffer;
10006 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10007 // if posix_memalign fails, will segv here.
10008 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10009
10010 // Copy audio history if any from old buffer before freeing it
10011 if (previousRear != 0) {
10012 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10013 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10014
10015 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10016 previousFront &= previousRsmpInFramesP2 - 1;
10017 size_t part1 = previousRsmpInFramesP2 - previousFront;
10018 if (part1 > (size_t) unread) {
10019 part1 = unread;
10020 }
10021 if (part1 != 0) {
10022 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10023 part1 * mFrameSize);
10024 mRsmpInRear = part1;
10025 part1 = unread - part1;
10026 if (part1 != 0) {
10027 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10028 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10029 mRsmpInRear += part1;
10030 }
10031 }
10032 // Update front for all clients according to new rear
10033 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10034 } else {
10035 mRsmpInRear = 0;
10036 }
10037 free(mRsmpInBuffer);
10038 mRsmpInBuffer = rsmpInBuffer;
10039}
10040
Andy Hung4b17e882023-07-07 13:47:37 -070010041void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010042{
Andy Hungf8635b62023-08-31 16:13:39 -070010043 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010044 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010045 if (record->getSource()) {
10046 mSource = record->getSource();
10047 }
Eric Laurent83b88082014-06-20 18:31:16 -070010048}
10049
Andy Hung4b17e882023-07-07 13:47:37 -070010050void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010051{
Andy Hungf8635b62023-08-31 16:13:39 -070010052 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010053 if (mSource == record->getSource()) {
10054 mSource = mInput;
10055 }
Eric Laurent83b88082014-06-20 18:31:16 -070010056 destroyTrack_l(record);
10057}
10058
Andy Hung4b17e882023-07-07 13:47:37 -070010059void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010060{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010061 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010062 config->role = AUDIO_PORT_ROLE_SINK;
10063 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10064 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010065 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10066 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10067 config->flags.input = mInput->flags;
10068 }
Eric Laurent83b88082014-06-20 18:31:16 -070010069}
Eric Laurent1c333e22014-05-20 10:48:17 -070010070
Eric Laurent6acd1d42017-01-04 14:23:29 -080010071// ----------------------------------------------------------------------------
10072// Mmap
10073// ----------------------------------------------------------------------------
10074
Andy Hung765de282023-07-07 15:58:48 -070010075// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10076// MmapPlaybackThread or MmapCaptureThread instance.
10077class MmapThreadHandle : public MmapStreamInterface {
10078public:
10079 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10080 ~MmapThreadHandle() override;
10081
10082 // MmapStreamInterface virtuals
10083 status_t createMmapBuffer(int32_t minSizeFrames,
10084 struct audio_mmap_buffer_info* info) final;
10085 status_t getMmapPosition(struct audio_mmap_position* position) final;
10086 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10087 status_t start(const AudioClient& client,
10088 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10089 status_t stop(audio_port_handle_t handle) final;
10090 status_t standby() final;
10091 status_t reportData(const void* buffer, size_t frameCount) final;
10092private:
10093 const sp<IAfMmapThread> mThread;
10094};
10095
10096/* static */
10097sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10098 const sp<IAfMmapThread>& mmapThread) {
10099 return sp<MmapThreadHandle>::make(mmapThread);
10100}
10101
10102MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010103 : mThread(thread)
10104{
Phil Burk9fabbf82017-08-03 12:02:00 -070010105 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106}
10107
Andy Hung765de282023-07-07 15:58:48 -070010108// MmapStreamInterface could be directly implemented by MmapThread excepting this
10109// special handling on adapter dtor.
10110MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010111{
Phil Burk9fabbf82017-08-03 12:02:00 -070010112 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010113}
10114
Andy Hung765de282023-07-07 15:58:48 -070010115status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116 struct audio_mmap_buffer_info *info)
10117{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010118 return mThread->createMmapBuffer(minSizeFrames, info);
10119}
10120
Andy Hung765de282023-07-07 15:58:48 -070010121status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010122{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010123 return mThread->getMmapPosition(position);
10124}
10125
Andy Hung765de282023-07-07 15:58:48 -070010126status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010127 int64_t *timeNanos) {
10128 return mThread->getExternalPosition(position, timeNanos);
10129}
10130
Andy Hung765de282023-07-07 15:58:48 -070010131status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010132 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010133{
jiabind1f1cb62020-03-24 11:57:57 -070010134 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010135}
10136
Andy Hung765de282023-07-07 15:58:48 -070010137status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010139 return mThread->stop(handle);
10140}
10141
Andy Hung765de282023-07-07 15:58:48 -070010142status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010143{
Eric Laurent18b57012017-02-13 16:23:52 -080010144 return mThread->standby();
10145}
10146
Andy Hung765de282023-07-07 15:58:48 -070010147status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10148{
jiabinfc791ee2023-02-15 19:43:40 +000010149 return mThread->reportData(buffer, frameCount);
10150}
10151
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152
Andy Hung4b17e882023-07-07 13:47:37 -070010153MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010154 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010155 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -070010156 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010157 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010158 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010159 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010160 mActiveTracks(&this->mLocalLog),
10161 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10162 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010163{
Eric Laurent18b57012017-02-13 16:23:52 -080010164 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 readHalParameters_l();
10166}
10167
Andy Hung4b17e882023-07-07 13:47:37 -070010168void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010169{
10170 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10171}
10172
Andy Hung4b17e882023-07-07 13:47:37 -070010173void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174{
Andy Hung11e74242023-06-26 19:20:57 -070010175 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010176 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010177 {
Andy Hungf8635b62023-08-31 16:13:39 -070010178 audio_utils::lock_guard _l(mutex());
Andy Hung11e74242023-06-26 19:20:57 -070010179 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010180 activeTracks.add(t);
10181 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010182 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010183 }
Andy Hung11e74242023-06-26 19:20:57 -070010184 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010185 stop(t->portId());
10186 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010187 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010188 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010189 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010190 } else {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010191 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010192 }
10193}
10194
10195
Andy Hung160664b2023-09-15 18:19:28 -070010196void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010197 audio_stream_type_t streamType __unused,
10198 audio_session_t sessionId,
10199 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010200 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201 audio_port_handle_t portId)
10202{
10203 mAttr = *attr;
10204 mSessionId = sessionId;
10205 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010206 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207 mPortId = portId;
10208}
10209
Andy Hung4b17e882023-07-07 13:47:37 -070010210status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010211 struct audio_mmap_buffer_info *info)
10212{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010213 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010214 if (mHalStream == 0) {
10215 return NO_INIT;
10216 }
Eric Laurent18b57012017-02-13 16:23:52 -080010217 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010218 return mHalStream->createMmapBuffer(minSizeFrames, info);
10219}
10220
Andy Hung4b17e882023-07-07 13:47:37 -070010221status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010222{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010223 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010224 if (mHalStream == 0) {
10225 return NO_INIT;
10226 }
10227 return mHalStream->getMmapPosition(position);
10228}
10229
Andy Hung4b17e882023-07-07 13:47:37 -070010230status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010231{
Eric Laurentdda206a2022-07-08 17:28:35 +020010232 // The HAL must receive track metadata before starting the stream
10233 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010234 status_t ret = mHalStream->start();
10235 if (ret != NO_ERROR) {
10236 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10237 return ret;
10238 }
Andy Hungcf10d742020-04-28 15:38:24 -070010239 if (mStandby) {
10240 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010241 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010242 mStandby = false;
10243 }
Eric Laurent331679c2018-04-16 17:03:16 -070010244 return NO_ERROR;
10245}
10246
Andy Hung4b17e882023-07-07 13:47:37 -070010247status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010248 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010249 audio_port_handle_t *handle)
10250{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010251 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010252 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010253 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010254 if (mHalStream == 0) {
10255 return NO_INIT;
10256 }
10257
10258 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010259
Eric Laurentdda206a2022-07-08 17:28:35 +020010260 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010261 if (*handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010262 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010263 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010264 }
10265
10266 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10267
10268 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010269 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010270 client.attributionSource);
10271
Andy Hungbcfd9e12023-09-19 14:48:41 -070010272 const auto localSessionId = mSessionId;
10273 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010274 if (isOutput()) {
10275 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10276 config.sample_rate = mSampleRate;
10277 config.channel_mask = mChannelMask;
10278 config.format = mFormat;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010279 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010280 audio_output_flags_t flags =
10281 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010282 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010283 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010284 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010285 bool isBitPerfect;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010286 mutex().unlock();
10287 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10288 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010289 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010290 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010291 &config,
10292 flags,
10293 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010294 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010295 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010296 &isSpatialized,
10297 &isBitPerfect);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010298 mutex().lock();
10299 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010300 ALOGD_IF(!secondaryOutputs.empty(),
10301 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010302 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010303 audio_config_base_t config;
10304 config.sample_rate = mSampleRate;
10305 config.channel_mask = mChannelMask;
10306 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010307 audio_port_handle_t deviceId = mDeviceId;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010308 mutex().unlock();
10309 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010310 RECORD_RIID_INVALID,
Andy Hungbcfd9e12023-09-19 14:48:41 -070010311 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010312 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010313 &config,
10314 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10315 &deviceId,
10316 &portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010317 mutex().lock();
10318 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010319 }
10320 // APM should not chose a different input or output stream for the same set of attributes
10321 // and audo configuration
10322 if (ret != NO_ERROR || io != mId) {
10323 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10324 __FUNCTION__, ret, io, mId);
10325 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010326 }
10327
10328 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010329 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010330 ret = AudioSystem::startOutput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010331 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332 } else {
jiabin09609032022-06-15 19:26:01 +000010333 {
10334 // Add the track record before starting input so that the silent status for the
10335 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010336 setClientSilencedState_l(portId, false /*silenced*/);
10337 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010338 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010339 ret = AudioSystem::startInput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010340 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010341 }
10342
10343 // abort if start is rejected by audio policy manager
10344 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010345 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010346 if (!mActiveTracks.isEmpty()) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010347 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010349 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010351 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010353 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010354 } else {
10355 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356 }
jiabin09609032022-06-15 19:26:01 +000010357 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010358 return PERMISSION_DENIED;
10359 }
10360
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010361 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010362 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10363 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010364 mChannelMask, mSessionId, isOutput(),
10365 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010366 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010367 if (!isOutput()) {
10368 track->setSilenced_l(isClientSilenced_l(portId));
10369 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010370
Eric Laurent4eb58f12018-12-07 16:41:02 -080010371 if (isOutput()) {
10372 // force volume update when a new track is added
10373 mHalVolFloat = -1.0f;
10374 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010375 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010376 if (t->isSilenced_l()
10377 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010378 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010379 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010380 }
10381 }
10382
Eric Laurent6acd1d42017-01-04 14:23:29 -080010383 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010384 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385 if (chain != 0) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010386 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010387 chain->incTrackCnt();
10388 chain->incActiveTrackCnt();
10389 }
10390
Andy Hungc2b11cb2020-04-22 09:04:01 -070010391 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010393
10394 if (mActiveTracks.size() == 1) {
10395 ret = exitStandby_l();
10396 }
10397
Eric Laurent6acd1d42017-01-04 14:23:29 -080010398 broadcast_l();
10399
Eric Laurentdda206a2022-07-08 17:28:35 +020010400 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401
Eric Laurentdda206a2022-07-08 17:28:35 +020010402 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010403}
10404
Andy Hung4b17e882023-07-07 13:47:37 -070010405status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010407 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010408 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010409
10410 if (mHalStream == 0) {
10411 return NO_INIT;
10412 }
10413
Eric Laurenta54f1282017-07-01 19:39:32 -070010414 if (handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010415 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010416 return NO_ERROR;
10417 }
10418
Andy Hung11e74242023-06-26 19:20:57 -070010419 sp<IAfMmapTrack> track;
10420 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421 if (handle == t->portId()) {
10422 track = t;
10423 break;
10424 }
10425 }
10426 if (track == 0) {
10427 return BAD_VALUE;
10428 }
10429
10430 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010431 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010432
Andy Hungb17d24b2023-08-29 14:26:09 -070010433 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010434 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010435 AudioSystem::stopOutput(track->portId());
10436 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010437 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010438 AudioSystem::stopInput(track->portId());
10439 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010440 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010441 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010442
Andy Hung116bc262023-06-20 18:56:17 -070010443 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 if (chain != 0) {
10445 chain->decActiveTrackCnt();
10446 chain->decTrackCnt();
10447 }
10448
Eric Laurentdda206a2022-07-08 17:28:35 +020010449 if (mActiveTracks.isEmpty()) {
10450 mHalStream->stop();
10451 }
10452
Eric Laurent6acd1d42017-01-04 14:23:29 -080010453 broadcast_l();
10454
Eric Laurent6acd1d42017-01-04 14:23:29 -080010455 return NO_ERROR;
10456}
10457
Andy Hung4b17e882023-07-07 13:47:37 -070010458status_t MmapThread::standby()
Andy Hungbcfd9e12023-09-19 14:48:41 -070010459NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010460{
10461 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010462 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010463
10464 if (mHalStream == 0) {
10465 return NO_INIT;
10466 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010467 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010468 return INVALID_OPERATION;
10469 }
10470 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010471 if (!mStandby) {
10472 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010473 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010474 mStandby = true;
10475 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010476 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010477 return NO_ERROR;
10478}
10479
Andy Hung4b17e882023-07-07 13:47:37 -070010480status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010481 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10482 return INVALID_OPERATION;
10483}
10484
Andy Hung4b17e882023-07-07 13:47:37 -070010485void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486{
10487 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10488 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10489 mFormat = mHALFormat;
10490 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10491 result = mHalStream->getFrameSize(&mFrameSize);
10492 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010493 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10494 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 result = mHalStream->getBufferSize(&mBufferSize);
10496 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10497 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010498
Andy Hungcf10d742020-04-28 15:38:24 -070010499 // TODO: make a readHalParameters call?
10500 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010501 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -070010502 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010503 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10504 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10505 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10506 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10507 /*
10508 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10509 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10510 (int32_t)mHapticChannelMask)
10511 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10512 (int32_t)mHapticChannelCount)
10513 */
10514 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -070010515 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010516 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10517 (int32_t)mFrameCount) // sic - added HAL
10518 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010519}
10520
Andy Hung4b17e882023-07-07 13:47:37 -070010521bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010522{
Andy Hung94dfbb42023-09-06 19:41:47 -070010523 {
10524 audio_utils::unique_lock _l(mutex());
10525 checkSilentMode_l();
10526 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010527
10528 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10529
10530 while (!exitPending())
10531 {
Andy Hung116bc262023-06-20 18:56:17 -070010532 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010533
Andy Hung13850be2019-03-14 11:33:09 -070010534 { // under Thread lock
Andy Hungb17d24b2023-08-29 14:26:09 -070010535 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010536
Eric Laurent6acd1d42017-01-04 14:23:29 -080010537 if (mSignalPending) {
10538 // A signal was raised while we were unlocked
10539 mSignalPending = false;
10540 } else {
10541 if (mConfigEvents.isEmpty()) {
10542 // we're about to wait, flush the binder command buffer
10543 IPCThreadState::self()->flushCommands();
10544
10545 if (exitPending()) {
10546 break;
10547 }
10548
Eric Laurent6acd1d42017-01-04 14:23:29 -080010549 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010550 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -070010551 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010552 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553
10554 checkSilentMode_l();
10555
10556 continue;
10557 }
10558 }
10559
10560 processConfigEvents_l();
10561
10562 processVolume_l();
10563
10564 checkInvalidTracks_l();
10565
Andy Hung94dfbb42023-09-06 19:41:47 -070010566 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567
Kevin Rocard069c2712018-03-29 19:09:14 -070010568 updateMetadata_l();
10569
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010571 } // release Thread lock
10572
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010574 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010575 }
Andy Hung13850be2019-03-14 11:33:09 -070010576
10577 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578 unlockEffectChains(effectChains);
10579 // Effect chains will be actually deleted here if they were removed from
10580 // mEffectChains list during mixing or effects processing
10581 }
10582
10583 threadLoop_exit();
10584
10585 if (!mStandby) {
10586 threadLoop_standby();
10587 mStandby = true;
10588 }
10589
Eric Laurent6acd1d42017-01-04 14:23:29 -080010590 ALOGV("Thread %p type %d exiting", this, mType);
10591 return false;
10592}
10593
Andy Hungb17d24b2023-08-29 14:26:09 -070010594// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070010595bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010596 status_t& status)
10597{
10598 AudioParameter param = AudioParameter(keyValuePair);
10599 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010600 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010601 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010602 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010604 if (sendToHal) {
10605 status = mHalStream->setParameters(keyValuePair);
10606 } else {
10607 status = NO_ERROR;
10608 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010609
10610 return false;
10611}
10612
Andy Hung4b17e882023-07-07 13:47:37 -070010613String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010614{
Andy Hungf8635b62023-08-31 16:13:39 -070010615 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616 String8 out_s8;
10617 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10618 return out_s8;
10619 }
Andy Hung920f6572022-10-06 12:09:49 -070010620 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621}
10622
Andy Hung94dfbb42023-09-06 19:41:47 -070010623void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010624 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010625 sp<AudioIoDescriptor> desc;
10626 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627 switch (event) {
10628 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010629 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010631 isInput = true;
10632 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010633 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010634 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010635 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010636 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10637 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010638 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010639 case AUDIO_INPUT_CLOSED:
10640 case AUDIO_OUTPUT_CLOSED:
10641 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010642 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010643 break;
10644 }
Andy Hung94dfbb42023-09-06 19:41:47 -070010645 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010646}
10647
Andy Hung4b17e882023-07-07 13:47:37 -070010648status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649 audio_patch_handle_t *handle)
Andy Hungb17d24b2023-08-29 14:26:09 -070010650NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010651{
10652 status_t status = NO_ERROR;
10653
10654 // store new device and send to effects
10655 audio_devices_t type = AUDIO_DEVICE_NONE;
10656 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010657 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10658 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10659 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660 if (isOutput()) {
10661 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010662 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10663 && !mAudioHwDev->supportsAudioPatches(),
10664 "Enumerated device type(%#x) must not be used "
10665 "as it does not support audio patches",
10666 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010667 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010668 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10669 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010670 }
10671 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010672 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010673 } else {
10674 type = patch->sources[0].ext.device.type;
10675 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010676 numDevices = mPatch.num_sources;
10677 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010678 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010679 }
10680
10681 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010682 if (isOutput()) {
10683 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10684 } else {
10685 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10686 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010687 }
10688
jiabinc52b1ff2019-10-31 17:20:42 -070010689 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010690 // store new source and send to effects
10691 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10692 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10693 for (size_t i = 0; i < mEffectChains.size(); i++) {
10694 mEffectChains[i]->setAudioSource_l(mAudioSource);
10695 }
10696 }
10697 }
10698
jiabin78b86f22024-02-22 00:39:29 +000010699 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10700 // okay to notify the client earlier before the new patch creation.
10701 if (mDeviceId != deviceId) {
10702 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10703 // The aaudioservice handle the routing changed event asynchronously. In that case,
10704 // it is safe to hold the lock here.
10705 callback->onRoutingChanged(deviceId);
10706 }
10707 }
10708
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010710 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10711 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010712 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010713 audio_port_config port;
10714 std::optional<audio_source_t> source;
10715 if (isOutput()) {
10716 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010717 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010718 port = patch->sources[0];
10719 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010720 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010721 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722 *handle = AUDIO_PATCH_HANDLE_NONE;
10723 }
10724
jiabinc52b1ff2019-10-31 17:20:42 -070010725 if (numDevices == 0 || mDeviceId != deviceId) {
10726 if (isOutput()) {
10727 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10728 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010729 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010730 } else {
10731 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10732 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10733 }
jiabinc52b1ff2019-10-31 17:20:42 -070010734 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010735 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010737 // Force meteadata update after a route change
10738 mActiveTracks.setHasChanged();
10739
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740 return status;
10741}
10742
Andy Hung4b17e882023-07-07 13:47:37 -070010743status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744{
10745 status_t status = NO_ERROR;
10746
jiabinc52b1ff2019-10-31 17:20:42 -070010747 mPatch = audio_patch{};
10748 mOutDeviceTypeAddrs.clear();
10749 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750
10751 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10752 supportsAudioPatches : false;
10753
10754 if (supportsAudioPatches) {
10755 status = mHalDevice->releaseAudioPatch(handle);
10756 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010757 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010758 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010759 // Force meteadata update after a route change
10760 mActiveTracks.setHasChanged();
10761
Eric Laurent6acd1d42017-01-04 14:23:29 -080010762 return status;
10763}
10764
Andy Hung4b17e882023-07-07 13:47:37 -070010765void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hungbcfd9e12023-09-19 14:48:41 -070010766NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010767{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010768 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010769 if (isOutput()) {
10770 config->role = AUDIO_PORT_ROLE_SOURCE;
10771 config->ext.mix.hw_module = mAudioHwDev->handle();
10772 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10773 } else {
10774 config->role = AUDIO_PORT_ROLE_SINK;
10775 config->ext.mix.hw_module = mAudioHwDev->handle();
10776 config->ext.mix.usecase.source = mAudioSource;
10777 }
10778}
10779
Andy Hung4b17e882023-07-07 13:47:37 -070010780status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010781{
10782 audio_session_t session = chain->sessionId();
10783
10784 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10785 // Attach all tracks with same session ID to this chain.
10786 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010787 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010788 if (session == track->sessionId()) {
10789 chain->incTrackCnt();
10790 chain->incActiveTrackCnt();
10791 }
10792 }
10793
10794 chain->setThread(this);
10795 chain->setInBuffer(nullptr);
10796 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010797 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798
10799 mEffectChains.add(chain);
10800 checkSuspendOnAddEffectChain_l(chain);
10801 return NO_ERROR;
10802}
10803
Andy Hung4b17e882023-07-07 13:47:37 -070010804size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010805{
10806 audio_session_t session = chain->sessionId();
10807
10808 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10809
10810 for (size_t i = 0; i < mEffectChains.size(); i++) {
10811 if (chain == mEffectChains[i]) {
10812 mEffectChains.removeAt(i);
10813 // detach all active tracks from the chain
10814 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010815 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010816 if (session == track->sessionId()) {
10817 chain->decActiveTrackCnt();
10818 chain->decTrackCnt();
10819 }
10820 }
10821 break;
10822 }
10823 }
10824 return mEffectChains.size();
10825}
10826
Andy Hung4b17e882023-07-07 13:47:37 -070010827void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010828{
10829 mHalStream->standby();
10830}
10831
Andy Hung4b17e882023-07-07 13:47:37 -070010832void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010833{
Phil Burk7dce7282017-09-27 13:51:41 -070010834 // Do not call callback->onTearDown() because it is redundant for thread exit
10835 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010836}
10837
Andy Hung4b17e882023-07-07 13:47:37 -070010838status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010839{
10840 return BAD_VALUE;
10841}
10842
Andy Hung4b17e882023-07-07 13:47:37 -070010843bool MmapThread::isValidSyncEvent(
10844 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010845{
10846 return false;
10847}
10848
Andy Hung4b17e882023-07-07 13:47:37 -070010849status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010850 const effect_descriptor_t *desc, audio_session_t sessionId)
10851{
10852 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010853 if (audio_is_global_session(sessionId)) {
10854 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010855 desc->name, mThreadName);
10856 return BAD_VALUE;
10857 }
10858
10859 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10860 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10861 desc->name);
10862 return BAD_VALUE;
10863 }
10864 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010865 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10866 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010867 return BAD_VALUE;
10868 }
10869
10870 // Only allow effects without processing load or latency
10871 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10872 return BAD_VALUE;
10873 }
10874
Andy Hung116bc262023-06-20 18:56:17 -070010875 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010876 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10877 return BAD_VALUE;
10878 }
10879
Eric Laurent6acd1d42017-01-04 14:23:29 -080010880 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010881}
10882
Andy Hung4b17e882023-07-07 13:47:37 -070010883void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010884{
Andy Hung11e74242023-06-26 19:20:57 -070010885 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010887 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10888 // The aaudioservice handle the routing changed event asynchronously. In that case,
10889 // it is safe to hold the lock here.
10890 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10891 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010892 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10893 mNoCallbackWarningCount++;
10894 }
10895 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010896 }
10897 }
10898}
10899
Andy Hung4b17e882023-07-07 13:47:37 -070010900void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010901{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010902 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10903 mAttr.content_type, mAttr.usage, mAttr.source);
10904 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010905 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010906 dprintf(fd, " No active clients\n");
10907 }
10908}
10909
Andy Hung4b17e882023-07-07 13:47:37 -070010910void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010911{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010913 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010914 dprintf(fd, " %zu Tracks\n", numtracks);
10915 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010916 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010917 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010918 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010919 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010920 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010921 result.append(prefix);
10922 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010923 }
10924 } else {
10925 dprintf(fd, "\n");
10926 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010927 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010928}
10929
Andy Hung4b17e882023-07-07 13:47:37 -070010930/* static */
10931sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010932 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010933 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010934 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010935}
10936
10937MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010938 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010939 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010940 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010941 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010942 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010943{
10944 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10945 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070010946 mMasterVolume = afThreadCallback->masterVolume_l();
10947 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent19611512023-07-03 18:14:07 +020010948
10949 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10950 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10951 mStreamTypes[stream].volume = 0.0f;
10952 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
10953 }
10954 // Audio patch and call assistant volume are always max
10955 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10956 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10957 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10958 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10959
Eric Laurent6acd1d42017-01-04 14:23:29 -080010960 if (mAudioHwDev) {
10961 if (mAudioHwDev->canSetMasterVolume()) {
10962 mMasterVolume = 1.0;
10963 }
10964
10965 if (mAudioHwDev->canSetMasterMute()) {
10966 mMasterMute = false;
10967 }
10968 }
10969}
10970
Andy Hung4b17e882023-07-07 13:47:37 -070010971void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010972 audio_stream_type_t streamType,
10973 audio_session_t sessionId,
10974 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010975 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010976 audio_port_handle_t portId)
10977{
Andy Hung160664b2023-09-15 18:19:28 -070010978 audio_utils::lock_guard l(mutex());
10979 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010980 mStreamType = streamType;
10981}
10982
Andy Hung4b17e882023-07-07 13:47:37 -070010983AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010984{
Andy Hungf8635b62023-08-31 16:13:39 -070010985 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010986 AudioStreamOut *output = mOutput;
10987 mOutput = NULL;
10988 return output;
10989}
10990
Andy Hung4b17e882023-07-07 13:47:37 -070010991void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010992{
Andy Hungf8635b62023-08-31 16:13:39 -070010993 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010994 // Don't apply master volume in SW if our HAL can do it for us.
10995 if (mAudioHwDev &&
10996 mAudioHwDev->canSetMasterVolume()) {
10997 mMasterVolume = 1.0;
10998 } else {
10999 mMasterVolume = value;
11000 }
11001}
11002
Andy Hung4b17e882023-07-07 13:47:37 -070011003void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011004{
Andy Hungf8635b62023-08-31 16:13:39 -070011005 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011006 // Don't apply master mute in SW if our HAL can do it for us.
11007 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11008 mMasterMute = false;
11009 } else {
11010 mMasterMute = muted;
11011 }
11012}
11013
Andy Hung4b17e882023-07-07 13:47:37 -070011014void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011015{
Andy Hungf8635b62023-08-31 16:13:39 -070011016 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011017 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011018 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011019 broadcast_l();
11020 }
11021}
11022
Andy Hung4b17e882023-07-07 13:47:37 -070011023float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011024{
Andy Hungf8635b62023-08-31 16:13:39 -070011025 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011026 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011027}
11028
Andy Hung4b17e882023-07-07 13:47:37 -070011029void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011030{
Andy Hungf8635b62023-08-31 16:13:39 -070011031 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011032 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011034 broadcast_l();
11035 }
11036}
11037
Andy Hung4b17e882023-07-07 13:47:37 -070011038void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011039{
Andy Hungf8635b62023-08-31 16:13:39 -070011040 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011041 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070011042 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 track->invalidate();
11044 }
11045 broadcast_l();
11046 }
11047}
11048
Andy Hung4b17e882023-07-07 13:47:37 -070011049void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011050{
Andy Hungf8635b62023-08-31 16:13:39 -070011051 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011052 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070011053 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011054 if (portIds.find(track->portId()) != portIds.end()) {
11055 track->invalidate();
11056 trackMatch = true;
11057 portIds.erase(track->portId());
11058 }
11059 if (portIds.empty()) {
11060 break;
11061 }
11062 }
11063 if (trackMatch) {
11064 broadcast_l();
11065 }
11066}
11067
Andy Hung4b17e882023-07-07 13:47:37 -070011068void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011069NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011070{
11071 float volume;
11072
Eric Laurent19611512023-07-03 18:14:07 +020011073 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011074 volume = 0;
11075 } else {
Eric Laurent19611512023-07-03 18:14:07 +020011076 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077 }
11078
11079 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011080 // Convert volumes from float to 8.24
11081 uint32_t vol = (uint32_t)(volume * (1 << 24));
11082
11083 // Delegate volume control to effect in track effect chain if needed
11084 // only one effect chain can be present on DirectOutputThread, so if
11085 // there is one, the track is connected to it
11086 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011087 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011088 volume = (float)vol / (1 << 24);
11089 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011090 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011091 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11092 mHalVolFloat = volume; // HW volume control worked, so update value.
11093 mNoCallbackWarningCount = 0;
11094 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011095 sp<MmapStreamCallback> callback = mCallback.promote();
11096 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011097 mHalVolFloat = volume; // SW volume control worked, so update value.
11098 mNoCallbackWarningCount = 0;
Andy Hungb17d24b2023-08-29 14:26:09 -070011099 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011100 callback->onVolumeChanged(volume);
Andy Hungb17d24b2023-08-29 14:26:09 -070011101 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011102 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011103 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11104 ALOGW("Could not set MMAP stream volume: no volume callback!");
11105 mNoCallbackWarningCount++;
11106 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011107 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011108 }
Andy Hung11e74242023-06-26 19:20:57 -070011109 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011110 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070011111 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011112 /*muteState=*/{mMasterMute,
Eric Laurent19611512023-07-03 18:14:07 +020011113 streamVolume_l() == 0.f,
11114 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011115 // TODO(b/241533526): adjust logic to include mute from AppOps
11116 false /*muteFromPlaybackRestricted*/,
11117 false /*muteFromClientVolume*/,
11118 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011119 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011120 }
11121}
11122
Andy Hung4b17e882023-07-07 13:47:37 -070011123ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011124{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011125 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011126 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011127 }
11128 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011129 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011130 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011131 playback_track_metadata_v7_t trackMetadata;
11132 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011133 .usage = track->attributes().usage,
11134 .content_type = track->attributes().content_type,
11135 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011136 };
11137 trackMetadata.channel_mask = track->channelMask(),
11138 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11139 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011140 }
11141 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011142
11143 MetadataUpdate change;
11144 change.playbackMetadataUpdate = metadata.tracks;
11145 return change;
11146};
Kevin Rocard069c2712018-03-29 19:09:14 -070011147
Andy Hung4b17e882023-07-07 13:47:37 -070011148void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011149{
11150 if (!mMasterMute) {
11151 char value[PROPERTY_VALUE_MAX];
11152 if (property_get("ro.audio.silent", value, "0") > 0) {
11153 char *endptr;
11154 unsigned long ul = strtoul(value, &endptr, 0);
11155 if (*endptr == '\0' && ul != 0) {
Andy Hung6fb26892024-02-20 16:32:57 -080011156 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011157 // The setprop command will not allow a property to be changed after
11158 // the first time it is set, so we don't have to worry about un-muting.
11159 setMasterMute_l(true);
11160 }
11161 }
11162 }
11163}
11164
Andy Hung4b17e882023-07-07 13:47:37 -070011165void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011166{
11167 MmapThread::toAudioPortConfig(config);
11168 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11169 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11170 config->flags.output = mOutput->flags;
11171 }
11172}
11173
Andy Hung4b17e882023-07-07 13:47:37 -070011174status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070011175 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011176{
11177 if (mOutput == nullptr) {
11178 return NO_INIT;
11179 }
11180 struct timespec timestamp;
11181 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11182 if (status == NO_ERROR) {
11183 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11184 }
11185 return status;
11186}
11187
Andy Hung4b17e882023-07-07 13:47:37 -070011188status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011189 // Send to MelProcessor for sound dose measurement.
11190 auto processor = mMelProcessor.load();
11191 if (processor) {
11192 processor->process(buffer, frameCount * mFrameSize);
11193 }
11194
jiabinfc791ee2023-02-15 19:43:40 +000011195 return NO_ERROR;
11196}
11197
Andy Hungb17d24b2023-08-29 14:26:09 -070011198// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011199void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011200 const sp<audio_utils::MelProcessor>& processor)
11201{
11202 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011203 mMelProcessor.store(processor);
11204 if (processor) {
11205 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011206 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011207
11208 // no need to update output format for MMapPlaybackThread since it is
11209 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011210}
11211
Andy Hungb17d24b2023-08-29 14:26:09 -070011212// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011213void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011214{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011215 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11216 auto melProcessor = mMelProcessor.load();
11217 if (melProcessor != nullptr) {
11218 melProcessor->pause();
11219 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011220}
11221
Andy Hung4b17e882023-07-07 13:47:37 -070011222void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011223{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011224 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011225
Glenn Kastend3bb6452016-12-05 18:14:37 -080011226 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent19611512023-07-03 18:14:07 +020011227 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011228 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11229}
11230
Andy Hung4b17e882023-07-07 13:47:37 -070011231/* static */
11232sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070011233 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070011234 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011235 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011236}
11237
11238MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011239 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011240 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011241 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011242 mInput(input)
11243{
11244 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11245 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11246}
11247
Andy Hung4b17e882023-07-07 13:47:37 -070011248status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011249{
Phil Burkf054fc32018-12-06 09:45:59 -080011250 {
11251 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011252 if (mInput != nullptr && mInput->stream != nullptr) {
11253 mInput->stream->setGain(1.0f);
11254 }
11255 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011256 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011257}
11258
Andy Hung4b17e882023-07-07 13:47:37 -070011259AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011260{
Andy Hungf8635b62023-08-31 16:13:39 -070011261 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011262 AudioStreamIn *input = mInput;
11263 mInput = NULL;
11264 return input;
11265}
Kevin Rocard069c2712018-03-29 19:09:14 -070011266
Andy Hung4b17e882023-07-07 13:47:37 -070011267void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011268{
11269 bool changed = false;
11270 bool silenced = false;
11271
11272 sp<MmapStreamCallback> callback = mCallback.promote();
11273 if (callback == 0) {
11274 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11275 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11276 mNoCallbackWarningCount++;
11277 }
11278 }
11279
11280 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11281 // track is silenced and unmute otherwise
11282 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11283 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11284 changed = true;
11285 silenced = mActiveTracks[i]->isSilenced_l();
11286 }
11287 }
11288
11289 if (changed) {
11290 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11291 }
11292}
11293
Andy Hung4b17e882023-07-07 13:47:37 -070011294ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011295{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011296 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011297 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011298 }
11299 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011300 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011301 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011302 record_track_metadata_v7_t trackMetadata;
11303 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011304 .source = track->attributes().source,
11305 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011306 };
11307 trackMetadata.channel_mask = track->channelMask(),
11308 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11309 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011310 }
11311 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011312 MetadataUpdate change;
11313 change.recordMetadataUpdate = metadata.tracks;
11314 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011315}
11316
Andy Hung4b17e882023-07-07 13:47:37 -070011317void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011318{
Andy Hungf8635b62023-08-31 16:13:39 -070011319 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011320 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011321 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011322 mActiveTracks[i]->setSilenced_l(silenced);
11323 broadcast_l();
11324 }
11325 }
jiabin09609032022-06-15 19:26:01 +000011326 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011327}
11328
Andy Hung4b17e882023-07-07 13:47:37 -070011329void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011330{
11331 MmapThread::toAudioPortConfig(config);
11332 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11333 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11334 config->flags.input = mInput->flags;
11335 }
11336}
11337
Andy Hung4b17e882023-07-07 13:47:37 -070011338status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011339 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011340{
11341 if (mInput == nullptr) {
11342 return NO_INIT;
11343 }
11344 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11345}
11346
jiabinc658e452022-10-21 20:52:21 +000011347// ----------------------------------------------------------------------------
11348
Andy Hung4b17e882023-07-07 13:47:37 -070011349/* static */
11350sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011351 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011352 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011353 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011354}
11355
Andy Hung7535ed92023-07-17 17:05:00 -070011356BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011357 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011358 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011359
Andy Hung4b17e882023-07-07 13:47:37 -070011360PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011361 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011362 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11363 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011364 float volumeLeft = 1.0f;
11365 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011366 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11367 const int trackId = mActiveTracks[0]->id();
11368 mAudioMixer->setParameter(
11369 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11370 mAudioMixer->setParameter(
11371 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11372 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011373 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011374 mIsBitPerfect = true;
11375 } else {
11376 mIsBitPerfect = false;
11377 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11378 // active.
11379 for (const auto& track : mActiveTracks) {
11380 const int trackId = track->id();
11381 mAudioMixer->setParameter(
11382 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11383 }
11384 }
jiabin76d94692022-12-15 21:51:21 +000011385 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11386 mVolumeLeft = volumeLeft;
11387 mVolumeRight = volumeRight;
11388 setVolumeForOutput_l(volumeLeft, volumeRight);
11389 }
jiabinc658e452022-10-21 20:52:21 +000011390 return result;
11391}
11392
Andy Hung4b17e882023-07-07 13:47:37 -070011393void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011394 MixerThread::threadLoop_mix();
11395 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11396}
11397
Glenn Kasten63238ef2015-03-02 15:50:29 -080011398} // namespace android