blob: fd5d5fc6ce7be37f0f23e810f6c0b4b65924fcf4 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Andy Hung25a80ac2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
36#ifdef DEBUG_CPU_USAGE
37#include <audio_utils/Statistics.h>
38#include <cpustats/ThreadCpuUsage.h>
39#endif
40#include <audio_utils/channels.h>
41#include <audio_utils/format.h>
42#include <audio_utils/minifloat.h>
43#include <audio_utils/mono_blend.h>
44#include <audio_utils/primitives.h>
45#include <audio_utils/safe_math.h>
46#include <audiomanager/AudioManager.h>
47#include <binder/IPCThreadState.h>
48#include <binder/IServiceManager.h>
49#include <binder/PersistableBundle.h>
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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hung25a80ac2023-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 Hungee58e4a2023-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 Hung25a80ac2023-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 Hung25a80ac2023-07-19 12:47:35 -0700249static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-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 Hung81994d62023-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 Hung25a80ac2023-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 Wasilczyk833345b2023-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 Hungee58e4a2023-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 Hung583043b2023-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 Hung583043b2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungc5007f82023-08-29 14:26:09 -0700691 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800692 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700693 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800694 }
695 // When Thread::requestExitAndWait is made virtual and this method is renamed to
696 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700697
698 // For TimeCheck: track waiting on the thread join of getTid().
699 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
700
Eric Laurent81784c32012-11-19 14:55:58 -0800701 requestExitAndWait();
702}
703
Andy Hungee58e4a2023-07-07 13:47:37 -0700704status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800705{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000706 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700707 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800708
Eric Laurent10351942014-05-08 18:49:52 -0700709 return sendSetParameterConfigEvent_l(keyValuePairs);
710}
711
712// sendConfigEvent_l() must be called with ThreadBase::mLock held
713// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700714status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700715NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700716{
717 status_t status = NO_ERROR;
718
Eric Laurent72e3f392015-05-20 14:43:50 -0700719 if (event->mRequiresSystemReady && !mSystemReady) {
720 event->mWaitStatus = false;
721 mPendingConfigEvents.add(event);
722 return status;
723 }
Eric Laurent10351942014-05-08 18:49:52 -0700724 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700725 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700726 mWaitWorkCV.notify_one();
727 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700728 {
Andy Hungc5007f82023-08-29 14:26:09 -0700729 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700730 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800731 if (event->mCondition.wait_for(
732 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
733 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700734 event->mStatus = TIMED_OUT;
735 event->mWaitStatus = false;
736 }
737 }
738 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800739 }
Andy Hungc5007f82023-08-29 14:26:09 -0700740 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800741 return status;
742}
743
Andy Hungee58e4a2023-07-07 13:47:37 -0700744void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700745 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800746{
Andy Hung972bec12023-08-31 16:13:39 -0700747 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700748 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800749}
750
Andy Hungc5007f82023-08-29 14:26:09 -0700751// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700752void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700753 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800754{
Andy Hungd0979812019-02-21 15:51:44 -0800755 // The audio statistics history is exponentially weighted to forget events
756 // about five or more seconds in the past. In order to have
757 // crisper statistics for mediametrics, we reset the statistics on
758 // an IoConfigEvent, to reflect different properties for a new device.
759 mIoJitterMs.reset();
760 mLatencyMs.reset();
761 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000762 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100763 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800764
Eric Laurent09f1ed22019-04-24 17:45:17 -0700765 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700766 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800767}
768
Andy Hungee58e4a2023-07-07 13:47:37 -0700769void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700770{
Andy Hung972bec12023-08-31 16:13:39 -0700771 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800772 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700773}
774
Andy Hungc5007f82023-08-29 14:26:09 -0700775// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700776void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800777 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800778{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800779 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700780 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800781}
782
Andy Hungc5007f82023-08-29 14:26:09 -0700783// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700784status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800785{
Andy Hung2ddee192015-12-18 17:34:44 -0800786 sp<ConfigEvent> configEvent;
787 AudioParameter param(keyValuePair);
788 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700789 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800790 setMasterMono_l(value != 0);
791 if (param.size() == 1) {
792 return NO_ERROR; // should be a solo parameter - we don't pass down
793 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700794 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800795 configEvent = new SetParameterConfigEvent(param.toString());
796 } else {
797 configEvent = new SetParameterConfigEvent(keyValuePair);
798 }
Eric Laurent10351942014-05-08 18:49:52 -0700799 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700800}
801
Andy Hungee58e4a2023-07-07 13:47:37 -0700802status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700803 const struct audio_patch *patch,
804 audio_patch_handle_t *handle)
805{
Andy Hung972bec12023-08-31 16:13:39 -0700806 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700807 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
808 status_t status = sendConfigEvent_l(configEvent);
809 if (status == NO_ERROR) {
810 CreateAudioPatchConfigEventData *data =
811 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
812 *handle = data->mHandle;
813 }
814 return status;
815}
816
Andy Hungee58e4a2023-07-07 13:47:37 -0700817status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700818 const audio_patch_handle_t handle)
819{
Andy Hung972bec12023-08-31 16:13:39 -0700820 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700821 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
822 return sendConfigEvent_l(configEvent);
823}
824
Andy Hungee58e4a2023-07-07 13:47:37 -0700825status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700826 const DeviceDescriptorBaseVector& outDevices)
827{
828 if (type() != RECORD) {
829 // The update out device operation is only for record thread.
830 return INVALID_OPERATION;
831 }
Andy Hung972bec12023-08-31 16:13:39 -0700832 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700833 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
834 return sendConfigEvent_l(configEvent);
835}
836
Andy Hungee58e4a2023-07-07 13:47:37 -0700837void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200838{
839 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
840 sp<ConfigEvent> configEvent =
841 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
842 sendConfigEvent_l(configEvent);
843}
Eric Laurent1c333e22014-05-20 10:48:17 -0700844
Andy Hungee58e4a2023-07-07 13:47:37 -0700845void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200846{
Andy Hung972bec12023-08-31 16:13:39 -0700847 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200848 sendCheckOutputStageEffectsEvent_l();
849}
850
Andy Hungee58e4a2023-07-07 13:47:37 -0700851void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200852{
853 sp<ConfigEvent> configEvent =
854 (ConfigEvent *)new CheckOutputStageEffectsEvent();
855 sendConfigEvent_l(configEvent);
856}
857
Andy Hungee58e4a2023-07-07 13:47:37 -0700858void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200859{
860 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
861 sendConfigEvent_l(configEvent);
862}
863
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700864// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700865void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700866{
Eric Laurent10351942014-05-08 18:49:52 -0700867 bool configChanged = false;
868
Eric Laurent81784c32012-11-19 14:55:58 -0800869 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700870 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700871 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800872 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700873 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700874 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700875 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
876 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800877 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700878 true /*asynchronous*/);
879 if (err != 0) {
880 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700881 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700882 }
883 } break;
884 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700885 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700886 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700887 } break;
888 case CFG_EVENT_SET_PARAMETER: {
889 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
890 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
891 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700892 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000893 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700894 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700895 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700896 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700897 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700898 CreateAudioPatchConfigEventData *data =
899 (CreateAudioPatchConfigEventData *)event->mData.get();
900 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700901 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200902 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700903 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
904 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
905 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700906 } break;
907 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700908 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700909 ReleaseAudioPatchConfigEventData *data =
910 (ReleaseAudioPatchConfigEventData *)event->mData.get();
911 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700912 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200913 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700914 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
915 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
916 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
917 } break;
918 case CFG_EVENT_UPDATE_OUT_DEVICE: {
919 UpdateOutDevicesConfigEventData *data =
920 (UpdateOutDevicesConfigEventData *)event->mData.get();
921 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700922 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200923 case CFG_EVENT_RESIZE_BUFFER: {
924 ResizeBufferConfigEventData *data =
925 (ResizeBufferConfigEventData *)event->mData.get();
926 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
927 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200928
929 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
930 setCheckOutputStageEffects();
931 } break;
932
Eric Laurent68a40a82022-05-03 18:15:04 +0200933 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
934 onHalLatencyModesChanged_l();
935 } break;
936
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700937 default:
Eric Laurent10351942014-05-08 18:49:52 -0700938 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700939 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800940 }
Eric Laurent10351942014-05-08 18:49:52 -0700941 {
Andy Hung972bec12023-08-31 16:13:39 -0700942 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700943 if (event->mWaitStatus) {
944 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700945 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700946 }
947 }
948 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
949 }
950
951 if (configChanged) {
952 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800953 }
Eric Laurent81784c32012-11-19 14:55:58 -0800954}
955
Marco Nelissenb2208842014-02-07 14:00:50 -0800956String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
957 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700958 const audio_channel_representation_t representation =
959 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700960
961 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800962 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700963 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
964 if (output) {
965 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
966 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
967 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700968 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700969 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
971 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
972 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
973 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
974 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
975 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
978 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
979 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
980 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700981 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
982 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
983 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
984 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
985 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
986 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
987 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700988 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700989 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
990 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700991 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
992 } else {
993 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
994 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
995 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
996 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
997 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
998 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
999 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1000 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1001 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1002 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1003 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1004 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001005 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1006 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1007 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001008 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001009 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1010 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001011 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1012 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1013 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1014 }
1015 const int len = s.length();
1016 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001017 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001018 s.unlockBuffer(len - 2); // remove trailing ", "
1019 }
1020 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001021 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001022 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1023 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1024 return s;
1025 default:
1026 s.appendFormat("unknown mask, representation:%d bits:%#x",
1027 representation, audio_channel_mask_get_bits(mask));
1028 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001029 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001030}
1031
Andy Hungee58e4a2023-07-07 13:47:37 -07001032void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001033NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001034{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001035 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1036 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1037
Andy Hungc5007f82023-08-29 14:26:09 -07001038 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001039 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001040 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001041 }
1042
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001043 dumpBase_l(fd, args);
1044 dumpInternals_l(fd, args);
1045 dumpTracks_l(fd, args);
1046 dumpEffectChains_l(fd, args);
1047
1048 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001049 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001050 }
1051
1052 dprintf(fd, " Local log:\n");
1053 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001054
1055 // --all does the statistics
1056 bool dumpAll = false;
1057 for (const auto &arg : args) {
1058 if (arg == String16("--all")) {
1059 dumpAll = true;
1060 }
1061 }
1062 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001063 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001064 if (!sched.empty()) {
1065 (void)write(fd, sched.c_str(), sched.size());
1066 }
1067 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001068}
1069
Andy Hungee58e4a2023-07-07 13:47:37 -07001070void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001071{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001072 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001073 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001074 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001075 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001076 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1077 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001078 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001079 dprintf(fd, " Channel count: %u\n", mChannelCount);
1080 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001081 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001082 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1083 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001084 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001085 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001086 size_t numConfig = mConfigEvents.size();
1087 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001088 const size_t SIZE = 256;
1089 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001090 for (size_t i = 0; i < numConfig; i++) {
1091 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001092 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001093 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001094 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001095 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001096 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001097 }
Andy Hung293558a2017-03-21 12:19:20 -07001098 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001099 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001100 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001101 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001102 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001103 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001104
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001105 // Dump timestamp statistics for the Thread types that support it.
1106 if (mType == RECORD
1107 || mType == MIXER
1108 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001109 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001110 || mType == OFFLOAD
1111 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001112 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001113 dprintf(fd, " Timestamp corrected: %s\n",
1114 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001115 }
1116
Andy Hung446f4df2019-02-21 12:26:41 -08001117 if (mLastIoBeginNs > 0) { // MMAP may not set this
1118 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1119 isOutput() ? "write" : "read",
1120 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1121 }
1122
1123 if (mProcessTimeMs.getN() > 0) {
1124 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1125 }
1126
1127 if (mIoJitterMs.getN() > 0) {
1128 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1129 isOutput() ? "write" : "read",
1130 mIoJitterMs.toString().c_str());
1131 }
1132
Andy Hunge6c37112019-02-26 17:38:10 -08001133 if (mLatencyMs.getN() > 0) {
1134 dprintf(fd, " Threadloop %s latency stats: %s\n",
1135 isOutput() ? "write" : "read",
1136 mLatencyMs.toString().c_str());
1137 }
Robert Wu06db0a32021-08-10 19:05:34 +00001138
1139 if (mMonopipePipeDepthStats.getN() > 0) {
1140 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1141 isOutput() ? "write" : "read",
1142 mMonopipePipeDepthStats.toString().c_str());
1143 }
Eric Laurent81784c32012-11-19 14:55:58 -08001144}
1145
Andy Hungee58e4a2023-07-07 13:47:37 -07001146void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001147{
1148 const size_t SIZE = 256;
1149 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001150
Marco Nelissenb2208842014-02-07 14:00:50 -08001151 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001152 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001153 write(fd, buffer, strlen(buffer));
1154
Marco Nelissenb2208842014-02-07 14:00:50 -08001155 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001156 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001157 if (chain != 0) {
1158 chain->dump(fd, args);
1159 }
1160 }
1161}
1162
Andy Hungee58e4a2023-07-07 13:47:37 -07001163void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001164{
Andy Hung972bec12023-08-31 16:13:39 -07001165 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001166 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001167}
1168
Andy Hungee58e4a2023-07-07 13:47:37 -07001169String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001170{
1171 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001172 case MIXER:
1173 return String16("AudioMix");
1174 case DIRECT:
1175 return String16("AudioDirectOut");
1176 case DUPLICATING:
1177 return String16("AudioDup");
1178 case RECORD:
1179 return String16("AudioIn");
1180 case OFFLOAD:
1181 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001182 case MMAP_PLAYBACK:
1183 return String16("MmapPlayback");
1184 case MMAP_CAPTURE:
1185 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001186 case SPATIALIZER:
1187 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001188 default:
1189 ALOG_ASSERT(false);
1190 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001191 }
1192}
1193
Andy Hungee58e4a2023-07-07 13:47:37 -07001194void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001195{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001196 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001197 if (mPowerManager != 0) {
1198 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001199 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001200 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1201 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001202 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001203 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001204 {} /* workSource */,
1205 {} /* historyTag */);
1206 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001207 mWakeLockToken = binder;
1208 }
Chris Ye6597d732020-02-28 22:38:25 -08001209 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001210 }
Wei Jia3f273d12015-11-24 09:06:49 -08001211
Andy Hung3f0c9022016-01-15 17:49:46 -08001212 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001213 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1214 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001215}
1216
Andy Hungee58e4a2023-07-07 13:47:37 -07001217void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001218{
Andy Hung972bec12023-08-31 16:13:39 -07001219 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001220 releaseWakeLock_l();
1221}
1222
Andy Hungee58e4a2023-07-07 13:47:37 -07001223void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001224{
Andy Hung3f0c9022016-01-15 17:49:46 -08001225 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001226 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001227 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001228 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001229 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001230 }
1231 mWakeLockToken.clear();
1232 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001233}
1234
Andy Hungee58e4a2023-07-07 13:47:37 -07001235void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001236 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001237 // use checkService() to avoid blocking if power service is not up yet
1238 sp<IBinder> binder =
1239 defaultServiceManager()->checkService(String16("power"));
1240 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001241 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001242 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001243 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001244 binder->linkToDeath(mDeathRecipient);
1245 }
1246 }
1247}
1248
Andy Hungee58e4a2023-07-07 13:47:37 -07001249void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001250 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001251
1252#if !LOG_NDEBUG
1253 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001254 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001255 s << uid << " ";
1256 }
1257 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1258#endif
1259
Andy Hung438e7572015-12-14 15:51:17 -08001260 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1261 if (mSystemReady) {
1262 ALOGE("no wake lock to update, but system ready!");
1263 } else {
1264 ALOGW("no wake lock to update, system not ready yet");
1265 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001266 return;
1267 }
1268 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001269 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001270 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1271 mWakeLockToken, uidsAsInt);
1272 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001273 }
1274}
1275
Andy Hungee58e4a2023-07-07 13:47:37 -07001276void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001277{
Andy Hung972bec12023-08-31 16:13:39 -07001278 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001279 releaseWakeLock_l();
1280 mPowerManager.clear();
1281}
1282
Andy Hungee58e4a2023-07-07 13:47:37 -07001283void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001284 const DeviceDescriptorBaseVector& outDevices __unused)
1285{
1286 ALOGE("%s should only be called in RecordThread", __func__);
1287}
1288
Andy Hungee58e4a2023-07-07 13:47:37 -07001289void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001290{
1291 ALOGE("%s should only be called in RecordThread", __func__);
1292}
1293
Andy Hungee58e4a2023-07-07 13:47:37 -07001294void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001295{
1296 sp<ThreadBase> thread = mThread.promote();
1297 if (thread != 0) {
1298 thread->clearPowerManager();
1299 }
1300 ALOGW("power manager service died !!!");
1301}
1302
Andy Hungee58e4a2023-07-07 13:47:37 -07001303void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001304 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001305{
Andy Hung116bc262023-06-20 18:56:17 -07001306 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001307 if (chain != 0) {
1308 if (type != NULL) {
1309 chain->setEffectSuspended_l(type, suspend);
1310 } else {
1311 chain->setEffectSuspendedAll_l(suspend);
1312 }
1313 }
1314
1315 updateSuspendedSessions_l(type, suspend, sessionId);
1316}
1317
Andy Hungee58e4a2023-07-07 13:47:37 -07001318void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001319{
1320 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1321 if (index < 0) {
1322 return;
1323 }
1324
1325 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1326 mSuspendedSessions.valueAt(index);
1327
1328 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001329 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001330 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001331 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001332 chain->setEffectSuspendedAll_l(true);
1333 } else {
1334 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1335 desc->mType.timeLow);
1336 chain->setEffectSuspended_l(&desc->mType, true);
1337 }
1338 }
1339 }
1340}
1341
Andy Hungee58e4a2023-07-07 13:47:37 -07001342void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001343 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001344 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001345{
1346 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1347
1348 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1349
1350 if (suspend) {
1351 if (index >= 0) {
1352 sessionEffects = mSuspendedSessions.valueAt(index);
1353 } else {
1354 mSuspendedSessions.add(sessionId, sessionEffects);
1355 }
1356 } else {
1357 if (index < 0) {
1358 return;
1359 }
1360 sessionEffects = mSuspendedSessions.valueAt(index);
1361 }
1362
1363
Andy Hung116bc262023-06-20 18:56:17 -07001364 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001365 if (type != NULL) {
1366 key = type->timeLow;
1367 }
1368 index = sessionEffects.indexOfKey(key);
1369
1370 sp<SuspendedSessionDesc> desc;
1371 if (suspend) {
1372 if (index >= 0) {
1373 desc = sessionEffects.valueAt(index);
1374 } else {
1375 desc = new SuspendedSessionDesc();
1376 if (type != NULL) {
1377 desc->mType = *type;
1378 }
1379 sessionEffects.add(key, desc);
1380 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1381 }
1382 desc->mRefCount++;
1383 } else {
1384 if (index < 0) {
1385 return;
1386 }
1387 desc = sessionEffects.valueAt(index);
1388 if (--desc->mRefCount == 0) {
1389 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1390 sessionEffects.removeItemsAt(index);
1391 if (sessionEffects.isEmpty()) {
1392 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1393 sessionId);
1394 mSuspendedSessions.removeItem(sessionId);
1395 }
1396 }
1397 }
1398 if (!sessionEffects.isEmpty()) {
1399 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1400 }
1401}
1402
Andy Hungee58e4a2023-07-07 13:47:37 -07001403void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001404 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001405 bool threadLocked)
1406NO_THREAD_SAFETY_ANALYSIS // manual locking
1407{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001408 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001409 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001410 }
Eric Laurent81784c32012-11-19 14:55:58 -08001411
Eric Laurent81784c32012-11-19 14:55:58 -08001412 if (mType != RECORD) {
1413 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1414 // another session. This gives the priority to well behaved effect control panels
1415 // and applications not using global effects.
1416 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1417 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001418 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001419 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1420 }
1421 }
1422
Eric Laurent6b446ce2019-12-13 10:56:31 -08001423 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001424 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001425 }
1426}
1427
Andy Hungc5007f82023-08-29 14:26:09 -07001428// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001429status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001430 const effect_descriptor_t *desc, audio_session_t sessionId)
1431{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001432 // No global output effect sessions on record threads
1433 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1434 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001435 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1436 desc->name, mThreadName);
1437 return BAD_VALUE;
1438 }
1439 // only pre processing effects on record thread
1440 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1441 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1442 desc->name, mThreadName);
1443 return BAD_VALUE;
1444 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001445
1446 // always allow effects without processing load or latency
1447 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1448 return NO_ERROR;
1449 }
1450
Eric Laurent4c415062016-06-17 16:14:16 -07001451 audio_input_flags_t flags = mInput->flags;
1452 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1453 if (flags & AUDIO_INPUT_FLAG_RAW) {
1454 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1455 desc->name, mThreadName);
1456 return BAD_VALUE;
1457 }
1458 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1459 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1460 desc->name, mThreadName);
1461 return BAD_VALUE;
1462 }
1463 }
jiabineb3bda02020-06-30 14:07:03 -07001464
Andy Hung116bc262023-06-20 18:56:17 -07001465 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001466 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1467 return BAD_VALUE;
1468 }
Eric Laurent4c415062016-06-17 16:14:16 -07001469 return NO_ERROR;
1470}
1471
Andy Hungc5007f82023-08-29 14:26:09 -07001472// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001473status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001474 const effect_descriptor_t *desc, audio_session_t sessionId)
1475{
1476 // no preprocessing on playback threads
1477 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001478 ALOGW("%s: pre processing effect %s created on playback"
1479 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001480 return BAD_VALUE;
1481 }
1482
Eric Laurent3e4de772017-07-16 16:55:08 -07001483 // always allow effects without processing load or latency
1484 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1485 return NO_ERROR;
1486 }
1487
Andy Hung116bc262023-06-20 18:56:17 -07001488 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001489 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1490 __func__);
1491 return BAD_VALUE;
1492 }
1493
Eric Laurent4eb45d02023-12-20 12:07:17 +01001494 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001495 && mType != SPATIALIZER) {
1496 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1497 __func__, mType);
1498 return BAD_VALUE;
1499 }
1500
Eric Laurent4c415062016-06-17 16:14:16 -07001501 switch (mType) {
1502 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001503 audio_output_flags_t flags = mOutput->flags;
1504 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1505 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1506 // global effects are applied only to non fast tracks if they are SW
1507 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1508 break;
1509 }
1510 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1511 // only post processing on output stage session
1512 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001513 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1514 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001515 return BAD_VALUE;
1516 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001517 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1518 // only post processing on output stage session
1519 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001520 ALOGW("%s: non post processing effect %s not allowed on device session",
1521 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001522 return BAD_VALUE;
1523 }
Eric Laurent4c415062016-06-17 16:14:16 -07001524 } else {
1525 // no restriction on effects applied on non fast tracks
1526 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1527 break;
1528 }
1529 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001530
Eric Laurent4c415062016-06-17 16:14:16 -07001531 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001532 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001533 return BAD_VALUE;
1534 }
1535 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001536 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1537 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001538 return BAD_VALUE;
1539 }
1540 }
1541 } break;
1542 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001543 // nothing actionable on offload threads, if the effect:
1544 // - is offloadable: the effect can be created
1545 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1546 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001547 break;
1548 case DIRECT:
1549 // Reject any effect on Direct output threads for now, since the format of
1550 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001551 ALOGW("%s: effect %s on DIRECT output thread %s",
1552 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001553 return BAD_VALUE;
1554 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001555 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001556 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1557 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001558 return BAD_VALUE;
1559 }
1560 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001561 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1562 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001563 return BAD_VALUE;
1564 }
1565 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001566 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1567 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001568 return BAD_VALUE;
1569 }
1570 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001571 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001572 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1573 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1574 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1575 // are supported and added after the spatializer.
1576 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1577 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1578 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001579 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001580 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1581 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001582 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001583 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1584 break;
1585 }
1586 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1587 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1588 __func__, desc->name);
1589 return BAD_VALUE;
1590 }
1591 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1592 // only post processing on output stage session
1593 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1594 ALOGW("%s: non post processing effect %s not allowed on device session",
1595 __func__, desc->name);
1596 return BAD_VALUE;
1597 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001598 }
1599 break;
jiabinc658e452022-10-21 20:52:21 +00001600 case BIT_PERFECT:
1601 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1602 // Allow HW accelerated effects of tunnel type
1603 break;
1604 }
1605 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1606 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1607 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1608 // 3) there is any bit-perfect track with the given session id.
1609 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1610 sessionId == AUDIO_SESSION_DEVICE) {
1611 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1612 __func__, desc->name, mThreadName);
1613 return BAD_VALUE;
1614 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1615 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1616 __func__, desc->name, sessionId);
1617 return BAD_VALUE;
1618 }
1619 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001620 default:
1621 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1622 }
1623
1624 return NO_ERROR;
1625}
1626
Andy Hungc5007f82023-08-29 14:26:09 -07001627// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001628sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001629 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001630 const sp<IEffectClient>& effectClient,
1631 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001632 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001633 effect_descriptor_t *desc,
1634 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001636 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001637 bool probe,
1638 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001639{
Andy Hung116bc262023-06-20 18:56:17 -07001640 sp<IAfEffectModule> effect;
1641 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001642 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001643 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001644 bool chainCreated = false;
1645 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001646 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001647
1648 lStatus = initCheck();
1649 if (lStatus != NO_ERROR) {
1650 ALOGW("createEffect_l() Audio driver not initialized.");
1651 goto Exit;
1652 }
1653
Eric Laurent81784c32012-11-19 14:55:58 -08001654 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1655
Andy Hungc5007f82023-08-29 14:26:09 -07001656 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001657 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001658
Eric Laurent4c415062016-06-17 16:14:16 -07001659 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001660 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001661 goto Exit;
1662 }
1663
Eric Laurent81784c32012-11-19 14:55:58 -08001664 // check for existing effect chain with the requested audio session
1665 chain = getEffectChain_l(sessionId);
1666 if (chain == 0) {
1667 // create a new chain for this session
1668 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001669 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001670 addEffectChain_l(chain);
1671 chain->setStrategy(getStrategyForSession_l(sessionId));
1672 chainCreated = true;
1673 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001674 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001675 }
1676
1677 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1678
1679 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001680 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001681 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001682 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001683 if (lStatus != NO_ERROR) {
1684 goto Exit;
1685 }
1686 effectCreated = true;
1687
jiabinc52b1ff2019-10-31 17:20:42 -07001688 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001689 effect->setDevices(outDeviceTypeAddrs());
1690 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001691 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001692 effect->setAudioSource(mAudioSource);
1693 }
jiabin1319f5a2021-03-30 22:21:24 +00001694 if (effect->isHapticGenerator()) {
1695 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1696 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001697 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001698 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001699 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001700 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001701 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001702 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001703 }
1704 }
Eric Laurent81784c32012-11-19 14:55:58 -08001705 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001706 handle = IAfEffectHandle::create(
1707 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001708 lStatus = handle->initCheck();
1709 if (lStatus == OK) {
1710 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001711 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001712 }
Eric Laurent81784c32012-11-19 14:55:58 -08001713 if (enabled != NULL) {
1714 *enabled = (int)effect->isEnabled();
1715 }
1716 }
1717
1718Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001719 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001720 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001721 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001722 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001723 }
Eric Laurent81784c32012-11-19 14:55:58 -08001724 if (chainCreated) {
1725 removeEffectChain_l(chain);
1726 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001727 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001728 }
1729
Glenn Kasten9156ef32013-08-06 15:39:08 -07001730 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001731 return handle;
1732}
1733
Andy Hungee58e4a2023-07-07 13:47:37 -07001734void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001735 bool unpinIfLast)
1736{
1737 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001738 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001739 {
Andy Hung972bec12023-08-31 16:13:39 -07001740 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001741 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001742 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001743 return;
1744 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001745 effect = effectBase->asEffectModule();
1746 if (effect == nullptr) {
1747 return;
1748 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001749 // restore suspended effects if the disconnected handle was enabled and the last one.
1750 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1751 if (remove) {
1752 removeEffect_l(effect, true);
1753 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001754 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001755 }
1756 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001757 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001758 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001759 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001760 }
1761 }
1762}
1763
Andy Hungee58e4a2023-07-07 13:47:37 -07001764void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001765 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001766 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001767 broadcast_l();
1768 }
1769 if (!effect->isOffloadable()) {
1770 if (mType == ThreadBase::OFFLOAD) {
1771 PlaybackThread *t = (PlaybackThread *)this;
1772 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1773 }
1774 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001775 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001776 }
1777 }
1778}
1779
Andy Hungee58e4a2023-07-07 13:47:37 -07001780void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001781 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001782 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001783 broadcast_l();
1784 }
1785}
1786
Andy Hungee58e4a2023-07-07 13:47:37 -07001787sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001788 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001789{
Andy Hung972bec12023-08-31 16:13:39 -07001790 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001791 return getEffect_l(sessionId, effectId);
1792}
1793
Andy Hungee58e4a2023-07-07 13:47:37 -07001794sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001795 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001796{
Andy Hung116bc262023-06-20 18:56:17 -07001797 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001798 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1799}
1800
Andy Hungee58e4a2023-07-07 13:47:37 -07001801std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001802{
Andy Hung116bc262023-06-20 18:56:17 -07001803 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001804 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001805}
1806
Andy Hung972bec12023-08-31 16:13:39 -07001807// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1808// ThreadBase::mutex() held
1809status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001810{
1811 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001812 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001813 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001814 bool chainCreated = false;
1815
Eric Laurent5baf2af2013-09-12 17:37:00 -07001816 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001817 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1818 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001819
Eric Laurent81784c32012-11-19 14:55:58 -08001820 if (chain == 0) {
1821 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001822 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001823 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001824 addEffectChain_l(chain);
1825 chain->setStrategy(getStrategyForSession_l(sessionId));
1826 chainCreated = true;
1827 }
Andy Hung972bec12023-08-31 16:13:39 -07001828 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001829
1830 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001831 ALOGW("%s: %p effect %s already present in chain %p",
1832 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001833 return BAD_VALUE;
1834 }
1835
Shunkai Yaod125e402024-01-20 03:19:06 +00001836 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001837
Shunkai Yao29d10572024-03-19 04:31:47 +00001838 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001839 if (status != NO_ERROR) {
1840 if (chainCreated) {
1841 removeEffectChain_l(chain);
1842 }
1843 return status;
1844 }
1845
jiabin8f278ee2019-11-11 12:16:27 -08001846 effect->setDevices(outDeviceTypeAddrs());
1847 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001848 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001849 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001850
Eric Laurent81784c32012-11-19 14:55:58 -08001851 return NO_ERROR;
1852}
1853
Andy Hungee58e4a2023-07-07 13:47:37 -07001854void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001855
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001856 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001857 effect_descriptor_t desc = effect->desc();
1858 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1859 detachAuxEffect_l(effect->id());
1860 }
1861
Andy Hung116bc262023-06-20 18:56:17 -07001862 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001863 if (chain != 0) {
1864 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001865 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001866 removeEffectChain_l(chain);
1867 }
1868 } else {
1869 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1870 }
1871}
1872
Shunkai Yaof4847652024-01-12 00:25:20 +00001873void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1874 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001875{
1876 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001877 for (const auto& effectChain : effectChains) {
1878 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001879 }
1880}
1881
Shunkai Yaof4847652024-01-12 00:25:20 +00001882void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1883 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001884{
Shunkai Yaof4847652024-01-12 00:25:20 +00001885 for (const auto& effectChain : effectChains) {
1886 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001887 }
1888}
1889
Andy Hungee58e4a2023-07-07 13:47:37 -07001890sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001891{
Andy Hung972bec12023-08-31 16:13:39 -07001892 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001893 return getEffectChain_l(sessionId);
1894}
1895
Andy Hungee58e4a2023-07-07 13:47:37 -07001896sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001897 const
Eric Laurent81784c32012-11-19 14:55:58 -08001898{
1899 size_t size = mEffectChains.size();
1900 for (size_t i = 0; i < size; i++) {
1901 if (mEffectChains[i]->sessionId() == sessionId) {
1902 return mEffectChains[i];
1903 }
1904 }
1905 return 0;
1906}
1907
Andy Hungee58e4a2023-07-07 13:47:37 -07001908void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001909{
Andy Hung972bec12023-08-31 16:13:39 -07001910 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001911 size_t size = mEffectChains.size();
1912 for (size_t i = 0; i < size; i++) {
1913 mEffectChains[i]->setMode_l(mode);
1914 }
1915}
1916
Andy Hungee58e4a2023-07-07 13:47:37 -07001917void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001918{
1919 config->type = AUDIO_PORT_TYPE_MIX;
1920 config->ext.mix.handle = mId;
1921 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001922 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001923 config->channel_mask = mChannelMask;
1924 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1925 AUDIO_PORT_CONFIG_FORMAT;
1926}
1927
Andy Hungee58e4a2023-07-07 13:47:37 -07001928void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001929{
Andy Hung972bec12023-08-31 16:13:39 -07001930 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001931 if (mSystemReady) {
1932 return;
1933 }
1934 mSystemReady = true;
1935
1936 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1937 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1938 }
1939 mPendingConfigEvents.clear();
1940}
1941
Andy Hungdae27702016-10-31 14:01:16 -07001942template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001943ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001944 ssize_t index = mActiveTracks.indexOf(track);
1945 if (index >= 0) {
1946 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1947 return index;
1948 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001949 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001950 mActiveTracksGeneration++;
1951 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001952 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001953 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001954 return mActiveTracks.add(track);
1955}
1956
1957template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001958ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001959 ssize_t index = mActiveTracks.remove(track);
1960 if (index < 0) {
1961 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1962 return index;
1963 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001964 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001965 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001966 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001967 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001968 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001969#ifdef TEE_SINK
1970 track->dumpTee(-1 /* fd */, "_REMOVE");
1971#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001972 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001973 return index;
1974}
1975
1976template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001977void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001978 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001979 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001980 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001981 }
1982 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001983 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001984 mActiveTracks.clear();
1985 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001986}
1987
1988template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001989void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001990 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001991 // Updates ActiveTracks client uids to the thread wakelock.
1992 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1993 thread->updateWakeLockUids_l(getWakeLockUids());
1994 mLastActiveTracksGeneration = mActiveTracksGeneration;
1995 }
Andy Hungdae27702016-10-31 14:01:16 -07001996}
Eric Laurent83b88082014-06-20 18:31:16 -07001997
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001998template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001999bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002000 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002001 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002002
2003 for (const sp<T> &track : mActiveTracks) {
2004 // Do not short-circuit as all hasChanged states must be reset
2005 // as all the metadata are going to be sent
2006 hasChanged |= track->readAndClearHasChanged();
2007 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002008 return hasChanged;
2009}
2010
2011template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002012void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002013 const char *funcName, const sp<T> &track) const {
2014 if (mLocalLog != nullptr) {
2015 String8 result;
2016 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002017 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002018 }
2019}
2020
Andy Hungee58e4a2023-07-07 13:47:37 -07002021void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002022{
2023 // Thread could be blocked waiting for async
2024 // so signal it to handle state changes immediately
2025 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2026 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2027 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002028 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002029}
2030
Andy Hungd0979812019-02-21 15:51:44 -08002031// Call only from threadLoop() or when it is idle.
2032// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002033void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002034NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002035{
2036 // Do not log if we have no stats.
2037 // We choose the timestamp verifier because it is the most likely item to be present.
2038 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2039 if (nstats == 0) {
2040 return;
2041 }
2042
2043 // Don't log more frequently than once per 12 hours.
2044 // We use BOOTTIME to include suspend time.
2045 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2046 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2047 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2048 return;
2049 }
2050
2051 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2052 mLastRecordedTimeNs = timeNs;
2053
Ray Essickf27e9872019-12-07 06:28:46 -08002054 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002055
2056#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2057
2058 // thread configuration
2059 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2060 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2061 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2062 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2063 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2064 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2065 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002066 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2067 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002068
2069 // thread statistics
2070 if (mIoJitterMs.getN() > 0) {
2071 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2072 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2073 }
2074 if (mProcessTimeMs.getN() > 0) {
2075 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2076 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2077 }
2078 const auto tsjitter = mTimestampVerifier.getJitterMs();
2079 if (tsjitter.getN() > 0) {
2080 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2081 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2082 }
2083 if (mLatencyMs.getN() > 0) {
2084 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2085 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2086 }
Robert Wu06db0a32021-08-10 19:05:34 +00002087 if (mMonopipePipeDepthStats.getN() > 0) {
2088 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2089 mMonopipePipeDepthStats.getMean());
2090 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2091 mMonopipePipeDepthStats.getStdDev());
2092 }
Andy Hungd0979812019-02-21 15:51:44 -08002093
2094 item->selfrecord();
2095}
2096
Andy Hungee58e4a2023-07-07 13:47:37 -07002097product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002098{
Andy Hung583043b2023-07-17 17:05:00 -07002099 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002100 return PRODUCT_STRATEGY_NONE;
2101 }
2102 return AudioSystem::getStrategyForStream(stream);
2103}
2104
Andy Hungc5007f82023-08-29 14:26:09 -07002105// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002106void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002107 const sp<audio_utils::MelProcessor>& /*processor*/)
2108{
2109 // Do nothing
2110 ALOGW("%s: ThreadBase does not support CSD", __func__);
2111}
2112
Andy Hungc5007f82023-08-29 14:26:09 -07002113// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002114void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002115{
2116 // Do nothing
2117 ALOGW("%s: ThreadBase does not support CSD", __func__);
2118}
2119
Eric Laurent81784c32012-11-19 14:55:58 -08002120// ----------------------------------------------------------------------------
2121// Playback
2122// ----------------------------------------------------------------------------
2123
Andy Hung583043b2023-07-17 17:05:00 -07002124PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002125 AudioStreamOut* output,
2126 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002127 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002128 bool systemReady,
2129 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002130 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002131 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002132 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002133 mMixerBuffer(NULL),
2134 mMixerBufferSize(0),
2135 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2136 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002137 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002138 mEffectBuffer(NULL),
2139 mEffectBufferSize(0),
2140 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2141 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002142 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002143 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002144 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002145 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002146 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002147 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002148 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002149 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002150 mMixerStatus(MIXER_IDLE),
2151 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002152 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 mBytesRemaining(0),
2154 mCurrentWriteLength(0),
2155 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002156 mWriteAckSequence(0),
2157 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002158 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002159 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002160 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002161 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002162 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002163 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002164 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002165{
Glenn Kastend7dca052015-03-05 16:05:54 -08002166 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002167 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002168
Andy Hungc5007f82023-08-29 14:26:09 -07002169 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002170 // it would be safer to explicitly pass initial masterVolume/masterMute as
2171 // parameter.
2172 //
2173 // If the HAL we are using has support for master volume or master mute,
2174 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2175 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002176 mMasterVolume = afThreadCallback->masterVolume_l();
2177 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002178 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002179 if (mOutput->audioHwDev->canSetMasterVolume()) {
2180 mMasterVolume = 1.0;
2181 }
2182
2183 if (mOutput->audioHwDev->canSetMasterMute()) {
2184 mMasterMute = false;
2185 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002186 mIsMsdDevice = strcmp(
2187 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002188 }
2189
Eric Laurentf1f22e72021-07-13 14:04:14 +02002190 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2191 mMixerChannelMask = mixerConfig->channel_mask;
2192 }
2193
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002194 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002195
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002196 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002197 && mMixerChannelMask != mChannelMask) {
2198 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2199 mChannelMask, mMixerChannelMask);
2200 }
2201
Andy Hungc8fddf32018-08-08 18:32:37 -07002202 // TODO: We may also match on address as well as device type for
2203 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002204 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002205 // TODO: This property should be ensure that only contains one single device type.
2206 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2207 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002208 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2209 : AUDIO_DEVICE_NONE));
2210 }
2211
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002212 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2213 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002214 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002215 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002216 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002217 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002218 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2219 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002220 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2221 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002222}
2223
Andy Hungee58e4a2023-07-07 13:47:37 -07002224PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002225{
Andy Hung583043b2023-07-17 17:05:00 -07002226 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002227 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002228 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002229 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002230 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002231}
2232
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002233// Thread virtuals
2234
Andy Hungee58e4a2023-07-07 13:47:37 -07002235void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002236{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002237 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002238 ALOGE("The stream is not open yet"); // This should not happen.
2239 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002240 // Callbacks take strong or weak pointers as a parameter.
2241 // Since PlaybackThread passes itself as a callback handler, it can only
2242 // be done outside of the constructor. Creating weak and especially strong
2243 // pointers to a refcounted object in its own constructor is strongly
2244 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2245 // Even if a function takes a weak pointer, it is possible that it will
2246 // need to convert it to a strong pointer down the line.
2247 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2248 mOutput->stream->setCallback(this) == OK) {
2249 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002250 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002251 }
2252
jiabinf6eb4c32020-02-25 14:06:25 -08002253 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002254 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002255 }
2256 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002257 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002258 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002259}
2260
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002261// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002262void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002263{
2264 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002265 status_t result = mOutput->stream->exit();
2266 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002267}
2268
Andy Hungee58e4a2023-07-07 13:47:37 -07002269void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002270{
Eric Laurent81784c32012-11-19 14:55:58 -08002271 String8 result;
2272
Marco Nelissenb2208842014-02-07 14:00:50 -08002273 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002274 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2275 const stream_type_t *st = &mStreamTypes[i];
2276 if (i > 0) {
2277 result.appendFormat(", ");
2278 }
2279 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2280 if (st->mute) {
2281 result.append("M");
2282 }
2283 }
2284 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002285 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002286 result.clear();
2287
Eric Laurent81784c32012-11-19 14:55:58 -08002288 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2289 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002290 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002291 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002292
2293 size_t numtracks = mTracks.size();
2294 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002295 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002296 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002297 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002298 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002299 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002300 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002301 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002302 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002303 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002304 if (track != 0) {
2305 bool active = mActiveTracks.indexOf(track) >= 0;
2306 if (active) {
2307 numactiveseen++;
2308 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002309 result.append(prefix);
2310 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002311 }
2312 }
2313 } else {
2314 result.append("\n");
2315 }
2316 if (numactiveseen != numactive) {
2317 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002318 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002319 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002320 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002321 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002322 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002323 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002324 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002325 result.append(prefix);
2326 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002327 }
2328 }
2329 }
2330
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002331 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002332}
2333
Andy Hungee58e4a2023-07-07 13:47:37 -07002334void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002335{
Andy Hung04cb8f72020-03-20 13:44:33 -07002336 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002337 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002338 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2339 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002340 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2341 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2342 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2343 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002344 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002345 dprintf(fd, " Total writes: %d\n", mNumWrites);
2346 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2347 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002348 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002349 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002350 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002351 AudioStreamOut *output = mOutput;
2352 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002353 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002354 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002355 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2356 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2357 if (mPipeSink.get() != nullptr) {
2358 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2359 }
2360 if (output != nullptr) {
2361 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002362 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002363 }
Eric Laurent81784c32012-11-19 14:55:58 -08002364}
2365
Andy Hungc5007f82023-08-29 14:26:09 -07002366// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002367sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002368 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002369 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002370 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002371 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002372 audio_format_t format,
2373 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002374 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002375 size_t *pNotificationFrameCount,
2376 uint32_t notificationsPerBuffer,
2377 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002378 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002379 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002380 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002381 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002382 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002383 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002384 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002385 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002386 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002387 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002388 bool isBitPerfect,
2389 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002390{
Glenn Kasten74935e42013-12-19 08:56:45 -08002391 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002392 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002393 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002394 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002395 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002396 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002397 uint32_t sampleRate;
2398
2399 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2400 lStatus = BAD_VALUE;
2401 goto Exit;
2402 }
Eric Laurent21da6472017-11-09 16:29:26 -08002403
2404 if (*pSampleRate == 0) {
2405 *pSampleRate = mSampleRate;
2406 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002407 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002408
2409 // special case for FAST flag considered OK if fast mixer is present
2410 if (hasFastMixer()) {
2411 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2412 }
2413
2414 // Check if requested flags are compatible with output stream flags
2415 if ((*flags & outputFlags) != *flags) {
2416 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2417 *flags, outputFlags);
2418 *flags = (audio_output_flags_t)(*flags & outputFlags);
2419 }
Eric Laurent81784c32012-11-19 14:55:58 -08002420
jiabinc658e452022-10-21 20:52:21 +00002421 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002422 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002423 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002424 if (chain.get() != nullptr) {
2425 // Bit-perfect is required according to the configuration and preferred mixer
2426 // attributes, but it is not in the output flag from the client's request. Explicitly
2427 // adding bit-perfect flag to check the compatibility
2428 audio_output_flags_t flagsToCheck =
2429 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2430 chain->checkOutputFlagCompatibility(&flagsToCheck);
2431 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2432 ALOGE("%s cannot create track as there is data-processing effect attached to "
2433 "given session id(%d)", __func__, sessionId);
2434 lStatus = BAD_VALUE;
2435 goto Exit;
2436 }
2437 *flags = flagsToCheck;
2438 }
2439 }
2440
Eric Laurent81784c32012-11-19 14:55:58 -08002441 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002442 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002443 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002444 // PCM data
2445 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002446 // TODO: extract as a data library function that checks that a computationally
2447 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002448 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002449 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2450 (channelMask == AUDIO_CHANNEL_OUT_MONO
2451 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002452 // hardware sample rate
2453 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002454 // normal mixer has an associated fast mixer
2455 hasFastMixer() &&
2456 // there are sufficient fast track slots available
2457 (mFastTrackAvailMask != 0)
2458 // FIXME test that MixerThread for this fast track has a capable output HAL
2459 // FIXME add a permission test also?
2460 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002461 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2462 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002463 // read the fast track multiplier property the first time it is needed
2464 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2465 if (ok != 0) {
2466 ALOGE("%s pthread_once failed: %d", __func__, ok);
2467 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002468 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002469 }
Eric Laurent4c415062016-06-17 16:14:16 -07002470
2471 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002472 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002473 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002474 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002475 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002476 AUDIO_SESSION_OUTPUT_STAGE,
2477 AUDIO_SESSION_OUTPUT_MIX,
2478 sessionId,
2479 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002480 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002481 if (chain.get() != nullptr) {
2482 audio_output_flags_t old = *flags;
2483 chain->checkOutputFlagCompatibility(flags);
2484 if (old != *flags) {
2485 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2486 (int)session, (int)old, (int)*flags);
2487 }
Eric Laurent4c415062016-06-17 16:14:16 -07002488 }
2489 }
2490 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002491 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002492 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2493 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002494 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002495 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002496 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002497 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002498 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002499 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002500 audio_is_linear_pcm(format), channelMask, sampleRate,
2501 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002502 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002503 }
2504 }
Eric Laurent21da6472017-11-09 16:29:26 -08002505
2506 if (!audio_has_proportional_frames(format)) {
2507 if (sharedBuffer != 0) {
2508 // Same comment as below about ignoring frameCount parameter for set()
2509 frameCount = sharedBuffer->size();
2510 } else if (frameCount == 0) {
2511 frameCount = mNormalFrameCount;
2512 }
2513 if (notificationFrameCount != frameCount) {
2514 notificationFrameCount = frameCount;
2515 }
2516 } else if (sharedBuffer != 0) {
2517 // FIXME: Ensure client side memory buffers need
2518 // not have additional alignment beyond sample
2519 // (e.g. 16 bit stereo accessed as 32 bit frame).
2520 size_t alignment = audio_bytes_per_sample(format);
2521 if (alignment & 1) {
2522 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2523 alignment = 1;
2524 }
2525 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2526 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2527 if (channelCount > 1) {
2528 // More than 2 channels does not require stronger alignment than stereo
2529 alignment <<= 1;
2530 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002531 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002532 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002533 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002534 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002535 goto Exit;
2536 }
Eric Laurent21da6472017-11-09 16:29:26 -08002537
2538 // When initializing a shared buffer AudioTrack via constructors,
2539 // there's no frameCount parameter.
2540 // But when initializing a shared buffer AudioTrack via set(),
2541 // there _is_ a frameCount parameter. We silently ignore it.
2542 frameCount = sharedBuffer->size() / frameSize;
2543 } else {
2544 size_t minFrameCount = 0;
2545 // For fast tracks we try to respect the application's request for notifications per buffer.
2546 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2547 if (notificationsPerBuffer > 0) {
2548 // Avoid possible arithmetic overflow during multiplication.
2549 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2550 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2551 notificationsPerBuffer, mFrameCount);
2552 } else {
2553 minFrameCount = mFrameCount * notificationsPerBuffer;
2554 }
2555 }
2556 } else {
2557 // For normal PCM streaming tracks, update minimum frame count.
2558 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2559 // cover audio hardware latency.
2560 // This is probably too conservative, but legacy application code may depend on it.
2561 // If you change this calculation, also review the start threshold which is related.
2562 uint32_t latencyMs = latency_l();
2563 if (latencyMs == 0) {
2564 ALOGE("Error when retrieving output stream latency");
2565 lStatus = UNKNOWN_ERROR;
2566 goto Exit;
2567 }
2568
2569 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2570 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2571
Eric Laurent81784c32012-11-19 14:55:58 -08002572 }
Eric Laurent21da6472017-11-09 16:29:26 -08002573 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002574 frameCount = minFrameCount;
2575 }
Eric Laurent81784c32012-11-19 14:55:58 -08002576 }
Eric Laurent21da6472017-11-09 16:29:26 -08002577
2578 // Make sure that application is notified with sufficient margin before underrun.
2579 // The client can divide the AudioTrack buffer into sub-buffers,
2580 // and expresses its desire to server as the notification frame count.
2581 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2582 size_t maxNotificationFrames;
2583 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2584 // notify every HAL buffer, regardless of the size of the track buffer
2585 maxNotificationFrames = mFrameCount;
2586 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002587 // Triple buffer the notification period for a triple buffered mixer period;
2588 // otherwise, double buffering for the notification period is fine.
2589 //
2590 // TODO: This should be moved to AudioTrack to modify the notification period
2591 // on AudioTrack::setBufferSizeInFrames() changes.
2592 const int nBuffering =
2593 (uint64_t{frameCount} * mSampleRate)
2594 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2595
Eric Laurent21da6472017-11-09 16:29:26 -08002596 maxNotificationFrames = frameCount / nBuffering;
2597 // If client requested a fast track but this was denied, then use the smaller maximum.
2598 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2599 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2600 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2601 maxNotificationFrames = maxNotificationFramesFastDenied;
2602 }
2603 }
2604 }
2605 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2606 if (notificationFrameCount == 0) {
2607 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2608 maxNotificationFrames, frameCount);
2609 } else {
2610 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2611 notificationFrameCount, maxNotificationFrames, frameCount);
2612 }
2613 notificationFrameCount = maxNotificationFrames;
2614 }
2615 }
2616
Glenn Kasten74935e42013-12-19 08:56:45 -08002617 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002618 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002619
Glenn Kastenc3df8382014-03-13 15:05:25 -07002620 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002621 case BIT_PERFECT:
2622 if (isBitPerfect) {
2623 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2624 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2625 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2626 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2627 mChannelMask);
2628 lStatus = BAD_VALUE;
2629 goto Exit;
2630 }
2631 }
2632 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002633
2634 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002635 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002636 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002637 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2638 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002639 sampleRate, format, channelMask, mOutput, mFormat);
2640 lStatus = BAD_VALUE;
2641 goto Exit;
2642 }
2643 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002644 break;
2645
2646 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002647 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002648 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2649 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002650 sampleRate, format, channelMask, mOutput, mFormat);
2651 lStatus = BAD_VALUE;
2652 goto Exit;
2653 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002654 break;
2655
2656 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002657 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002658 ALOGE("createTrack_l() Bad parameter: format %#x \""
2659 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002660 format, mOutput, mFormat);
2661 lStatus = BAD_VALUE;
2662 goto Exit;
2663 }
Andy Hungcd044842014-08-07 11:04:34 -07002664 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002665 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2666 lStatus = BAD_VALUE;
2667 goto Exit;
2668 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002669 break;
2670
Eric Laurent81784c32012-11-19 14:55:58 -08002671 }
2672
2673 lStatus = initCheck();
2674 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002675 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002676 goto Exit;
2677 }
2678
Andy Hungc5007f82023-08-29 14:26:09 -07002679 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002680 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002681
2682 // all tracks in same audio session must share the same routing strategy otherwise
2683 // conflicts will happen when tracks are moved from one output to another by audio policy
2684 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002685 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002686 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002687 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002688 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002689 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002690 if (sessionId == t->sessionId() && strategy != actual) {
2691 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2692 strategy, actual);
2693 lStatus = BAD_VALUE;
2694 goto Exit;
2695 }
2696 }
2697 }
2698
yucliuc9c49cd2020-07-13 16:25:21 -07002699 // Set DIRECT flag if current thread is DirectOutputThread. This can
2700 // happen when the playback is rerouted to direct output thread by
2701 // dynamic audio policy.
2702 // Do NOT report the flag changes back to client, since the client
2703 // doesn't explicitly request a direct flag.
2704 audio_output_flags_t trackFlags = *flags;
2705 if (mType == DIRECT) {
2706 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2707 }
jiabin94ed47c2023-07-27 23:34:20 +00002708 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002709
Andy Hung8d31fd22023-06-26 19:20:57 -07002710 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002711 channelMask, frameCount,
2712 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002713 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002714 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002715 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002716
Glenn Kasten03003332013-08-06 15:40:54 -07002717 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2718 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002719 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002720 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002721 goto Exit;
2722 }
2723 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002724 {
Andy Hung972bec12023-08-31 16:13:39 -07002725 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002726 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002727 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002728 }
2729 }
Eric Laurent81784c32012-11-19 14:55:58 -08002730
Andy Hung116bc262023-06-20 18:56:17 -07002731 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002732 if (chain != 0) {
2733 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2734 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002735 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002736 chain->incTrackCnt();
2737 }
2738
Eric Laurent05067782016-06-01 18:27:28 -07002739 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002740 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2741 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2742 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002743 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002744 }
2745 }
2746
2747 lStatus = NO_ERROR;
2748
2749Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002750 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002751 return track;
2752}
2753
Andy Hung1bc088a2018-02-09 15:57:31 -08002754template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002755ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002756{
Andy Hungc0691382018-09-12 18:01:57 -07002757 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002758 const ssize_t index = mTracks.remove(track);
2759 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002760 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002761 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002762 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002763 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002764 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002765 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002766 }
2767 return index;
2768}
2769
Andy Hungee58e4a2023-07-07 13:47:37 -07002770uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002771{
2772 return latency;
2773}
2774
Andy Hungee58e4a2023-07-07 13:47:37 -07002775uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002776{
Andy Hung972bec12023-08-31 16:13:39 -07002777 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002778 return latency_l();
2779}
Andy Hungee58e4a2023-07-07 13:47:37 -07002780uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002781NO_THREAD_SAFETY_ANALYSIS
2782// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002783{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002784 uint32_t latency;
2785 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2786 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002787 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002788 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002789}
2790
Andy Hungee58e4a2023-07-07 13:47:37 -07002791void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002792{
Andy Hung972bec12023-08-31 16:13:39 -07002793 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002794 // Don't apply master volume in SW if our HAL can do it for us.
2795 if (mOutput && mOutput->audioHwDev &&
2796 mOutput->audioHwDev->canSetMasterVolume()) {
2797 mMasterVolume = 1.0;
2798 } else {
2799 mMasterVolume = value;
2800 }
2801}
2802
Andy Hungee58e4a2023-07-07 13:47:37 -07002803void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002804{
2805 mMasterBalance.store(balance);
2806}
2807
Andy Hungee58e4a2023-07-07 13:47:37 -07002808void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002809{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002810 if (isDuplicating()) {
2811 return;
2812 }
Andy Hung972bec12023-08-31 16:13:39 -07002813 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002814 // Don't apply master mute in SW if our HAL can do it for us.
2815 if (mOutput && mOutput->audioHwDev &&
2816 mOutput->audioHwDev->canSetMasterMute()) {
2817 mMasterMute = false;
2818 } else {
2819 mMasterMute = muted;
2820 }
2821}
2822
Andy Hungee58e4a2023-07-07 13:47:37 -07002823void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002824{
Andy Hung972bec12023-08-31 16:13:39 -07002825 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002826 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002827 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002828}
2829
Andy Hungee58e4a2023-07-07 13:47:37 -07002830void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002831{
Andy Hung972bec12023-08-31 16:13:39 -07002832 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002833 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002834 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002835}
2836
Andy Hungee58e4a2023-07-07 13:47:37 -07002837float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002838{
Andy Hung972bec12023-08-31 16:13:39 -07002839 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002840 return mStreamTypes[stream].volume;
2841}
2842
Andy Hungee58e4a2023-07-07 13:47:37 -07002843void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002844{
2845 mOutput->stream->setVolume(left, right);
2846}
2847
Andy Hungc5007f82023-08-29 14:26:09 -07002848// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002849status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002850{
2851 status_t status = ALREADY_EXISTS;
2852
Eric Laurent81784c32012-11-19 14:55:58 -08002853 if (mActiveTracks.indexOf(track) < 0) {
2854 // the track is newly added, make sure it fills up all its
2855 // buffers before playing. This is to ensure the client will
2856 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002857 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002858 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002859 // Because the track is not on the ActiveTracks,
2860 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002861 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002862 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002863 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002865 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002867 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002868 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002869 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 }
2871 return INVALID_OPERATION;
2872 }
2873 // abort if start is rejected by audio policy manager
2874 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002875 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2876 // current playback thread is reopened, which may happen when clients set preferred
2877 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2878 // immediately.
2879 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 }
2881#ifdef ADD_BATTERY_DATA
2882 // to track the speaker usage
2883 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2884#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002885 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 }
2887
Eric Laurent51716182016-02-29 18:00:56 -08002888 // set retry count for buffer fill
2889 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002890 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002891 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002892 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002893 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002894 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002895 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002896 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002897 track->retryCount() = kMaxTrackStartupRetries;
2898 track->fillingStatus() =
2899 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002900 }
2901
Andy Hung116bc262023-06-20 18:56:17 -07002902 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002903 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2904 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002905 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002906 // Unlock due to VibratorService will lock for this call and will
2907 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002908 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002909 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002910 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002911 std::optional<media::AudioVibratorInfo> vibratorInfo;
2912 {
2913 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2914 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002915 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002916 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002917 }
Andy Hungc5007f82023-08-29 14:26:09 -07002918 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002919 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002920 if (vibratorInfo) {
2921 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2922 }
2923
jiabin57303cc2018-12-18 15:45:57 -08002924 // Haptic playback should be enabled by vibrator service.
2925 if (track->getHapticPlaybackEnabled()) {
2926 // Disable haptic playback of all active track to ensure only
2927 // one track playing haptic if current track should play haptic.
2928 for (const auto &t : mActiveTracks) {
2929 t->setHapticPlaybackEnabled(false);
2930 }
jiabin245cdd92018-12-07 17:55:15 -08002931 }
jiabine70bc7f2020-06-30 22:07:55 -07002932
2933 // Set haptic intensity for effect
2934 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002935 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002936 }
jiabin245cdd92018-12-07 17:55:15 -08002937 }
2938
Andy Hung8d31fd22023-06-26 19:20:57 -07002939 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002940 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002941
2942 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2943 // all key changes are complete. It is possible that the threadLoop will begin
2944 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002945 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002946
Eric Laurentd0107bc2013-06-11 14:38:48 -07002947 if (chain != 0) {
2948 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2949 track->sessionId());
2950 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002951 }
2952
Andy Hungc2b11cb2020-04-22 09:04:01 -07002953 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002954 status = NO_ERROR;
2955 }
2956
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002957 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002958 return status;
2959}
2960
Andy Hungee58e4a2023-07-07 13:47:37 -07002961bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002962{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002963 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002964 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002965 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002966 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002967 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002968 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002969 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002970 if (track->isPausePending()) {
2971 track->pauseAck();
2972 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002973 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002974 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002975
2976 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002977}
2978
Andy Hungee58e4a2023-07-07 13:47:37 -07002979void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002980{
2981 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002982
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002983 String8 result;
2984 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002985 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002986
Eric Laurent81784c32012-11-19 14:55:58 -08002987 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002988 {
Andy Hung972bec12023-08-31 16:13:39 -07002989 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002990 mAudioTrackCallbacks.erase(track);
2991 }
Eric Laurent81784c32012-11-19 14:55:58 -08002992 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002993 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002994 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002995 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2996 mFastTrackAvailMask |= 1 << index;
2997 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002998 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002999 }
Andy Hung116bc262023-06-20 18:56:17 -07003000 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003001 if (chain != 0) {
3002 chain->decTrackCnt();
3003 }
3004}
3005
Andy Hungee58e4a2023-07-07 13:47:37 -07003006String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003007{
Andy Hung972bec12023-08-31 16:13:39 -07003008 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003009 String8 out_s8;
3010 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3011 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003012 }
Andy Hung920f6572022-10-06 12:09:49 -07003013 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003014}
3015
Andy Hungee58e4a2023-07-07 13:47:37 -07003016status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003017 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003018 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003019 return NO_INIT;
3020 }
3021 return mOutput->stream->selectPresentation(presentationId, programId);
3022}
3023
Andy Hungab65b182023-09-06 19:41:47 -07003024void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003025 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003026 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003027 sp<AudioIoDescriptor> desc;
3028 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003029 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003030 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003031 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003032 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003033 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3034 mSampleRate, mFormat, mChannelMask,
3035 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3036 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003037 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003038 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003039 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003040 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003041 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003042 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003043 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003044 break;
3045 }
Andy Hungab65b182023-09-06 19:41:47 -07003046 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003047}
3048
Andy Hungee58e4a2023-07-07 13:47:37 -07003049void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003050{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003051 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052}
3053
Andy Hungee58e4a2023-07-07 13:47:37 -07003054void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003055{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003056 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003057}
3058
Andy Hungee58e4a2023-07-07 13:47:37 -07003059void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003060{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003061 mCallbackThread->setAsyncError();
3062}
3063
Andy Hungee58e4a2023-07-07 13:47:37 -07003064void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003065 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003066{
Andy Hungee58e4a2023-07-07 13:47:37 -07003067 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003068 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003069 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003070 if (playbackThread == nullptr) {
3071 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3072 return;
3073 }
3074
jiabinf6eb4c32020-02-25 14:06:25 -08003075 audio_utils::metadata::Data metadata =
3076 audio_utils::metadata::dataFromByteString(metadataBs);
3077 if (metadata.empty()) {
3078 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3079 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3080 (int)metadataBs.size());
3081 return;
3082 }
3083
3084 audio_utils::metadata::ByteString metaDataStr =
3085 audio_utils::metadata::byteStringFromData(metadata);
3086 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003087 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003088 for (const auto& callbackPair : mAudioTrackCallbacks) {
3089 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003090 }
3091 }).detach();
3092}
3093
Andy Hungee58e4a2023-07-07 13:47:37 -07003094void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003095{
Andy Hung972bec12023-08-31 16:13:39 -07003096 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003097 // reject out of sequence requests
3098 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3099 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003100 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101 }
3102}
3103
Andy Hungee58e4a2023-07-07 13:47:37 -07003104void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105{
Andy Hung972bec12023-08-31 16:13:39 -07003106 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003107 // reject out of sequence requests
3108 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003109 // Register discontinuity when HW drain is completed because that can cause
3110 // the timestamp frame position to reset to 0 for direct and offload threads.
3111 // (Out of sequence requests are ignored, since the discontinuity would be handled
3112 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003113 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003114 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003115 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116 }
3117}
3118
Andy Hungee58e4a2023-07-07 13:47:37 -07003119void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003120NO_THREAD_SAFETY_ANALYSIS
3121// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003122{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003123 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003124 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3125 mSampleRate = audioConfig.sample_rate;
3126 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003127 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003128 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003129 }
Andy Hung81994d62023-07-20 21:44:14 -07003130 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003131 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3132 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003133 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003134
3135 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3136 mMixerChannelMask = mChannelMask;
3137 }
3138
Andy Hunge5412692014-05-16 11:25:07 -07003139 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003140 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003141
Eric Laurentf1f22e72021-07-13 14:04:14 +02003142 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3143
Phil Burkca5e6142015-07-14 09:42:29 -07003144 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003145 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003146 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003147 // Get format from the shim, which will be different than the HAL format
3148 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003149 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003150 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003151 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003152 }
Andy Hung81994d62023-07-20 21:44:14 -07003153 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003154 LOG_FATAL("HAL format %#x not supported for mixed output",
3155 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003156 }
Phil Burk062e67a2015-02-11 13:40:50 -08003157 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003158 result = mOutput->stream->getBufferSize(&mBufferSize);
3159 LOG_ALWAYS_FATAL_IF(result != OK,
3160 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003161 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003162 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003163 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003164 mFrameCount);
3165 }
3166
Eric Laurentd1f69b02014-12-15 14:33:13 -08003167 mHwSupportsPause = false;
3168 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003169 bool supportsPause = false, supportsResume = false;
3170 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3171 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003172 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003173 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003174 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003175 } else if (supportsResume) {
3176 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003177 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003178 }
3179 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003180 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3181 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3182 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003183
Andy Hungfbfc3952015-01-15 13:33:51 -08003184 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3185 // For best precision, we use float instead of the associated output
3186 // device format (typically PCM 16 bit).
3187
3188 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3189 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3190 mBufferSize = mFrameSize * mFrameCount;
3191
3192 // TODO: We currently use the associated output device channel mask and sample rate.
3193 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3194 // (if a valid mask) to avoid premature downmix.
3195 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3196 // instead of the output device sample rate to avoid loss of high frequency information.
3197 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3198 }
3199
Andy Hung09a50072014-02-27 14:30:47 -08003200 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003201 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003202 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003203 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3204 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003205 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3206 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003207
Eric Laurent81784c32012-11-19 14:55:58 -08003208 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3209 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3210 maxNormalFrameCount = maxNormalFrameCount & ~15;
3211 if (maxNormalFrameCount < minNormalFrameCount) {
3212 maxNormalFrameCount = minNormalFrameCount;
3213 }
3214 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3215 if (multiplier <= 1.0) {
3216 multiplier = 1.0;
3217 } else if (multiplier <= 2.0) {
3218 if (2 * mFrameCount <= maxNormalFrameCount) {
3219 multiplier = 2.0;
3220 } else {
3221 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3222 }
3223 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003224 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003225 }
3226 }
3227 mNormalFrameCount = multiplier * mFrameCount;
3228 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003229 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003230 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3231 }
Andy Hungab65b182023-09-06 19:41:47 -07003232 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3233 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003234
Andy Hung08fb1742015-05-31 23:22:10 -07003235 // Check if we want to throttle the processing to no more than 2x normal rate
3236 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003237 mThreadThrottleTimeMs = 0;
3238 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003239 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3240
Andy Hung010a1a12014-03-13 13:57:33 -07003241 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3242 // Originally this was int16_t[] array, need to remove legacy implications.
3243 free(mSinkBuffer);
3244 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003245
Andy Hung5b10a202014-03-13 13:59:29 -07003246 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3247 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3248 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003249 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003250
Andy Hung69aed5f2014-02-25 17:24:40 -08003251 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3252 // drives the output.
3253 free(mMixerBuffer);
3254 mMixerBuffer = NULL;
3255 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003256 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003257 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003258 * audio_bytes_per_sample(mMixerBufferFormat);
3259 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3260 }
Andy Hung98ef9782014-03-04 14:46:50 -08003261 free(mEffectBuffer);
3262 mEffectBuffer = NULL;
3263 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003264 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003265 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003266 * audio_bytes_per_sample(mEffectBufferFormat);
3267 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3268 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003269
Eric Laurentb62d0362021-10-26 17:40:18 +02003270 if (mType == SPATIALIZER) {
3271 free(mPostSpatializerBuffer);
3272 mPostSpatializerBuffer = nullptr;
3273 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3274 * audio_bytes_per_sample(mEffectBufferFormat);
3275 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3276 }
3277
Mikhail Naganov55773032020-10-01 15:08:13 -07003278 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3279 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003280 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3281 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003282 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003283
Eric Laurent81784c32012-11-19 14:55:58 -08003284 // force reconfiguration of effect chains and engines to take new buffer size and audio
3285 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003286 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003287 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3288 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003289 // create a copy of mEffectChains as calling moveEffectChain_ll()
3290 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003291 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003292 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003293 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003294 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003295 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003296
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003297 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003298 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003299 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003300 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003301 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3302 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3303 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3304 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3305 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3306 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3307 (int32_t)mHapticChannelMask)
3308 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3309 (int32_t)mHapticChannelCount)
3310 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003311 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003312 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3313 (int32_t)mFrameCount) // sic - added HAL
3314 ;
3315 uint32_t latencyMs;
3316 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3317 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3318 }
3319 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003320}
3321
Andy Hungee58e4a2023-07-07 13:47:37 -07003322ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003323{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003324 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003325 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003326 }
3327 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003328 static const bool stereo_spatialization_property =
3329 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3330 const bool stereo_spatialization_enabled =
3331 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3332 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003333 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3334 for (const sp<IAfTrack>& track : mActiveTracks) {
3335 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3336 allSessionsMetadata[track->sessionId()];
3337 auto backInserter = std::back_inserter(sessionMetadata);
3338 // No track is invalid as this is called after prepareTrack_l in the same
3339 // critical section
3340 track->copyMetadataTo(backInserter);
3341 }
3342 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3343 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3344 metadata.tracks.insert(metadata.tracks.end(),
3345 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3346 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3347 chain->sendMetadata_l(sessionTrackMetadata, {});
3348 }
3349 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3350 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3351 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3352 }
3353 }
3354 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3355 chain->sendMetadata_l(metadata.tracks, {});
3356 }
3357 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3358 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3359 }
3360 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3361 chain->sendMetadata_l(metadata.tracks, {});
3362 }
3363 } else {
3364 auto backInserter = std::back_inserter(metadata.tracks);
3365 for (const sp<IAfTrack>& track : mActiveTracks) {
3366 // No track is invalid as this is called after prepareTrack_l in the same
3367 // critical section
3368 track->copyMetadataTo(backInserter);
3369 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003370 }
Kevin Rocard12381092018-04-11 09:19:59 -07003371 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003372 MetadataUpdate change;
3373 change.playbackMetadataUpdate = metadata.tracks;
3374 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003375}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003376
Andy Hungee58e4a2023-07-07 13:47:37 -07003377void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003378 const StreamOutHalInterface::SourceMetadata& metadata)
3379{
3380 mOutput->stream->updateSourceMetadata(metadata);
3381};
3382
Andy Hungee58e4a2023-07-07 13:47:37 -07003383status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003384 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003385{
3386 if (halFrames == NULL || dspFrames == NULL) {
3387 return BAD_VALUE;
3388 }
Andy Hung972bec12023-08-31 16:13:39 -07003389 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003390 if (initCheck() != NO_ERROR) {
3391 return INVALID_OPERATION;
3392 }
Andy Hung818e7a32016-02-16 18:08:07 -08003393 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003394 *halFrames = framesWritten;
3395
3396 if (isSuspended()) {
3397 // return an estimation of rendered frames when the output is suspended
3398 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003399 *dspFrames = (uint32_t)
3400 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003401 return NO_ERROR;
3402 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003403 status_t status;
3404 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003405 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003406 *dspFrames = (size_t)frames;
3407 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003408 }
3409}
3410
Andy Hungee58e4a2023-07-07 13:47:37 -07003411product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003412{
3413 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3414 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3415 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003416 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003417 }
3418 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003419 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003420 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003421 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003422 }
3423 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003424 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003425}
3426
3427
Andy Hungee58e4a2023-07-07 13:47:37 -07003428AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003429{
Andy Hung972bec12023-08-31 16:13:39 -07003430 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003431 return mOutput;
3432}
3433
Andy Hungee58e4a2023-07-07 13:47:37 -07003434AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003435{
Andy Hung972bec12023-08-31 16:13:39 -07003436 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003437 AudioStreamOut *output = mOutput;
3438 mOutput = NULL;
3439 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3440 // must push a NULL and wait for ack
3441 mOutputSink.clear();
3442 mPipeSink.clear();
3443 mNormalSink.clear();
3444 return output;
3445}
3446
Andy Hungc5007f82023-08-29 14:26:09 -07003447// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003448sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003449{
3450 if (mOutput == NULL) {
3451 return NULL;
3452 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003453 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003454}
3455
Andy Hungee58e4a2023-07-07 13:47:37 -07003456uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003457{
3458 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3459}
3460
Andy Hungee58e4a2023-07-07 13:47:37 -07003461status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003462{
3463 if (!isValidSyncEvent(event)) {
3464 return BAD_VALUE;
3465 }
3466
Andy Hung972bec12023-08-31 16:13:39 -07003467 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003468
3469 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003470 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003471 if (event->triggerSession() == track->sessionId()) {
3472 (void) track->setSyncEvent(event);
3473 return NO_ERROR;
3474 }
3475 }
3476
3477 return NAME_NOT_FOUND;
3478}
3479
Andy Hungee58e4a2023-07-07 13:47:37 -07003480bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003481{
3482 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3483}
3484
Andy Hungee58e4a2023-07-07 13:47:37 -07003485void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003486 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003487{
Andy Hungfe726a62018-09-27 15:17:25 -07003488 // Miscellaneous track cleanup when removed from the active list,
3489 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003490#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003491 for (const auto& track : tracksToRemove) {
3492 if (track->isExternalTrack()) {
3493 // to track the speaker usage
3494 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003495 }
3496 }
Andy Hungfe726a62018-09-27 15:17:25 -07003497#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003498}
3499
Andy Hungee58e4a2023-07-07 13:47:37 -07003500void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003501{
3502 if (!mMasterMute) {
3503 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003504 if (mOutDeviceTypeAddrs.empty()) {
3505 ALOGD("ro.audio.silent is ignored since no output device is set");
3506 return;
3507 }
Andy Hungab65b182023-09-06 19:41:47 -07003508 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003509 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3510 return;
3511 }
Eric Laurent81784c32012-11-19 14:55:58 -08003512 if (property_get("ro.audio.silent", value, "0") > 0) {
3513 char *endptr;
3514 unsigned long ul = strtoul(value, &endptr, 0);
3515 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003516 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003517 // The setprop command will not allow a property to be changed after
3518 // the first time it is set, so we don't have to worry about un-muting.
3519 setMasterMute_l(true);
3520 }
3521 }
3522 }
3523}
3524
3525// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003526ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003527{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003528 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003529 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003530 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003531 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003532
3533 // If an NBAIO sink is present, use it to write the normal mixer's submix
3534 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003535
Andy Hung010a1a12014-03-13 13:57:33 -07003536 const size_t count = mBytesRemaining / mFrameSize;
3537
Simon Wilson2d590962012-11-29 15:18:50 -08003538 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003539 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003540 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003541 if (screenState != mScreenState) {
3542 mScreenState = screenState;
3543 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3544 if (pipe != NULL) {
3545 pipe->setAvgFrames((mScreenState & 1) ?
3546 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3547 }
3548 }
Andy Hung010a1a12014-03-13 13:57:33 -07003549 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003550 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003551
Eric Laurent81784c32012-11-19 14:55:58 -08003552 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003553 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003554
Andy Hung8946a282018-04-19 20:04:56 -07003555#ifdef TEE_SINK
3556 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3557#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003558 } else {
3559 bytesWritten = framesWritten;
3560 }
3561 // otherwise use the HAL / AudioStreamOut directly
3562 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003563 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003564
Eric Laurentbfb1b832013-01-07 09:53:42 -08003565 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003566 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3567 mWriteAckSequence += 2;
3568 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003569 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003570 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003572 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003573 // FIXME We should have an implementation of timestamps for direct output threads.
3574 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003575 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003576 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003577
Eric Laurentbfb1b832013-01-07 09:53:42 -08003578 if (mUseAsyncWrite &&
3579 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3580 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003581 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003582 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003583 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003584 }
Eric Laurent81784c32012-11-19 14:55:58 -08003585 }
3586
Eric Laurent81784c32012-11-19 14:55:58 -08003587 mNumWrites++;
3588 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003589 if (mStandby) {
3590 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003591 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003592 mStandby = false;
3593 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003594 return bytesWritten;
3595}
3596
Andy Hungc5007f82023-08-29 14:26:09 -07003597// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003598void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003599 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003600{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003601 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003602 if (outputSink != nullptr) {
3603 outputSink->startMelComputation(processor);
3604 }
Vlad Popab042ee62022-10-20 18:05:00 +02003605}
3606
Andy Hungc5007f82023-08-29 14:26:09 -07003607// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003608void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003609{
3610 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003611 if (outputSink != nullptr) {
3612 outputSink->stopMelComputation();
3613 }
Vlad Popab042ee62022-10-20 18:05:00 +02003614}
3615
Andy Hungee58e4a2023-07-07 13:47:37 -07003616void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003618 bool supportsDrain = false;
3619 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003620 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3621 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003622 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3623 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003624 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003625 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003627 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003628 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003629 }
3630}
3631
Andy Hungee58e4a2023-07-07 13:47:37 -07003632void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003633{
Eric Laurent275e8e92014-11-30 15:14:47 -08003634 {
Andy Hung972bec12023-08-31 16:13:39 -07003635 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003636 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003637 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003638 track->invalidate();
3639 }
Andy Hungdae27702016-10-31 14:01:16 -07003640 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3641 // After we exit there are no more track changes sent to BatteryNotifier
3642 // because that requires an active threadLoop.
3643 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3644 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003645 }
Eric Laurent81784c32012-11-19 14:55:58 -08003646}
3647
3648/*
3649The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003650 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003651 - mActiveSleepTimeUs from activeSleepTimeUs()
3652 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003653 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3654 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003655 - maxPeriod from frame count and sample rate (MIXER only)
3656
3657The parameters that affect these derived values are:
3658 - frame count
3659 - frame size
3660 - sample rate
3661 - device type: A2DP or not
3662 - device latency
3663 - format: PCM or not
3664 - active sleep time
3665 - idle sleep time
3666*/
3667
Andy Hungee58e4a2023-07-07 13:47:37 -07003668void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003669{
Andy Hung25c2dac2014-02-27 14:56:00 -08003670 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003671 mActiveSleepTimeUs = activeSleepTimeUs();
3672 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003673
Andy Hung8fe87eb2023-07-20 21:31:38 -07003674 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003675
Eric Laurent42537be2016-01-08 17:16:42 -08003676 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3677 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003678 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003679 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3680 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3681 }
3682 }
Eric Laurent81784c32012-11-19 14:55:58 -08003683}
3684
Andy Hungee58e4a2023-07-07 13:47:37 -07003685bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003686{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003687 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003688 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003689 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003690 size_t size = mTracks.size();
3691 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003692 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003693 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003694 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003695 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003696 }
3697 }
Eric Laurent13084622016-05-17 10:51:49 -07003698 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003699}
3700
Andy Hungee58e4a2023-07-07 13:47:37 -07003701void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003702{
Andy Hung972bec12023-08-31 16:13:39 -07003703 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003704 invalidateTracks_l(streamType);
3705}
3706
Andy Hungee58e4a2023-07-07 13:47:37 -07003707void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003708 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003709 invalidateTracks_l(portIds);
3710}
3711
Andy Hungee58e4a2023-07-07 13:47:37 -07003712bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003713 bool trackMatch = false;
3714 const size_t size = mTracks.size();
3715 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003716 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003717 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3718 t->invalidate();
3719 portIds.erase(t->portId());
3720 trackMatch = true;
3721 }
3722 if (portIds.empty()) {
3723 break;
3724 }
3725 }
3726 return trackMatch;
3727}
3728
jiabinf042b9b2021-05-07 23:46:28 +00003729// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003730IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003731 audio_port_handle_t trackPortId) {
3732 for (size_t i = 0; i < mTracks.size(); i++) {
3733 if (mTracks[i]->portId() == trackPortId) {
3734 return mTracks[i].get();
3735 }
3736 }
3737 return nullptr;
3738}
3739
Andy Hungee58e4a2023-07-07 13:47:37 -07003740status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003741{
Glenn Kastend848eb42016-03-08 13:42:11 -08003742 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003743 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003744 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003745
Andy Hungd3639922022-04-28 18:00:49 -07003746 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003747 if (!audio_is_global_session(session)) {
3748 // player sessions on a spatializer output will use a dedicated input buffer and
3749 // will either output multi channel to mEffectBuffer if the track is spatilaized
3750 // or stereo to mPostSpatializerBuffer if not spatialized.
3751 uint32_t channelMask;
3752 bool isSessionSpatialized =
3753 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3754 if (isSessionSpatialized) {
3755 channelMask = mMixerChannelMask;
3756 } else {
3757 channelMask = mChannelMask;
3758 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003759 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003760 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003761 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003762 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003763 &halInBuffer);
3764 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003765
Andy Hung583043b2023-07-17 17:05:00 -07003766 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003767 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3768 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3769 &halOutBuffer);
3770 if (result != OK) return result;
3771
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003772 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003773
Mikhail Naganov022b9952017-01-04 16:36:51 -08003774 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3775 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003776 } else {
3777 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3778 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3779 // mPostSpatializerBuffer as output buffer
3780 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003781 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003782 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3783 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003784 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003785 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3786 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003787
Eric Laurentb62d0362021-10-26 17:40:18 +02003788 if (session == AUDIO_SESSION_DEVICE) {
3789 halInBuffer = halOutBuffer;
3790 }
3791 }
3792 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003793 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003794 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3795 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3796 &halInBuffer);
3797 if (result != OK) return result;
3798 halOutBuffer = halInBuffer;
3799 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3800 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003801 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003802 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003803 // Only one effect chain can be present in direct output thread and it uses
3804 // the sink buffer as input
3805 if (mType != DIRECT) {
3806 size_t numSamples = mNormalFrameCount
3807 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3808 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003809 const status_t allocateStatus =
3810 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003811 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003812 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003813 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003814
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003815 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003816 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3817 buffer, session);
3818 }
3819 }
3820 }
3821
3822 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003823 // Attach all tracks with same session ID to this chain.
3824 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003825 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003826 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003827 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3828 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003829 track->setMainBuffer(buffer);
3830 chain->incTrackCnt();
3831 }
3832 }
3833
3834 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003835 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003836 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003837 ALOGV("addEffectChain_l() activating track %p on session %d",
3838 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003839 chain->incActiveTrackCnt();
3840 }
3841 }
3842 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003843
Eric Laurentaaa44472014-09-12 17:41:50 -07003844 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003845 chain->setInBuffer(halInBuffer);
3846 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003847 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3848 // chains list in order to be processed last as it contains output device effects.
3849 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3850 // processing effects specific to an output stream before effects applied to all streams
3851 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003852 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3853 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003854 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003855 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003856 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003857 // Effect chain for other sessions are inserted at beginning of effect
3858 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003859 // sessions is not important.
3860 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003861 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3862 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003863 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003864 size_t size = mEffectChains.size();
3865 size_t i = 0;
3866 for (i = 0; i < size; i++) {
3867 if (mEffectChains[i]->sessionId() < session) {
3868 break;
3869 }
3870 }
3871 mEffectChains.insertAt(chain, i);
3872 checkSuspendOnAddEffectChain_l(chain);
3873
3874 return NO_ERROR;
3875}
3876
Andy Hungee58e4a2023-07-07 13:47:37 -07003877size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003878{
Glenn Kastend848eb42016-03-08 13:42:11 -08003879 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003880
3881 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3882
3883 for (size_t i = 0; i < mEffectChains.size(); i++) {
3884 if (chain == mEffectChains[i]) {
3885 mEffectChains.removeAt(i);
3886 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003887 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003888 if (session == track->sessionId()) {
3889 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3890 chain.get(), session);
3891 chain->decActiveTrackCnt();
3892 }
3893 }
3894
3895 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003896 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003897 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003898 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003899 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003900 chain->decTrackCnt();
3901 }
3902 }
3903 break;
3904 }
3905 }
3906 return mEffectChains.size();
3907}
3908
Andy Hungee58e4a2023-07-07 13:47:37 -07003909status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003910 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003911{
Andy Hung972bec12023-08-31 16:13:39 -07003912 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003913 return attachAuxEffect_l(track, EffectId);
3914}
3915
Andy Hungee58e4a2023-07-07 13:47:37 -07003916status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003917 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003918{
3919 status_t status = NO_ERROR;
3920
3921 if (EffectId == 0) {
3922 track->setAuxBuffer(0, NULL);
3923 } else {
3924 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003925 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003926 if (effect != 0) {
3927 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3928 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3929 } else {
3930 status = INVALID_OPERATION;
3931 }
3932 } else {
3933 status = BAD_VALUE;
3934 }
3935 }
3936 return status;
3937}
3938
Andy Hungee58e4a2023-07-07 13:47:37 -07003939void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003940{
3941 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003942 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003943 if (track->auxEffectId() == effectId) {
3944 attachAuxEffect_l(track, 0);
3945 }
3946 }
3947}
3948
Andy Hungee58e4a2023-07-07 13:47:37 -07003949bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003950NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003951{
Andy Hung78d8d952023-05-30 18:10:23 -07003952 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003953
Andy Hung077d62e2023-10-03 10:49:34 -07003954 if (mType == SPATIALIZER) {
3955 const pid_t tid = getTid();
3956 if (tid == -1) { // odd: we are here, we must be a running thread.
3957 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3958 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003959 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3960 if (priorityBoost > 0) {
3961 stream()->setHalThreadPriority(priorityBoost);
3962 }
Andy Hung077d62e2023-10-03 10:49:34 -07003963 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003964 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3965 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3966 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3967 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3968 // only on ARC.
3969 const pid_t tid = getTid();
3970 if (tid == -1) {
3971 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
3972 } else {
3973 const status_t status = requestPriority(getpid(),
3974 tid,
3975 kPriorityPlaybackThreadArc,
3976 false /* isForApp */,
3977 true /* asynchronous */);
3978 if (status != OK) {
3979 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
3980 status);
3981 } else {
3982 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
3983 }
3984 }
Andy Hung077d62e2023-10-03 10:49:34 -07003985 }
3986
Andy Hung8d31fd22023-06-26 19:20:57 -07003987 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003988
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003989 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003990 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003991
3992 // MIXER
3993 nsecs_t lastWarning = 0;
3994
3995 // DUPLICATING
3996 // FIXME could this be made local to while loop?
3997 writeFrames = 0;
3998
3999 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004000 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004001
Andy Hungd3639922022-04-28 18:00:49 -07004002 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004003 sleepTimeShift = 0;
4004 }
4005
4006 CpuStats cpuStats;
4007 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4008
4009 acquireWakeLock();
4010
Glenn Kasteneef598c2017-04-03 14:41:13 -07004011 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4012 // thread associated with this PlaybackThread.
4013 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4014 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004015 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4016 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004017 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004018 const char *logString = NULL;
4019
rago1bb90822017-05-02 18:31:48 -07004020 // Estimated time for next buffer to be written to hal. This is used only on
4021 // suspended mode (for now) to help schedule the wait time until next iteration.
4022 nsecs_t timeLoopNextNs = 0;
4023
Eric Laurent664539d2013-09-23 18:24:31 -07004024 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004025
Andy Hung2dbffc22018-08-08 18:50:41 -07004026 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004027
Eric Laurentb3f315a2021-07-13 15:09:05 +02004028 sendCheckOutputStageEffectsEvent();
4029
Andy Hung446f4df2019-02-21 12:26:41 -08004030 // loopCount is used for statistics and diagnostics.
4031 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004032 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004033 // Log merge requests are performed during AudioFlinger binder transactions, but
4034 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004035 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004036
Eric Laurent81784c32012-11-19 14:55:58 -08004037 cpuStats.sample(myName);
4038
Andy Hung116bc262023-06-20 18:56:17 -07004039 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004040 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004041 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004042 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004043
Andy Hung2dbffc22018-08-08 18:50:41 -07004044 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4045 //
Andy Hungc5007f82023-08-29 14:26:09 -07004046 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004047 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004048 // Here, we try for the AF lock, but do not block on it as the latency
4049 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004050 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004051 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004052 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004053 status_t status = INVALID_OPERATION;
4054 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004055 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004056 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004057 && swPatches.size() > 0) {
4058 status = swPatches[0].getLatencyMs_l(&latencyMs);
4059 downstreamPatchHandle = swPatches[0].getPatchHandle();
4060 }
4061 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004062 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004063 lastDownstreamPatchHandle = downstreamPatchHandle;
4064 }
4065 if (status == OK) {
4066 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004067 // latency of 5 seconds).
4068 const double minLatency = 0., maxLatency = 5000.;
4069 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004070 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004071 } else {
4072 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004073 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004074 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004075 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004076 }
Andy Hung583043b2023-07-17 17:05:00 -07004077 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004078 }
4079 } else {
4080 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4081 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004082 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004083 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4084 }
4085 }
4086
Eric Laurentb3f315a2021-07-13 15:09:05 +02004087 if (mCheckOutputStageEffects.exchange(false)) {
4088 checkOutputStageEffects();
4089 }
4090
Vlad Popa7e81cea2023-01-19 16:34:16 +01004091 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004092 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004093
Andy Hungc5007f82023-08-29 14:26:09 -07004094 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004095
Eric Laurent021cf962014-05-13 10:18:14 -07004096 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004097 if (mCheckOutputStageEffects.load()) {
4098 continue;
4099 }
Eric Laurent10351942014-05-08 18:49:52 -07004100
Andy Hungc5007f82023-08-29 14:26:09 -07004101 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004102 if (logString != NULL) {
4103 mNBLogWriter->logTimestamp();
4104 mNBLogWriter->log(logString);
4105 logString = NULL;
4106 }
4107
Dean Wheatley12473e92021-03-18 23:00:55 +11004108 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004109
Eric Laurent81784c32012-11-19 14:55:58 -08004110 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004111 if (mSignalPending) {
4112 // A signal was raised while we were unlocked
4113 mSignalPending = false;
4114 } else if (waitingAsyncCallback_l()) {
4115 if (exitPending()) {
4116 break;
4117 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004118 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004119 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004120 releaseWakeLock_l();
4121 released = true;
4122 }
Andy Hung10cbff12017-02-21 17:30:14 -08004123
4124 const int64_t waitNs = computeWaitTimeNs_l();
4125 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004126 std::cv_status cvstatus =
4127 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4128 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004129 mSignalPending = true; // if timeout recheck everything
4130 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004131 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004132 if (released) {
4133 acquireWakeLock_l();
4134 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004135 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4136 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004137
4138 continue;
4139 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004140 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004141 isSuspended()) {
4142 // put audio hardware into standby after short delay
4143 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004144
4145 threadLoop_standby();
4146
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004147 // This is where we go into standby
4148 if (!mStandby) {
4149 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004150 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004151 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004152 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004153 }
Andy Hungd0979812019-02-21 15:51:44 -08004154 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004155 }
4156
Eric Tan39ec8d62018-07-24 09:49:29 -07004157 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004158 // we're about to wait, flush the binder command buffer
4159 IPCThreadState::self()->flushCommands();
4160
4161 clearOutputTracks();
4162
4163 if (exitPending()) {
4164 break;
4165 }
4166
4167 releaseWakeLock_l();
4168 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004169 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004170 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004171 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004172 acquireWakeLock_l();
4173
4174 mMixerStatus = MIXER_IDLE;
4175 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4176 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004177 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004178 checkSilentMode_l();
4179
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004180 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4181 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004182 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004183 sleepTimeShift = 0;
4184 }
4185
4186 continue;
4187 }
4188 }
Eric Laurent81784c32012-11-19 14:55:58 -08004189 // mMixerStatusIgnoringFastTracks is also updated internally
4190 mMixerStatus = prepareTracks_l(&tracksToRemove);
4191
Andy Hungab65b182023-09-06 19:41:47 -07004192 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004193
Vlad Popa7e81cea2023-01-19 16:34:16 +01004194 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004195
Andy Hungf302e812024-01-26 11:55:15 -08004196 // Acquire a local copy of active tracks with lock (release w/o lock).
4197 //
4198 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4199 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4200 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4201 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4202
4203 setHalLatencyMode_l();
4204
4205 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4206 // so this is done before we lock our effect chains.
4207 for (const auto& track : mActiveTracks) {
4208 track->updateTeePatches_l();
4209 }
4210
4211 // signal actual start of output stream when the render position reported by
4212 // the kernel starts moving.
4213 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4214 && (mKernelPositionOnStandby
4215 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4216 mHalStarted = true;
4217 mWaitHalStartCV.notify_all();
4218 }
4219
Eric Laurent81784c32012-11-19 14:55:58 -08004220 // prevent any changes in effect chain list and in each effect chain
4221 // during mixing and effect process as the audio buffers could be deleted
4222 // or modified if an effect is created or deleted
4223 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004224
4225 // Determine which session to pick up haptic data.
4226 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004227 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004228 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004229 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004230 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004231 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004232 if (effectChain != nullptr
4233 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004234 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004235 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004236 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004237 break;
4238 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004239 if (activeHapticSessionId == AUDIO_SESSION_NONE
4240 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004241 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004242 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004243 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004244 }
4245 }
4246 }
Andy Hungc5007f82023-08-29 14:26:09 -07004247 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004248
Eric Laurentbfb1b832013-01-07 09:53:42 -08004249 if (mBytesRemaining == 0) {
4250 mCurrentWriteLength = 0;
4251 if (mMixerStatus == MIXER_TRACKS_READY) {
4252 // threadLoop_mix() sets mCurrentWriteLength
4253 threadLoop_mix();
4254 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4255 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004256 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004257 // must be written to HAL
4258 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004259 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004260 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004261
4262 // Tally underrun frames as we are inserting 0s here.
4263 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004264 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004265 && !track->isStopped()
4266 && !track->isPaused()
4267 && !track->isTerminated()) {
4268 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4269 __func__, track->id(), track->getTrackStateAsString(),
4270 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004271 track->audioTrackServerProxy()->tallyUnderrunFrames(
4272 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004273 }
4274 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004275 }
4276 }
Andy Hung98ef9782014-03-04 14:46:50 -08004277 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004278 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004279 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004280 // or mSinkBuffer (if there are no effects and there is no data already copied to
4281 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004282 //
4283 // This is done pre-effects computation; if effects change to
4284 // support higher precision, this needs to move.
4285 //
4286 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004287 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004288 uint32_t mixerChannelCount = mEffectBufferValid ?
4289 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004290 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004291 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4292 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4293
David Li88ee0902022-06-22 10:01:21 +08004294 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4295 // do these processes after effects are applied.
4296 if (!mEffectBufferValid) {
4297 // mono blend occurs for mixer threads only (not direct or offloaded)
4298 // and is handled here if we're going directly to the sink.
4299 if (requireMonoBlend()) {
4300 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4301 mNormalFrameCount, true /*limit*/);
4302 }
Andy Hung2ddee192015-12-18 17:34:44 -08004303
David Li88ee0902022-06-22 10:01:21 +08004304 if (!hasFastMixer()) {
4305 // Balance must take effect after mono conversion.
4306 // We do it here if there is no FastMixer.
4307 // mBalance detects zero balance within the class for speed
4308 // (not needed here).
4309 mBalance.setBalance(mMasterBalance.load());
4310 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4311 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004312 }
4313
Andy Hung98ef9782014-03-04 14:46:50 -08004314 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004315 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004316
4317 // If we're going directly to the sink and there are haptic channels,
4318 // we should adjust channels as the sample data is partially interleaved
4319 // in this case.
4320 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4321 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4322 mChannelCount + mHapticChannelCount,
4323 audio_bytes_per_sample(format),
4324 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4325 }
Andy Hung98ef9782014-03-04 14:46:50 -08004326 }
4327
Eric Laurentbfb1b832013-01-07 09:53:42 -08004328 mBytesRemaining = mCurrentWriteLength;
4329 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004330 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4331 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4332 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4333 mBytesWritten += mBytesRemaining;
4334 mFramesWritten += framesRemaining;
4335 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336 mBytesRemaining = 0;
4337 }
Eric Laurent81784c32012-11-19 14:55:58 -08004338
Eric Laurentbfb1b832013-01-07 09:53:42 -08004339 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004340 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004341 for (size_t i = 0; i < effectChains.size(); i ++) {
4342 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004343 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004344 if (activeHapticSessionId != AUDIO_SESSION_NONE
4345 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004346 // Haptic data is active in this case, copy it directly from
4347 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004348 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4349 audio_channel_count_from_out_mask(mMixerChannelMask) :
4350 mChannelCount;
4351 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4352 hapticSessionChannelCount = mChannelCount;
4353 }
4354
jiabin47affe52019-04-04 18:02:07 -07004355 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004356 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004357 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004358 memcpy_by_audio_format(
4359 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004360 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004361 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004362 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004363 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004364 }
Eric Laurent81784c32012-11-19 14:55:58 -08004365 }
4366 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004367 // Process effect chains for offloaded thread even if no audio
4368 // was read from audio track: process only updates effect state
4369 // and thus does have to be synchronized with audio writes but may have
4370 // to be called while waiting for async write callback
4371 if (mType == OFFLOAD) {
4372 for (size_t i = 0; i < effectChains.size(); i ++) {
4373 effectChains[i]->process_l();
4374 }
4375 }
Eric Laurent81784c32012-11-19 14:55:58 -08004376
Andy Hung98ef9782014-03-04 14:46:50 -08004377 // Only if the Effects buffer is enabled and there is data in the
4378 // Effects buffer (buffer valid), we need to
4379 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004380 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004381 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004382 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004383 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004384 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004385 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004386 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004387 }
4388
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004389 if (!hasFastMixer()) {
4390 // Balance must take effect after mono conversion.
4391 // We do it here if there is no FastMixer.
4392 // mBalance detects zero balance within the class for speed (not needed here).
4393 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004394 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004395 }
4396
Eric Laurentb62d0362021-10-26 17:40:18 +02004397 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4398 // mPostSpatializerBuffer if the haptics track is spatialized.
4399 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4400 // For other thread types, the haptics channels are already in mEffectBuffer.
4401 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4402 const size_t srcBufferSize = mNormalFrameCount *
4403 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4404 mEffectBufferFormat);
4405 const size_t dstBufferSize = mNormalFrameCount
4406 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4407
4408 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4409 mEffectBufferFormat,
4410 (uint8_t*)mEffectBuffer + srcBufferSize,
4411 mEffectBufferFormat,
4412 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004413 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004414 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4415 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4416 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4417 // Clamp PCM float values more than this distance from 0 to insulate
4418 // a HAL which doesn't handle NaN correctly.
4419 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4420 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4421 static_cast<const float*>(effectBuffer),
4422 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4423 } else {
4424 memcpy_by_audio_format(mSinkBuffer, mFormat,
4425 effectBuffer, mEffectBufferFormat, framesToCopy);
4426 }
jiabin245cdd92018-12-07 17:55:15 -08004427 // The sample data is partially interleaved when haptic channels exist,
4428 // we need to adjust channels here.
4429 if (mHapticChannelCount > 0) {
4430 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4431 mChannelCount + mHapticChannelCount,
4432 audio_bytes_per_sample(mFormat),
4433 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4434 }
Andy Hung98ef9782014-03-04 14:46:50 -08004435 }
4436
Eric Laurent81784c32012-11-19 14:55:58 -08004437 // enable changes in effect chain
4438 unlockEffectChains(effectChains);
4439
Vlad Popafce10862023-02-03 10:37:07 +01004440 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004441 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004442 metadataUpdate.playbackMetadataUpdate);
4443 }
4444
Eric Laurentbfb1b832013-01-07 09:53:42 -08004445 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004446 // mSleepTimeUs == 0 means we must write to audio hardware
4447 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004448 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004449 // writePeriodNs is updated >= 0 when ret > 0.
4450 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004451 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004452 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004453 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004454 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004455 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456 if (ret < 0) {
4457 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004458 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004459 mBytesWritten += ret;
4460 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004461 const int64_t frames = ret / mFrameSize;
4462 mFramesWritten += frames;
4463
4464 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4465 // process information relating to write time.
4466 if (audio_has_proportional_frames(mFormat)) {
4467 // we are in a continuous mixing cycle
4468 if (mMixerStatus == MIXER_TRACKS_READY &&
4469 loopCount == lastLoopCountWritten + 1) {
4470
4471 const double jitterMs =
4472 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4473 {frames, writePeriodNs},
4474 {0, 0} /* lastTimestamp */, mSampleRate);
4475 const double processMs =
4476 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4477
Andy Hung972bec12023-08-31 16:13:39 -07004478 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004479 mIoJitterMs.add(jitterMs);
4480 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004481
4482 if (mPipeSink.get() != nullptr) {
4483 // Using the Monopipe availableToWrite, we estimate the current
4484 // buffer size.
4485 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4486 const ssize_t
4487 availableToWrite = mPipeSink->availableToWrite();
4488 const size_t pipeFrames = monoPipe->maxFrames();
4489 const size_t
4490 remainingFrames = pipeFrames - max(availableToWrite, 0);
4491 mMonopipePipeDepthStats.add(remainingFrames);
4492 }
Andy Hung446f4df2019-02-21 12:26:41 -08004493 }
4494
4495 // write blocked detection
4496 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004497 if ((mType == MIXER || mType == SPATIALIZER)
4498 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004499 mNumDelayedWrites++;
4500 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4501 ATRACE_NAME("underrun");
4502 ALOGW("write blocked for %lld msecs, "
4503 "%d delayed writes, thread %d",
4504 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4505 mNumDelayedWrites, mId);
4506 lastWarning = lastIoEndNs;
4507 }
4508 }
4509 }
4510 // update timing info.
4511 mLastIoBeginNs = lastIoBeginNs;
4512 mLastIoEndNs = lastIoEndNs;
4513 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004514 }
4515 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4516 (mMixerStatus == MIXER_DRAIN_ALL)) {
4517 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004518 }
Andy Hungd3639922022-04-28 18:00:49 -07004519 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004520
4521 if (mThreadThrottle
4522 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004523 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004524 // Limit MixerThread data processing to no more than twice the
4525 // expected processing rate.
4526 //
4527 // This helps prevent underruns with NuPlayer and other applications
4528 // which may set up buffers that are close to the minimum size, or use
4529 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4530 //
4531 // The throttle smooths out sudden large data drains from the device,
4532 // e.g. when it comes out of standby, which often causes problems with
4533 // (1) mixer threads without a fast mixer (which has its own warm-up)
4534 // (2) minimum buffer sized tracks (even if the track is full,
4535 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004536 //
4537 // Total time spent in last processing cycle equals time spent in
4538 // 1. threadLoop_write, as well as time spent in
4539 // 2. threadLoop_mix (significant for heavy mixing, especially
4540 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004541
Andy Hung446f4df2019-02-21 12:26:41 -08004542 // it's OK if deltaMs is an overestimate.
4543
4544 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004545
Ivan Lozanoea04d392017-11-07 14:37:07 -08004546 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004547 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004548 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004549
Andy Hung08fb1742015-05-31 23:22:10 -07004550 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004551 // notify of throttle start on verbose log
4552 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4553 "mixer(%p) throttle begin:"
4554 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004555 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004556 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004557 // Throttle must be attributed to the previous mixer loop's write time
4558 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004559 // This also ensures proper timing statistics.
4560 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004561 } else {
4562 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4563 if (diff > 0) {
4564 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004565 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004566 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004567 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004568 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004569 outDeviceTypes_l(),
4570 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004571 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004572 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4573 }
Andy Hung08fb1742015-05-31 23:22:10 -07004574 }
4575 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004576 }
Eric Laurent81784c32012-11-19 14:55:58 -08004577
Eric Laurentbfb1b832013-01-07 09:53:42 -08004578 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004579 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004580 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004581 // suspended requires accurate metering of sleep time.
4582 if (isSuspended()) {
4583 // advance by expected sleepTime
4584 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4585 const nsecs_t nowNs = systemTime();
4586
4587 // compute expected next time vs current time.
4588 // (negative deltas are treated as delays).
4589 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4590 if (deltaNs < -kMaxNextBufferDelayNs) {
4591 // Delays longer than the max allowed trigger a reset.
4592 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4593 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4594 timeLoopNextNs = nowNs + deltaNs;
4595 } else if (deltaNs < 0) {
4596 // Delays within the max delay allowed: zero the delta/sleepTime
4597 // to help the system catch up in the next iteration(s)
4598 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4599 deltaNs = 0;
4600 }
4601 // update sleep time (which is >= 0)
4602 mSleepTimeUs = deltaNs / 1000;
4603 }
Eric Laurente93cc032016-05-05 10:15:10 -07004604 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004605 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004606 }
Glenn Kastene7754022014-10-31 12:11:26 -07004607 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004608 }
Eric Laurent81784c32012-11-19 14:55:58 -08004609 }
4610
4611 // Finally let go of removed track(s), without the lock held
4612 // since we can't guarantee the destructors won't acquire that
4613 // same lock. This will also mutate and push a new fast mixer state.
4614 threadLoop_removeTracks(tracksToRemove);
4615 tracksToRemove.clear();
4616
4617 // FIXME I don't understand the need for this here;
4618 // it was in the original code but maybe the
4619 // assignment in saveOutputTracks() makes this unnecessary?
4620 clearOutputTracks();
4621
4622 // Effect chains will be actually deleted here if they were removed from
4623 // mEffectChains list during mixing or effects processing
4624 effectChains.clear();
4625
4626 // FIXME Note that the above .clear() is no longer necessary since effectChains
4627 // is now local to this block, but will keep it for now (at least until merge done).
4628 }
4629
Eric Laurentbfb1b832013-01-07 09:53:42 -08004630 threadLoop_exit();
4631
Eric Laurentcf817a22014-08-04 20:36:31 -07004632 if (!mStandby) {
4633 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004634 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004635 }
4636
4637 releaseWakeLock();
4638
4639 ALOGV("Thread %p type %d exiting", this, mType);
4640 return false;
4641}
4642
Andy Hungee58e4a2023-07-07 13:47:37 -07004643void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004644{
Dean Wheatley12473e92021-03-18 23:00:55 +11004645 if (mStandby) {
4646 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4647 return;
4648 } else if (mHwPaused) {
4649 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4650 return;
4651 }
4652
4653 // Gather the framesReleased counters for all active tracks,
4654 // and associate with the sink frames written out. We need
4655 // this to convert the sink timestamp to the track timestamp.
4656 bool kernelLocationUpdate = false;
4657 ExtendedTimestamp timestamp; // use private copy to fetch
4658
4659 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4660 // HAL may be draining some small duration buffered data for fade out.
4661 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4662 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4663 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4664 mSampleRate);
4665
Andy Hungab65b182023-09-06 19:41:47 -07004666 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004667 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4668 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4669 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4670 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4671 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4672 = correctedTimestamp.mFrames;
4673 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4674 = correctedTimestamp.mTimeNs;
4675 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4676 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4677 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4678
4679 // Note: Downstream latency only added if timestamp correction enabled.
4680 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4681 const int64_t newPosition =
4682 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4683 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4684 // prevent retrograde
4685 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4686 newPosition,
4687 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4688 - mSuspendedFrames));
4689 }
4690 }
4691
4692 // We always fetch the timestamp here because often the downstream
4693 // sink will block while writing.
4694
4695 // We keep track of the last valid kernel position in case we are in underrun
4696 // and the normal mixer period is the same as the fast mixer period, or there
4697 // is some error from the HAL.
4698 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4699 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4700 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4701 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4702 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4703
4704 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4705 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4706 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4707 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4708 }
4709
4710 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4711 kernelLocationUpdate = true;
4712 } else {
4713 ALOGVV("getTimestamp error - no valid kernel position");
4714 }
4715
4716 // copy over kernel info
4717 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4718 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4719 + mSuspendedFrames; // add frames discarded when suspended
4720 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4721 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4722 } else {
4723 mTimestampVerifier.error();
4724 }
4725
4726 // mFramesWritten for non-offloaded tracks are contiguous
4727 // even after standby() is called. This is useful for the track frame
4728 // to sink frame mapping.
4729 bool serverLocationUpdate = false;
4730 if (mFramesWritten != mLastFramesWritten) {
4731 serverLocationUpdate = true;
4732 mLastFramesWritten = mFramesWritten;
4733 }
4734 // Only update timestamps if there is a meaningful change.
4735 // Either the kernel timestamp must be valid or we have written something.
4736 if (kernelLocationUpdate || serverLocationUpdate) {
4737 if (serverLocationUpdate) {
4738 // use the time before we called the HAL write - it is a bit more accurate
4739 // to when the server last read data than the current time here.
4740 //
4741 // If we haven't written anything, mLastIoBeginNs will be -1
4742 // and we use systemTime().
4743 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4744 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004745 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004746 }
4747
Andy Hung8d31fd22023-06-26 19:20:57 -07004748 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004749 if (!t->isFastTrack()) {
4750 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004751 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004752 mFramesWritten,
4753 mSampleRate,
4754 mTimestamp);
4755 }
4756 }
4757 }
4758
4759 if (audio_has_proportional_frames(mFormat)) {
4760 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4761 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4762 mLatencyMs.add(latencyMs);
4763 }
4764 }
4765#if 0
4766 // logFormat example
4767 if (z % 100 == 0) {
4768 timespec ts;
4769 clock_gettime(CLOCK_MONOTONIC, &ts);
4770 LOGT("This is an integer %d, this is a float %f, this is my "
4771 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4772 LOGT("A deceptive null-terminated string %\0");
4773 }
4774 ++z;
4775#endif
4776}
4777
Andy Hungc5007f82023-08-29 14:26:09 -07004778// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004779void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004780NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004781{
Andy Hung6c498e92023-12-05 17:28:17 -08004782 if (tracksToRemove.empty()) return;
4783
4784 // Block all incoming TrackHandle requests until we are finished with the release.
4785 setThreadBusy_l(true);
4786
Andy Hungfe726a62018-09-27 15:17:25 -07004787 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004788 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004789 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004790 if (chain != 0) {
4791 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4792 __func__, track->id(), chain.get(), track->sessionId());
4793 chain->decActiveTrackCnt();
4794 }
Andy Hung6c498e92023-12-05 17:28:17 -08004795
Andy Hungfe726a62018-09-27 15:17:25 -07004796 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004797 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004798 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004799 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004800 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004801 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004802 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004803 }
Andy Hung6c498e92023-12-05 17:28:17 -08004804 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004805 }
jiabineb3bda02020-06-30 14:07:03 -07004806 if (mHapticChannelCount > 0 &&
4807 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004808 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004809 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004810 // Unlock due to VibratorService will lock for this call and will
4811 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004812 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004813 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004814
4815 // When the track is stop, set the haptic intensity as MUTE
4816 // for the HapticGenerator effect.
4817 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004818 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004819 }
jiabin245cdd92018-12-07 17:55:15 -08004820 }
Andy Hung6c498e92023-12-05 17:28:17 -08004821
4822 // Under lock, the track is removed from the active tracks list.
4823 //
4824 // Once the track is no longer active, the TrackHandle may directly
4825 // modify it as the threadLoop() is no longer responsible for its maintenance.
4826 // Do not modify the track from threadLoop after the mutex is unlocked
4827 // if it is not active.
4828 mActiveTracks.remove(track);
4829
4830 if (track->isTerminated()) {
4831 // remove from our tracks vector
4832 removeTrack_l(track);
4833 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004834 }
Andy Hung6c498e92023-12-05 17:28:17 -08004835
4836 // Allow incoming TrackHandle requests. We still hold the mutex,
4837 // so pending TrackHandle requests will occur after we unlock it.
4838 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004839}
Eric Laurent81784c32012-11-19 14:55:58 -08004840
Andy Hungee58e4a2023-07-07 13:47:37 -07004841status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004842{
4843 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004844 ExtendedTimestamp ets;
4845 status_t status = mNormalSink->getTimestamp(ets);
4846 if (status == NO_ERROR) {
4847 status = ets.getBestTimestamp(&timestamp);
4848 }
4849 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004850 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004851 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004852 collectTimestamps_l();
4853 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4854 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004855 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004856 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4857 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4858 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4859 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4860 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004861 }
4862 return INVALID_OPERATION;
4863}
Eric Laurent1c333e22014-05-20 10:48:17 -07004864
Eric Laurenteab90452019-06-24 15:17:46 -07004865// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4866// still applied by the mixer.
4867// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4868// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4869// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004870status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004871{
4872 status_t result = NO_ERROR;
4873 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4874 if (*volume != mLeftVolFloat) {
4875 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004876 // HAL can return INVALID_OPERATION if operation is not supported.
4877 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004878 "Error when setting output stream volume: %d", result);
4879 if (result == NO_ERROR) {
4880 mLeftVolFloat = *volume;
4881 }
4882 }
4883 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4884 // remove stream volume contribution from software volume.
4885 if (mLeftVolFloat == *volume) {
4886 *volume = 1.0f;
4887 }
4888 }
4889 return result;
4890}
4891
Andy Hungee58e4a2023-07-07 13:47:37 -07004892status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004893 audio_patch_handle_t *handle)
4894{
Andy Hungf60abce2016-08-26 11:37:54 -07004895 status_t status;
4896 if (property_get_bool("af.patch_park", false /* default_value */)) {
4897 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4898 // or if HAL does not properly lock against access.
4899 AutoPark<FastMixer> park(mFastMixer);
4900 status = PlaybackThread::createAudioPatch_l(patch, handle);
4901 } else {
4902 status = PlaybackThread::createAudioPatch_l(patch, handle);
4903 }
Eric Laurentb0463942022-12-20 16:31:10 +01004904
4905 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004906 return status;
4907}
4908
Andy Hungee58e4a2023-07-07 13:47:37 -07004909status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004910 audio_patch_handle_t *handle)
4911{
4912 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004913
4914 // store new device and send to effects
4915 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004916 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004917 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004918 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4919 && !mOutput->audioHwDev->supportsAudioPatches(),
4920 "Enumerated device type(%#x) must not be used "
4921 "as it does not support audio patches",
4922 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004923 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004924 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4925 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004926 }
4927
François Gaffie0c280aa2018-07-25 10:02:15 +02004928 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004929#ifdef ADD_BATTERY_DATA
4930 // when changing the audio output device, call addBatteryData to notify
4931 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004932 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004933 uint32_t params = 0;
4934 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004935 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004936 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004937 }
4938
Eric Laurent054d9d32015-04-24 08:48:48 -07004939 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004940 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004941 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4942 }
4943
4944 if (params != 0) {
4945 addBatteryData(params);
4946 }
4947 }
4948#endif
4949
4950 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004951 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004952 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004953
jiabinc52b1ff2019-10-31 17:20:42 -07004954 // mPatch.num_sinks is not set when the thread is created so that
4955 // the first patch creation triggers an ioConfigChanged callback
4956 bool configChanged = (mPatch.num_sinks == 0) ||
4957 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004958 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004959 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004960 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004961
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004962 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004963 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4964 status = hwDevice->createAudioPatch(patch->num_sources,
4965 patch->sources,
4966 patch->num_sinks,
4967 patch->sinks,
4968 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004969 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004970 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004971 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004972 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004973 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004974
4975 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004976 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004977 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004978 // also dispatch to active AudioTracks for MediaMetrics
4979 for (const auto &track : mActiveTracks) {
4980 track->logEndInterval();
4981 track->logBeginInterval(patchSinksAsString);
4982 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004983
Eric Laurente8726fe2015-06-26 09:39:24 -07004984 if (configChanged) {
4985 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4986 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004987 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004988 mActiveTracks.setHasChanged();
4989
Eric Laurent1c333e22014-05-20 10:48:17 -07004990 return status;
4991}
4992
Andy Hungee58e4a2023-07-07 13:47:37 -07004993status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004994{
Andy Hungf60abce2016-08-26 11:37:54 -07004995 status_t status;
4996 if (property_get_bool("af.patch_park", false /* default_value */)) {
4997 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4998 // or if HAL does not properly lock against access.
4999 AutoPark<FastMixer> park(mFastMixer);
5000 status = PlaybackThread::releaseAudioPatch_l(handle);
5001 } else {
5002 status = PlaybackThread::releaseAudioPatch_l(handle);
5003 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005004 return status;
5005}
5006
Andy Hungee58e4a2023-07-07 13:47:37 -07005007status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005008{
5009 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005010
jiabinc52b1ff2019-10-31 17:20:42 -07005011 mPatch = audio_patch{};
5012 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005013
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005014 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005015 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5016 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005017 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005018 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005019 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005020 // Force meteadata update after a route change
5021 mActiveTracks.setHasChanged();
5022
Eric Laurent1c333e22014-05-20 10:48:17 -07005023 return status;
5024}
5025
Andy Hungee58e4a2023-07-07 13:47:37 -07005026void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005027{
Andy Hung972bec12023-08-31 16:13:39 -07005028 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005029 mTracks.add(track);
5030}
5031
Andy Hungee58e4a2023-07-07 13:47:37 -07005032void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005033{
Andy Hung972bec12023-08-31 16:13:39 -07005034 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005035 destroyTrack_l(track);
5036}
5037
Andy Hungee58e4a2023-07-07 13:47:37 -07005038void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005039{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005040 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005041 config->role = AUDIO_PORT_ROLE_SOURCE;
5042 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5043 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005044 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5045 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5046 config->flags.output = mOutput->flags;
5047 }
Eric Laurent83b88082014-06-20 18:31:16 -07005048}
5049
Eric Laurent81784c32012-11-19 14:55:58 -08005050// ----------------------------------------------------------------------------
5051
Andy Hungee58e4a2023-07-07 13:47:37 -07005052/* static */
5053sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005054 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005055 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005056 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005057}
5058
Andy Hung583043b2023-07-17 17:05:00 -07005059MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005060 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005061 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005062 // mAudioMixer below
5063 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005064 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005065 mFastMixerFutex(0),
5066 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005067 // mOutputSink below
5068 // mPipeSink below
5069 // mNormalSink below
5070{
Andy Hung583043b2023-07-17 17:05:00 -07005071 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005072 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005073 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005074 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005075 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5076 mNormalFrameCount);
5077 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5078
Andy Hungfbfc3952015-01-15 13:33:51 -08005079 if (type == DUPLICATING) {
5080 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5081 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5082 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5083 return;
5084 }
Eric Laurent81784c32012-11-19 14:55:58 -08005085 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005086 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005087 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005088 const NBAIO_Format offers[1] = {Format_from_SR_C(
5089 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005090#if !LOG_NDEBUG
5091 ssize_t index =
5092#else
5093 (void)
5094#endif
5095 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005096 ALOG_ASSERT(index == 0);
5097
5098 // initialize fast mixer depending on configuration
5099 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005100 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005101 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005102 } else {
5103 switch (kUseFastMixer) {
5104 case FastMixer_Never:
5105 initFastMixer = false;
5106 break;
5107 case FastMixer_Always:
5108 initFastMixer = true;
5109 break;
5110 case FastMixer_Static:
5111 case FastMixer_Dynamic:
5112 initFastMixer = mFrameCount < mNormalFrameCount;
5113 break;
5114 }
5115 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5116 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5117 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005118 }
5119 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005120 audio_format_t fastMixerFormat;
5121 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5122 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5123 } else {
5124 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5125 }
5126 if (mFormat != fastMixerFormat) {
5127 // change our Sink format to accept our intermediate precision
5128 mFormat = fastMixerFormat;
5129 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005130 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005131 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5132 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5133 }
Eric Laurent81784c32012-11-19 14:55:58 -08005134
5135 // create a MonoPipe to connect our submix to FastMixer
5136 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005137
Andy Hung1258c1a2014-05-23 21:22:17 -07005138 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005139 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005140 format.mFormat = fastMixerFormat;
5141 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5142
Eric Laurent81784c32012-11-19 14:55:58 -08005143 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5144 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5145 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5146 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005147 const NBAIO_Format offersFast[1] = {format};
5148 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005149#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005150 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005151#else
5152 (void)
5153#endif
Andy Hung920f6572022-10-06 12:09:49 -07005154 monoPipe->negotiate(offersFast, std::size(offersFast),
5155 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005156 ALOG_ASSERT(index == 0);
5157 monoPipe->setAvgFrames((mScreenState & 1) ?
5158 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5159 mPipeSink = monoPipe;
5160
Eric Laurent81784c32012-11-19 14:55:58 -08005161 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005162 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005163 FastMixerStateQueue *sq = mFastMixer->sq();
5164#ifdef STATE_QUEUE_DUMP
5165 sq->setObserverDump(&mStateQueueObserverDump);
5166 sq->setMutatorDump(&mStateQueueMutatorDump);
5167#endif
5168 FastMixerState *state = sq->begin();
5169 FastTrack *fastTrack = &state->mFastTracks[0];
5170 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5171 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5172 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005173 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5174 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5175 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005176 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005177 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005178 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005179 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005180 fastTrack->mGeneration++;
5181 state->mFastTracksGen++;
5182 state->mTrackMask = 1;
5183 // fast mixer will use the HAL output sink
5184 state->mOutputSink = mOutputSink.get();
5185 state->mOutputSinkGen++;
5186 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005187 // specify sink channel mask when haptic channel mask present as it can not
5188 // be calculated directly from channel count
5189 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005190 ? AUDIO_CHANNEL_NONE
5191 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005192 state->mCommand = FastMixerState::COLD_IDLE;
5193 // already done in constructor initialization list
5194 //mFastMixerFutex = 0;
5195 state->mColdFutexAddr = &mFastMixerFutex;
5196 state->mColdGen++;
5197 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005198 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005199 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005200 sq->end();
5201 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5202
Eric Tan0513b5d2018-09-17 10:32:48 -07005203 NBLog::thread_info_t info;
5204 info.id = mId;
5205 info.type = NBLog::FASTMIXER;
5206 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5207
Eric Laurent81784c32012-11-19 14:55:58 -08005208 // start the fast mixer
5209 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5210 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005211 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005212 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005213
5214#ifdef AUDIO_WATCHDOG
5215 // create and start the watchdog
5216 mAudioWatchdog = new AudioWatchdog();
5217 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5218 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5219 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005220 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005221#endif
Andy Hung8946a282018-04-19 20:04:56 -07005222 } else {
5223#ifdef TEE_SINK
5224 // Only use the MixerThread tee if there is no FastMixer.
5225 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5226 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5227#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005228 }
5229
5230 switch (kUseFastMixer) {
5231 case FastMixer_Never:
5232 case FastMixer_Dynamic:
5233 mNormalSink = mOutputSink;
5234 break;
5235 case FastMixer_Always:
5236 mNormalSink = mPipeSink;
5237 break;
5238 case FastMixer_Static:
5239 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5240 break;
5241 }
5242}
5243
Andy Hungee58e4a2023-07-07 13:47:37 -07005244MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005245{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005246 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005247 FastMixerStateQueue *sq = mFastMixer->sq();
5248 FastMixerState *state = sq->begin();
5249 if (state->mCommand == FastMixerState::COLD_IDLE) {
5250 int32_t old = android_atomic_inc(&mFastMixerFutex);
5251 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005252 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005253 }
5254 }
5255 state->mCommand = FastMixerState::EXIT;
5256 sq->end();
5257 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5258 mFastMixer->join();
5259 // Though the fast mixer thread has exited, it's state queue is still valid.
5260 // We'll use that extract the final state which contains one remaining fast track
5261 // corresponding to our sub-mix.
5262 state = sq->begin();
5263 ALOG_ASSERT(state->mTrackMask == 1);
5264 FastTrack *fastTrack = &state->mFastTracks[0];
5265 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5266 delete fastTrack->mBufferProvider;
5267 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005268 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005269#ifdef AUDIO_WATCHDOG
5270 if (mAudioWatchdog != 0) {
5271 mAudioWatchdog->requestExit();
5272 mAudioWatchdog->requestExitAndWait();
5273 mAudioWatchdog.clear();
5274 }
5275#endif
5276 }
Andy Hung583043b2023-07-17 17:05:00 -07005277 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005278 delete mAudioMixer;
5279}
5280
Andy Hungee58e4a2023-07-07 13:47:37 -07005281void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005282 PlaybackThread::onFirstRef();
5283
Andy Hung972bec12023-08-31 16:13:39 -07005284 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005285 if (mOutput != nullptr && mOutput->stream != nullptr) {
5286 status_t status = mOutput->stream->setLatencyModeCallback(this);
5287 if (status != INVALID_OPERATION) {
5288 updateHalSupportedLatencyModes_l();
5289 }
5290 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5291 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5292 mBluetoothLatencyModesEnabled.store(
5293 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5294 }
5295}
Eric Laurent81784c32012-11-19 14:55:58 -08005296
Andy Hungee58e4a2023-07-07 13:47:37 -07005297uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005298{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005299 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005300 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5301 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5302 }
5303 return latency;
5304}
5305
Andy Hungee58e4a2023-07-07 13:47:37 -07005306ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005307{
5308 // FIXME we should only do one push per cycle; confirm this is true
5309 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005310 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005311 FastMixerStateQueue *sq = mFastMixer->sq();
5312 FastMixerState *state = sq->begin();
5313 if (state->mCommand != FastMixerState::MIX_WRITE &&
5314 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5315 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005316
5317 // FIXME workaround for first HAL write being CPU bound on some devices
5318 ATRACE_BEGIN("write");
5319 mOutput->write((char *)mSinkBuffer, 0);
5320 ATRACE_END();
5321
Eric Laurent81784c32012-11-19 14:55:58 -08005322 int32_t old = android_atomic_inc(&mFastMixerFutex);
5323 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005324 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005325 }
5326#ifdef AUDIO_WATCHDOG
5327 if (mAudioWatchdog != 0) {
5328 mAudioWatchdog->resume();
5329 }
5330#endif
5331 }
5332 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005333#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005334 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005335 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005336#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005337 sq->end();
5338 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5339 if (kUseFastMixer == FastMixer_Dynamic) {
5340 mNormalSink = mPipeSink;
5341 }
5342 } else {
5343 sq->end(false /*didModify*/);
5344 }
5345 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005347}
5348
Andy Hungee58e4a2023-07-07 13:47:37 -07005349void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005350{
5351 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005352 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005353 FastMixerStateQueue *sq = mFastMixer->sq();
5354 FastMixerState *state = sq->begin();
5355 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005356 // Report any frames trapped in the Monopipe
5357 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5358 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5359 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5360 "monoPipeWritten:%lld monoPipeLeft:%lld",
5361 (long long)mFramesWritten, (long long)mSuspendedFrames,
5362 (long long)mPipeSink->framesWritten(), pipeFrames);
5363 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5364
Eric Laurent81784c32012-11-19 14:55:58 -08005365 state->mCommand = FastMixerState::COLD_IDLE;
5366 state->mColdFutexAddr = &mFastMixerFutex;
5367 state->mColdGen++;
5368 mFastMixerFutex = 0;
5369 sq->end();
5370 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5371 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5372 if (kUseFastMixer == FastMixer_Dynamic) {
5373 mNormalSink = mOutputSink;
5374 }
5375#ifdef AUDIO_WATCHDOG
5376 if (mAudioWatchdog != 0) {
5377 mAudioWatchdog->pause();
5378 }
5379#endif
5380 } else {
5381 sq->end(false /*didModify*/);
5382 }
5383 }
5384 PlaybackThread::threadLoop_standby();
5385}
5386
Andy Hungee58e4a2023-07-07 13:47:37 -07005387bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388{
5389 return false;
5390}
5391
Andy Hungee58e4a2023-07-07 13:47:37 -07005392bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005393{
5394 return !mStandby;
5395}
5396
Andy Hungee58e4a2023-07-07 13:47:37 -07005397bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398{
Andy Hung972bec12023-08-31 16:13:39 -07005399 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005400 return waitingAsyncCallback_l();
5401}
5402
Eric Laurent81784c32012-11-19 14:55:58 -08005403// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005404void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005405{
Andy Hung8d672e02023-09-15 18:19:28 -07005406 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5407 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005408 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005409 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005410 // discard any pending drain or write ack by incrementing sequence
5411 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5412 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005414 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5415 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005417 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005418 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005419}
5420
Andy Hungee58e4a2023-07-07 13:47:37 -07005421void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005422{
5423 ALOGV("signal playback thread");
5424 broadcast_l();
5425}
5426
Andy Hungee58e4a2023-07-07 13:47:37 -07005427void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005428{
5429 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5430 invalidateTracks((audio_stream_type_t)i);
5431 }
5432}
5433
Andy Hungee58e4a2023-07-07 13:47:37 -07005434void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005435{
Eric Laurent81784c32012-11-19 14:55:58 -08005436 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005437 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005438 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005439 // increase sleep time progressively when application underrun condition clears.
5440 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5441 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5442 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005443 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005444 sleepTimeShift--;
5445 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005446 mSleepTimeUs = 0;
5447 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005448 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005449
Eric Laurent81784c32012-11-19 14:55:58 -08005450}
5451
Andy Hungee58e4a2023-07-07 13:47:37 -07005452void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005453{
5454 // If no tracks are ready, sleep once for the duration of an output
5455 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005456 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005457 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005458 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5459 // Using the Monopipe availableToWrite, we estimate the
5460 // sleep time to retry for more data (before we underrun).
5461 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5462 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5463 const size_t pipeFrames = monoPipe->maxFrames();
5464 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5465 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5466 const size_t framesDelay = std::min(
5467 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5468 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5469 pipeFrames, framesLeft, framesDelay);
5470 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5471 } else {
5472 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5473 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5474 mSleepTimeUs = kMinThreadSleepTimeUs;
5475 }
5476 // reduce sleep time in case of consecutive application underruns to avoid
5477 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5478 // duration we would end up writing less data than needed by the audio HAL if
5479 // the condition persists.
5480 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5481 sleepTimeShift++;
5482 }
Eric Laurent81784c32012-11-19 14:55:58 -08005483 }
5484 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005485 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005486 }
5487 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005488 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5489 // before effects processing or output.
5490 if (mMixerBufferValid) {
5491 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005492 if (mType == SPATIALIZER) {
5493 memset(mSinkBuffer, 0, mSinkBufferSize);
5494 }
Andy Hung98ef9782014-03-04 14:46:50 -08005495 } else {
5496 memset(mSinkBuffer, 0, mSinkBufferSize);
5497 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005498 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005499 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5500 "anticipated start");
5501 }
5502 // TODO add standby time extension fct of effect tail
5503}
5504
Andy Hungc5007f82023-08-29 14:26:09 -07005505// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005506PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005507 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005508{
Andy Hungc0691382018-09-12 18:01:57 -07005509 // clean up deleted track ids in AudioMixer before allocating new tracks
5510 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5511 // for each trackId, destroy it in the AudioMixer
5512 if (mAudioMixer->exists(trackId)) {
5513 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005514 }
5515 });
Andy Hungc0691382018-09-12 18:01:57 -07005516 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005517
5518 mixer_state mixerStatus = MIXER_IDLE;
5519 // find out which tracks need to be processed
5520 size_t count = mActiveTracks.size();
5521 size_t mixedTracks = 0;
5522 size_t tracksWithEffect = 0;
5523 // counts only _active_ fast tracks
5524 size_t fastTracks = 0;
5525 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5526
5527 float masterVolume = mMasterVolume;
5528 bool masterMute = mMasterMute;
5529
5530 if (masterMute) {
5531 masterVolume = 0;
5532 }
5533 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005534 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005535 if (chain != 0) {
5536 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005537 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005538 masterVolume = (float)((v + (1 << 23)) >> 24);
5539 chain.clear();
5540 }
5541
5542 // prepare a new state to push
5543 FastMixerStateQueue *sq = NULL;
5544 FastMixerState *state = NULL;
5545 bool didModify = false;
5546 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005547 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005548 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005549 sq = mFastMixer->sq();
5550 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005551 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005552 }
5553
Andy Hung69aed5f2014-02-25 17:24:40 -08005554 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005555 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005556
Andy Hungbd3b2b02018-05-21 10:53:11 -07005557 // DeferredOperations handles statistics after setting mixerStatus.
5558 class DeferredOperations {
5559 public:
Andy Hungea840382020-05-05 21:50:17 -07005560 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5561 : mMixerStatus(mixerStatus)
5562 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005563
5564 // when leaving scope, tally frames properly.
5565 ~DeferredOperations() {
5566 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5567 // because that is when the underrun occurs.
5568 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005569 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005570 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005571 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005572 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005573 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005574 }
5575 }
Andy Hungea840382020-05-05 21:50:17 -07005576 // send the max underrun frames for this mixer period
5577 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005578 }
5579
5580 // tallyUnderrunFrames() is called to update the track counters
5581 // with the number of underrun frames for a particular mixer period.
5582 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005583 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005584 mUnderrunFrames.emplace_back(track, underrunFrames);
5585 }
5586
5587 private:
5588 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005589 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005590 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005591 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005592 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005593
jiabin245cdd92018-12-07 17:55:15 -08005594 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005595 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005596 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005597
5598 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005599 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005600
5601 // process fast tracks
5602 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005603 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5604 "%s(%d): FastTrack(%d) present without FastMixer",
5605 __func__, id(), track->id());
5606
jiabin245cdd92018-12-07 17:55:15 -08005607 if (track->getHapticPlaybackEnabled()) {
5608 noFastHapticTrack = false;
5609 }
Eric Laurent81784c32012-11-19 14:55:58 -08005610
5611 // It's theoretically possible (though unlikely) for a fast track to be created
5612 // and then removed within the same normal mix cycle. This is not a problem, as
5613 // the track never becomes active so it's fast mixer slot is never touched.
5614 // The converse, of removing an (active) track and then creating a new track
5615 // at the identical fast mixer slot within the same normal mix cycle,
5616 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005617 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005618 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005619 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5620 FastTrack *fastTrack = &state->mFastTracks[j];
5621
5622 // Determine whether the track is currently in underrun condition,
5623 // and whether it had a recent underrun.
5624 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5625 FastTrackUnderruns underruns = ftDump->mUnderruns;
5626 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005627 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005628 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005629 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005630 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005631 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005632 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005633 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005634 // don't count underruns that occur while stopping or pausing
5635 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005636 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005637 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5638 recentUnderruns > 0) {
5639 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005640 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005641 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005642 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005643 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005644
5645 // This is similar to the state machine for normal tracks,
5646 // with a few modifications for fast tracks.
5647 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005648 switch (track->state()) {
5649 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005650 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005651 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005652 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005653 }
5654 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005655 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005656 // ramp down is not yet implemented
5657 track->setPaused();
5658 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005659 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005660 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005661 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005662 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005663 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005664 if (recentFull > 0 || recentPartial > 0) {
5665 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005666 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005667 }
5668 if (recentUnderruns == 0) {
5669 // no recent underruns: stay active
5670 break;
5671 }
5672 // there has recently been an underrun of some kind
5673 if (track->sharedBuffer() == 0) {
5674 // were any of the recent underruns "empty" (no frames available)?
5675 if (recentEmpty == 0) {
5676 // no, then ignore the partial underruns as they are allowed indefinitely
5677 break;
5678 }
5679 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005680 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005681 break;
5682 }
5683 // indicate to client process that the track was disabled because of underrun;
5684 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005685 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005686 // remove from active list, but state remains ACTIVE [confusing but true]
5687 isActive = false;
5688 break;
5689 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005690 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005691 case IAfTrackBase::STOPPING_2:
5692 case IAfTrackBase::PAUSED:
5693 case IAfTrackBase::STOPPED:
5694 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005695 // Check for presentation complete if track is inactive
5696 // We have consumed all the buffers of this track.
5697 // This would be incomplete if we auto-paused on underrun
5698 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005699 uint32_t latency = 0;
5700 status_t result = mOutput->stream->getLatency(&latency);
5701 ALOGE_IF(result != OK,
5702 "Error when retrieving output stream latency: %d", result);
5703 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005704 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005705 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5706 // track stays in active list until presentation is complete
5707 break;
5708 }
5709 }
5710 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005711 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005712 }
5713 if (track->isStopped()) {
5714 // Can't reset directly, as fast mixer is still polling this track
5715 // track->reset();
5716 // So instead mark this track as needing to be reset after push with ack
5717 resetMask |= 1 << i;
5718 }
5719 isActive = false;
5720 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005721 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005722 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005723 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005724 }
5725
5726 if (isActive) {
5727 // was it previously inactive?
5728 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005729 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5730 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005731 fastTrack->mBufferProvider = eabp;
5732 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005733 fastTrack->mChannelMask = track->channelMask();
5734 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005735 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005736 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005737 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005738 fastTrack->mGeneration++;
5739 state->mTrackMask |= 1 << j;
5740 didModify = true;
5741 // no acknowledgement required for newly active tracks
5742 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005743 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005744 float volume;
5745 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5746 volume = 0.f;
5747 } else {
5748 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5749 }
5750
5751 handleVoipVolume_l(&volume);
5752
Eric Laurent81784c32012-11-19 14:55:58 -08005753 // cache the combined master volume and stream type volume for fast mixer; this
5754 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005755 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005756 proxy->framesReleased()).first;
5757 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005758 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005759 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005760 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5761 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5762
Andy Hung583043b2023-07-17 17:05:00 -07005763 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005764 /*muteState=*/{masterVolume == 0.f,
5765 mStreamTypes[track->streamType()].volume == 0.f,
5766 mStreamTypes[track->streamType()].mute,
5767 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005768 vlf == 0.f && vrf == 0.f,
5769 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005770
5771 vlf *= volume;
5772 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005773
jiabin76d94692022-12-15 21:51:21 +00005774 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005775 ++fastTracks;
5776 } else {
5777 // was it previously active?
5778 if (state->mTrackMask & (1 << j)) {
5779 fastTrack->mBufferProvider = NULL;
5780 fastTrack->mGeneration++;
5781 state->mTrackMask &= ~(1 << j);
5782 didModify = true;
5783 // If any fast tracks were removed, we must wait for acknowledgement
5784 // because we're about to decrement the last sp<> on those tracks.
5785 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5786 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005787 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5788 // AudioTrack may start (which may not be with a start() but with a write()
5789 // after underrun) and immediately paused or released. In that case the
5790 // FastTrack state hasn't had time to update.
5791 // TODO Remove the ALOGW when this theory is confirmed.
5792 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005793 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005794 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005795 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005796 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
5798 tracksToRemove->add(track);
5799 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005800 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005801 }
jiabin245cdd92018-12-07 17:55:15 -08005802 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5803 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5804 didModify = true;
5805 }
Eric Laurent81784c32012-11-19 14:55:58 -08005806 continue;
5807 }
5808
5809 { // local variable scope to avoid goto warning
5810
5811 audio_track_cblk_t* cblk = track->cblk();
5812
5813 // The first time a track is added we wait
5814 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005815 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005816
5817 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005818 // use the trackId as the AudioMixer name.
5819 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005820 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005821 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005822 track->channelMask(),
5823 track->format(),
5824 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005825 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005826 ALOGW("%s(): AudioMixer cannot create track(%d)"
5827 " mask %#x, format %#x, sessionId %d",
5828 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005829 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005830 tracksToRemove->add(track);
5831 track->invalidate(); // consider it dead.
5832 continue;
5833 }
5834 }
5835
Eric Laurent81784c32012-11-19 14:55:58 -08005836 // make sure that we have enough frames to mix one full buffer.
5837 // enforce this condition only once to enable draining the buffer in case the client
5838 // app does not call stop() and relies on underrun to stop:
5839 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5840 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005841 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005842 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5843 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005844
5845 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005846 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005847 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5848 // add frames already consumed but not yet released by the resampler
5849 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005850 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005851
Eric Laurent81784c32012-11-19 14:55:58 -08005852 uint32_t minFrames = 1;
5853 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5854 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005855 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005856 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005857
5858 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005859 if (ATRACE_ENABLED()) {
5860 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005861 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005862 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005863 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005864 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005865 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005866 !track->isPaused() && !track->isTerminated())
5867 {
Andy Hungc0691382018-09-12 18:01:57 -07005868 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005869
5870 mixedTracks++;
5871
Shunkai Yaof4847652024-01-12 00:25:20 +00005872 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005873 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005874 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005875 if (track->mainBuffer() != mSinkBuffer &&
5876 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005877 if (mEffectBufferEnabled) {
5878 mEffectBufferValid = true; // Later can set directly.
5879 }
Eric Laurent81784c32012-11-19 14:55:58 -08005880 chain = getEffectChain_l(track->sessionId());
5881 // Delegate volume control to effect in track effect chain if needed
5882 if (chain != 0) {
5883 tracksWithEffect++;
5884 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005885 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005886 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005887 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005888 }
5889 }
5890
5891
5892 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005893 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005894 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005895 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5896 if (track->state() == IAfTrackBase::RESUMING) {
5897 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005898 // If a new track is paused immediately after start, do not ramp on resume.
5899 if (cblk->mServer != 0) {
5900 param = AudioMixer::RAMP_VOLUME;
5901 }
Eric Laurent81784c32012-11-19 14:55:58 -08005902 }
Andy Hungc0691382018-09-12 18:01:57 -07005903 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005904 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005905 // FIXME should not make a decision based on mServer
5906 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005907 // If the track is stopped before the first frame was mixed,
5908 // do not apply ramp
5909 param = AudioMixer::RAMP_VOLUME;
5910 }
5911
5912 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005913 uint32_t vl, vr; // in U8.24 integer format
5914 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005915 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005916 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005917 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005918 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005919 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005920 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005921
Eric Laurenteab90452019-06-24 15:17:46 -07005922 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5923 v = 0;
5924 }
5925
5926 handleVoipVolume_l(&v);
5927
5928 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005929 vl = vr = 0;
5930 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005931 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005932 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005933 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005934 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5935 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005936 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005937 if (vlf > GAIN_FLOAT_UNITY) {
5938 ALOGV("Track left volume out of range: %.3g", vlf);
5939 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005940 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005941 if (vrf > GAIN_FLOAT_UNITY) {
5942 ALOGV("Track right volume out of range: %.3g", vrf);
5943 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005944 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005945
Andy Hung583043b2023-07-17 17:05:00 -07005946 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005947 /*muteState=*/{masterVolume == 0.f,
5948 mStreamTypes[track->streamType()].volume == 0.f,
5949 mStreamTypes[track->streamType()].mute,
5950 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005951 vlf == 0.f && vrf == 0.f,
5952 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005953
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005954 // now apply the master volume and stream type volume and shaper volume
5955 vlf *= v * vh;
5956 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005957 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005958 // then derive vl and vr as U8.24 versions for the effect chain
5959 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5960 vl = (uint32_t) (scaleto8_24 * vlf);
5961 vr = (uint32_t) (scaleto8_24 * vrf);
5962 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005963 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005964 // send level comes from shared memory and so may be corrupt
5965 if (sendLevel > MAX_GAIN_INT) {
5966 ALOGV("Track send level out of range: %04X", sendLevel);
5967 sendLevel = MAX_GAIN_INT;
5968 }
Andy Hung6be49402014-05-30 10:42:03 -07005969 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5970 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005971 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005972
jiabin76d94692022-12-15 21:51:21 +00005973 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005974
Eric Laurent81784c32012-11-19 14:55:58 -08005975 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00005976 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005977 // Do not ramp volume if volume is controlled by effect
5978 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005979 // Update remaining floating point volume levels
5980 vlf = (float)vl / (1 << 24);
5981 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005982 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005983 } else {
5984 // force no volume ramp when volume controller was just disabled or removed
5985 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005986 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005987 param = AudioMixer::VOLUME;
5988 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005989 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005990 }
5991
Eric Laurent81784c32012-11-19 14:55:58 -08005992 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005993 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005994 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005995
Andy Hungc0691382018-09-12 18:01:57 -07005996 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5997 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5998 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005999 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006000 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006001 AudioMixer::TRACK,
6002 AudioMixer::FORMAT, (void *)track->format());
6003 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006004 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006005 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006006 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006007
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006008 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006009 mAudioMixer->setParameter(
6010 trackId,
6011 AudioMixer::TRACK,
6012 AudioMixer::MIXER_CHANNEL_MASK,
6013 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6014 } else {
6015 mAudioMixer->setParameter(
6016 trackId,
6017 AudioMixer::TRACK,
6018 AudioMixer::MIXER_CHANNEL_MASK,
6019 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6020 }
6021
Glenn Kastene3aa6592012-12-04 12:22:46 -08006022 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006023 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006024 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006025 if (reqSampleRate == 0) {
6026 reqSampleRate = mSampleRate;
6027 } else if (reqSampleRate > maxSampleRate) {
6028 reqSampleRate = maxSampleRate;
6029 }
Eric Laurent81784c32012-11-19 14:55:58 -08006030 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006031 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006032 AudioMixer::RESAMPLE,
6033 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006034 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006035
Andy Hung8edb8dc2015-03-26 19:13:55 -07006036 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006037 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006038 AudioMixer::TIMESTRETCH,
6039 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006040 // cast away constness for this generic API.
6041 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006042
Andy Hung69aed5f2014-02-25 17:24:40 -08006043 /*
6044 * Select the appropriate output buffer for the track.
6045 *
Andy Hung98ef9782014-03-04 14:46:50 -08006046 * Tracks with effects go into their own effects chain buffer
6047 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006048 *
6049 * Other tracks can use mMixerBuffer for higher precision
6050 * channel accumulation. If this buffer is enabled
6051 * (mMixerBufferEnabled true), then selected tracks will accumulate
6052 * into it.
6053 *
6054 */
6055 if (mMixerBufferEnabled
6056 && (track->mainBuffer() == mSinkBuffer
6057 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006058 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006059 mAudioMixer->setParameter(
6060 trackId,
6061 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006062 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006063 mAudioMixer->setParameter(
6064 trackId,
6065 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006066 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006067 } else {
6068 mAudioMixer->setParameter(
6069 trackId,
6070 AudioMixer::TRACK,
6071 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6072 mAudioMixer->setParameter(
6073 trackId,
6074 AudioMixer::TRACK,
6075 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6076 // TODO: override track->mainBuffer()?
6077 mMixerBufferValid = true;
6078 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006079 } else {
6080 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006081 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006082 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006083 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006084 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006085 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006086 AudioMixer::TRACK,
6087 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6088 }
Eric Laurent81784c32012-11-19 14:55:58 -08006089 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006090 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006091 AudioMixer::TRACK,
6092 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006093 mAudioMixer->setParameter(
6094 trackId,
6095 AudioMixer::TRACK,
6096 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006097 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006098 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006099 trackId,
6100 AudioMixer::TRACK,
6101 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006102 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006103 mAudioMixer->setParameter(
6104 trackId,
6105 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006106 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006107
6108 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006109 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006110
6111 // If one track is ready, set the mixer ready if:
6112 // - the mixer was not ready during previous round OR
6113 // - no other track is not ready
6114 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6115 mixerStatus != MIXER_TRACKS_ENABLED) {
6116 mixerStatus = MIXER_TRACKS_READY;
6117 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006118
6119 // Enable the next few lines to instrument a test for underrun log handling.
6120 // TODO: Remove when we have a better way of testing the underrun log.
6121#if 0
6122 static int i;
6123 if ((++i & 0xf) == 0) {
6124 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6125 }
6126#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006127 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006128 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006129 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006130 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6131 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006132 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006133 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006134 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006135
Eric Laurent81784c32012-11-19 14:55:58 -08006136 // clear effect chain input buffer if an active track underruns to avoid sending
6137 // previous audio buffer again to effects
6138 chain = getEffectChain_l(track->sessionId());
6139 if (chain != 0) {
6140 chain->clearInputBuffer();
6141 }
6142
Andy Hungc0691382018-09-12 18:01:57 -07006143 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006144 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6145 track->isStopped() || track->isPaused()) {
6146 // We have consumed all the buffers of this track.
6147 // Remove it from the list of active tracks.
6148 // TODO: use actual buffer filling status instead of latency when available from
6149 // audio HAL
6150 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006151 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006152 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6153 if (track->isStopped()) {
6154 track->reset();
6155 }
6156 tracksToRemove->add(track);
6157 }
6158 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006159 // No buffers for this track. Give it a few chances to
6160 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006161 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006162 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6163 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006164 tracksToRemove->add(track);
6165 // indicate to client process that the track was disabled because of underrun;
6166 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006167 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006168 // If one track is not ready, mark the mixer also not ready if:
6169 // - the mixer was ready during previous round OR
6170 // - no other track is ready
6171 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6172 mixerStatus != MIXER_TRACKS_READY) {
6173 mixerStatus = MIXER_TRACKS_ENABLED;
6174 }
6175 }
Andy Hungc0691382018-09-12 18:01:57 -07006176 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006177 }
6178
6179 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006180
6181 }
6182
jiabin245cdd92018-12-07 17:55:15 -08006183 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6184 // When there is no fast track playing haptic and FastMixer exists,
6185 // enabling the first FastTrack, which provides mixed data from normal
6186 // tracks, to play haptic data.
6187 FastTrack *fastTrack = &state->mFastTracks[0];
6188 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6189 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6190 didModify = true;
6191 }
6192 }
6193
Eric Laurent81784c32012-11-19 14:55:58 -08006194 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006195 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006196 if (didModify) {
6197 state->mFastTracksGen++;
6198 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6199 if (kUseFastMixer == FastMixer_Dynamic &&
6200 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6201 state->mCommand = FastMixerState::COLD_IDLE;
6202 state->mColdFutexAddr = &mFastMixerFutex;
6203 state->mColdGen++;
6204 mFastMixerFutex = 0;
6205 if (kUseFastMixer == FastMixer_Dynamic) {
6206 mNormalSink = mOutputSink;
6207 }
6208 // If we go into cold idle, need to wait for acknowledgement
6209 // so that fast mixer stops doing I/O.
6210 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6211 pauseAudioWatchdog = true;
6212 }
Eric Laurent81784c32012-11-19 14:55:58 -08006213 }
6214 if (sq != NULL) {
6215 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006216 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6217 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6218 // when bringing the output sink into standby.)
6219 //
6220 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6221 //
6222 // This occurs with BT suspend when we idle the FastMixer with
6223 // active tracks, which may be added or removed.
6224 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006225 }
6226#ifdef AUDIO_WATCHDOG
6227 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6228 mAudioWatchdog->pause();
6229 }
6230#endif
6231
6232 // Now perform the deferred reset on fast tracks that have stopped
6233 while (resetMask != 0) {
6234 size_t i = __builtin_ctz(resetMask);
6235 ALOG_ASSERT(i < count);
6236 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006237 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006238 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6239 track->reset();
6240 }
6241
Andy Hung80d03d22018-04-10 10:32:11 -07006242 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6243 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6244 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6245 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6246 // See also the implementation of destroyTrack_l().
6247 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006248 const int trackId = track->id();
6249 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6250 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006251 }
6252 }
6253
Eric Laurent81784c32012-11-19 14:55:58 -08006254 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006255 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006256
Eric Laurentb3f315a2021-07-13 15:09:05 +02006257 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6258 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006259 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006260 }
6261
6262 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006263 // as long as there are effects we should clear the effects buffer, to avoid
6264 // passing a non-clean buffer to the effect chain
6265 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006266 if (mType == SPATIALIZER) {
6267 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6268 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006269 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006270 // sink or mix buffer must be cleared if all tracks are connected to an
6271 // effect chain as in this case the mixer will not write to the sink or mix buffer
6272 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006273 // always clear sink buffer for spatializer output as the output of the spatializer
6274 // effect will be accumulated into it
6275 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6276 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006277 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006278 if (mMixerBufferValid) {
6279 memset(mMixerBuffer, 0, mMixerBufferSize);
6280 // TODO: In testing, mSinkBuffer below need not be cleared because
6281 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6282 // after mixing.
6283 //
6284 // To enforce this guarantee:
6285 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6286 // (mixedTracks == 0 && fastTracks > 0))
6287 // must imply MIXER_TRACKS_READY.
6288 // Later, we may clear buffers regardless, and skip much of this logic.
6289 }
Andy Hung98ef9782014-03-04 14:46:50 -08006290 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006291 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006292 }
6293
6294 // if any fast tracks, then status is ready
6295 mMixerStatusIgnoringFastTracks = mixerStatus;
6296 if (fastTracks > 0) {
6297 mixerStatus = MIXER_TRACKS_READY;
6298 }
6299 return mixerStatus;
6300}
6301
Andy Hungc5007f82023-08-29 14:26:09 -07006302// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006303uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006304{
6305 uint32_t trackCount = 0;
6306 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006307 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006308 trackCount++;
6309 }
6310 }
6311 return trackCount;
6312}
6313
Andy Hungee58e4a2023-07-07 13:47:37 -07006314bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006315{
Brian Lindahl65e90012022-07-27 18:01:07 +02006316 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6317 // could falsely detect that the frame position has stalled due to underrun because we haven't
6318 // given the Audio HAL enough time to update.
6319 const nsecs_t nowNs = systemTime();
6320 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6321 return mLatchedValue;
6322 }
6323 mPreviousNs = nowNs;
6324 mLatchedValue = false;
6325 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006326 uint64_t position = 0;
6327 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006328 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006329 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006330 if (position != mPreviousPosition) {
6331 mPreviousPosition = position;
6332 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006333 }
6334 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006335 return mLatchedValue;
6336}
6337
Andy Hungee58e4a2023-07-07 13:47:37 -07006338void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006339{
6340 mLatchedValue = true;
6341 mPreviousPosition = 0;
6342 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006343}
6344
Andy Hungc5007f82023-08-29 14:26:09 -07006345// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006346bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006347 audio_channel_mask_t channelMask, audio_format_t format,
6348 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006349{
Andy Hung1bc088a2018-02-09 15:57:31 -08006350 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6351 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006352 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006353 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006354 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006355 ALOGW("%s: invalid format: %#x", __func__, format);
6356 return false;
6357 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006358 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006359 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6360 return false;
6361 }
6362 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006363}
6364
Andy Hungc5007f82023-08-29 14:26:09 -07006365// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006366bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006367 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006368{
Eric Laurent81784c32012-11-19 14:55:58 -08006369 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006370 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006371
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006372 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006373
Eric Laurent10351942014-05-08 18:49:52 -07006374 AudioParameter param = AudioParameter(keyValuePair);
6375 int value;
6376 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6377 reconfig = true;
6378 }
6379 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006380 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006381 status = BAD_VALUE;
6382 } else {
6383 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006384 reconfig = true;
6385 }
Eric Laurent10351942014-05-08 18:49:52 -07006386 }
6387 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006388 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006389 status = BAD_VALUE;
6390 } else {
6391 // no need to save value, since it's constant
6392 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006393 }
Eric Laurent10351942014-05-08 18:49:52 -07006394 }
6395 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6396 // do not accept frame count changes if tracks are open as the track buffer
6397 // size depends on frame count and correct behavior would not be guaranteed
6398 // if frame count is changed after track creation
6399 if (!mTracks.isEmpty()) {
6400 status = INVALID_OPERATION;
6401 } else {
6402 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006403 }
Eric Laurent10351942014-05-08 18:49:52 -07006404 }
6405 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006406 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006407 }
Eric Laurent81784c32012-11-19 14:55:58 -08006408
Eric Laurent10351942014-05-08 18:49:52 -07006409 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006410 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006411 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006412 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6413 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006414 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006415 mThreadMetrics.logEndInterval();
6416 mThreadSnapshot.onEnd();
6417 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006418 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006419 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006420 }
Eric Laurent10351942014-05-08 18:49:52 -07006421 if (status == NO_ERROR && reconfig) {
6422 readOutputParameters_l();
6423 delete mAudioMixer;
6424 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006425 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006426 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006427 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006428 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006429 track->channelMask(),
6430 track->format(),
6431 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006432 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006433 "%s(): AudioMixer cannot create track(%d)"
6434 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006435 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006436 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006437 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006438 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006439 }
Eric Laurent81784c32012-11-19 14:55:58 -08006440 }
6441
Dean Wheatley68918102021-03-19 22:09:19 +11006442 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006443}
6444
6445
Andy Hungee58e4a2023-07-07 13:47:37 -07006446void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006447{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006448 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006449 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006450 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006451 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006452 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6453 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6454 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006455 if (hasFastMixer()) {
6456 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6457
6458 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6459 // while we are dumping it. It may be inconsistent, but it won't mutate!
6460 // This is a large object so we place it on the heap.
6461 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006462 const std::unique_ptr<FastMixerDumpState> copy =
6463 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006464 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006465
6466#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006467 // Similar for state queue
6468 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6469 observerCopy.dump(fd);
6470 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6471 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006472#endif
6473
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006474#ifdef AUDIO_WATCHDOG
6475 if (mAudioWatchdog != 0) {
6476 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6477 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6478 wdCopy.dump(fd);
6479 }
6480#endif
6481
6482 } else {
6483 dprintf(fd, " No FastMixer\n");
6484 }
Eric Laurent90cea102023-05-15 15:08:27 +02006485
6486 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6487 mBluetoothLatencyModesEnabled ? "" : "not ");
6488 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6489 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6490 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006491}
6492
Andy Hungee58e4a2023-07-07 13:47:37 -07006493uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006494{
6495 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6496}
6497
Andy Hungee58e4a2023-07-07 13:47:37 -07006498uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006499{
6500 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6501}
6502
Andy Hungee58e4a2023-07-07 13:47:37 -07006503void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006504{
6505 PlaybackThread::cacheParameters_l();
6506
6507 // FIXME: Relaxed timing because of a certain device that can't meet latency
6508 // Should be reduced to 2x after the vendor fixes the driver issue
6509 // increase threshold again due to low power audio mode. The way this warning
6510 // threshold is calculated and its usefulness should be reconsidered anyway.
6511 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6512}
6513
Andy Hungee58e4a2023-07-07 13:47:37 -07006514void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006515 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006516}
6517
Andy Hungee58e4a2023-07-07 13:47:37 -07006518void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006519 // Only handle latency mode if:
6520 // - mBluetoothLatencyModesEnabled is true
6521 // - the HAL supports latency modes
6522 // - the selected device is Bluetooth LE or A2DP
6523 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6524 return;
6525 }
6526 if (mOutDeviceTypeAddrs.size() != 1
6527 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6528 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6529 return;
6530 }
6531
6532 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6533 if (mSupportedLatencyModes.size() == 1) {
6534 // If the HAL only support one latency mode currently, confirm the choice
6535 latencyMode = mSupportedLatencyModes[0];
6536 } else if (mSupportedLatencyModes.size() > 1) {
6537 // Request low latency if:
6538 // - At least one active track is either:
6539 // - a fast track with gaming usage or
6540 // - a track with acessibility usage
6541 for (const auto& track : mActiveTracks) {
6542 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6543 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6544 latencyMode = AUDIO_LATENCY_MODE_LOW;
6545 break;
6546 }
6547 }
6548 }
6549
6550 if (latencyMode != mSetLatencyMode) {
6551 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6552 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6553 __func__, mId, toString(latencyMode).c_str(), status);
6554 if (status == NO_ERROR) {
6555 mSetLatencyMode = latencyMode;
6556 }
6557 }
6558}
6559
Andy Hungee58e4a2023-07-07 13:47:37 -07006560void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006561
6562 if (mOutput == nullptr || mOutput->stream == nullptr) {
6563 return;
6564 }
6565 std::vector<audio_latency_mode_t> latencyModes;
6566 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6567 if (status != NO_ERROR) {
6568 latencyModes.clear();
6569 }
6570 if (latencyModes != mSupportedLatencyModes) {
6571 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6572 __func__, mId, status, toString(latencyModes).c_str());
6573 mSupportedLatencyModes.swap(latencyModes);
6574 sendHalLatencyModesChangedEvent_l();
6575 }
6576}
6577
Andy Hungee58e4a2023-07-07 13:47:37 -07006578status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006579 std::vector<audio_latency_mode_t>* modes) {
6580 if (modes == nullptr) {
6581 return BAD_VALUE;
6582 }
Andy Hung972bec12023-08-31 16:13:39 -07006583 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006584 *modes = mSupportedLatencyModes;
6585 return NO_ERROR;
6586}
6587
Andy Hungee58e4a2023-07-07 13:47:37 -07006588void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006589 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006590 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006591 if (modes != mSupportedLatencyModes) {
6592 ALOGD("%s: thread(%d) supported latency modes: %s",
6593 __func__, mId, toString(modes).c_str());
6594 mSupportedLatencyModes.swap(modes);
6595 sendHalLatencyModesChangedEvent_l();
6596 }
6597}
6598
Andy Hungee58e4a2023-07-07 13:47:37 -07006599status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006600 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6601 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6602 return INVALID_OPERATION;
6603 }
6604 mBluetoothLatencyModesEnabled.store(enabled);
6605 return NO_ERROR;
6606}
6607
Eric Laurent81784c32012-11-19 14:55:58 -08006608// ----------------------------------------------------------------------------
6609
Andy Hungee58e4a2023-07-07 13:47:37 -07006610/* static */
6611sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006612 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006613 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6614 const audio_offload_info_t& offloadInfo) {
6615 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006616 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006617}
6618
Andy Hung583043b2023-07-17 17:05:00 -07006619DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006620 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6621 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006622 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006623 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006624{
Andy Hung583043b2023-07-17 17:05:00 -07006625 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006626}
6627
Andy Hungee58e4a2023-07-07 13:47:37 -07006628DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006629{
6630}
6631
Andy Hungee58e4a2023-07-07 13:47:37 -07006632void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006633{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006634 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006635 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6636 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6637}
6638
Andy Hungee58e4a2023-07-07 13:47:37 -07006639void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006640{
Andy Hung972bec12023-08-31 16:13:39 -07006641 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006642 if (mMasterBalance != balance) {
6643 mMasterBalance.store(balance);
6644 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6645 broadcast_l();
6646 }
6647}
6648
Andy Hungee58e4a2023-07-07 13:47:37 -07006649void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006650{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006651 float left, right;
6652
Andy Hung333ab962019-05-28 20:23:35 -07006653 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006654 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006655
Andy Hung398ffa22022-12-13 19:19:53 -08006656 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6657 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6658
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006659 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6660 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006661
6662 const int64_t volumeShaperFrames =
6663 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6664 const auto [shaperVolume, shaperActive] =
6665 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006666 mVolumeShaperActive = shaperActive;
6667
Vlad Popae2f5aef2022-07-25 16:00:20 +02006668 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6669 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6670 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6671
6672 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6673
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006674 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006675 left = right = 0;
6676 } else {
6677 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006678 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006679
Glenn Kastenc56f3422014-03-21 17:53:17 -07006680 if (left > GAIN_FLOAT_UNITY) {
6681 left = GAIN_FLOAT_UNITY;
6682 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006683 if (right > GAIN_FLOAT_UNITY) {
6684 right = GAIN_FLOAT_UNITY;
6685 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006686 left *= v;
6687 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006688 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006689 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6690 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6691 right *= mMasterBalanceRight;
6692 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006693 }
6694
Andy Hung583043b2023-07-17 17:05:00 -07006695 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006696 /*muteState=*/{mMasterMute,
6697 mStreamTypes[track->streamType()].volume == 0.f,
6698 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006699 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006700 clientVolumeMute,
6701 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006702
Eric Laurentbfb1b832013-01-07 09:53:42 -08006703 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006704 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006705 if (left != mLeftVolFloat || right != mRightVolFloat) {
6706 mLeftVolFloat = left;
6707 mRightVolFloat = right;
6708
Eric Laurentbfb1b832013-01-07 09:53:42 -08006709 // Delegate volume control to effect in track effect chain if needed
6710 // only one effect chain can be present on DirectOutputThread, so if
6711 // there is one, the track is connected to it
6712 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006713 // if effect chain exists, volume is handled by it.
6714 // Convert volumes from float to 8.24
6715 uint32_t vl = (uint32_t)(left * (1 << 24));
6716 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006717 // Direct/Offload effect chains set output volume in setVolume().
6718 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006719 } else {
6720 // otherwise we directly set the volume.
6721 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006723 }
6724 }
6725}
6726
Andy Hungee58e4a2023-07-07 13:47:37 -07006727void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006728{
Andy Hung8d31fd22023-06-26 19:20:57 -07006729 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6730 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006731
Eric Laurent0f0631e2015-07-06 18:01:25 -07006732 if (previousTrack != 0 && latestTrack != 0) {
6733 if (mType == DIRECT) {
6734 if (previousTrack.get() != latestTrack.get()) {
6735 mFlushPending = true;
6736 }
6737 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006738 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6739 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006740 mFlushPending = true;
6741 }
6742 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006743 } else if (previousTrack == 0) {
6744 // there could be an old track added back during track transition for direct
6745 // output, so always issues flush to flush data of the previous track if it
6746 // was already destroyed with HAL paused, then flush can resume the playback
6747 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006748 }
6749 PlaybackThread::onAddNewTrack_l();
6750}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006751
Andy Hungee58e4a2023-07-07 13:47:37 -07006752PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006753 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006754)
6755{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006756 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006757 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006758 bool doHwPause = false;
6759 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006760
6761 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006762 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006763 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006764 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006765 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006766 continue;
6767 }
6768
Andy Hung8d31fd22023-06-26 19:20:57 -07006769 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006770#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006771 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006772#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006773 // Only consider last track started for volume and mixer state control.
6774 // In theory an older track could underrun and restart after the new one starts
6775 // but as we only care about the transition phase between two tracks on a
6776 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006777 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006778 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006779
Kuowei Li23666472021-01-20 10:23:25 +08006780 if (track->isPausePending()) {
6781 track->pauseAck();
6782 // It is possible a track might have been flushed or stopped.
6783 // Other operations such as flush pending might occur on the next prepare.
6784 if (track->isPausing()) {
6785 track->setPaused();
6786 }
6787 // Always perform pause, as an immediate flush will change
6788 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006789 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006790 doHwPause = true;
6791 mHwPaused = true;
6792 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006793 } else if (track->isFlushPending()) {
6794 track->flushAck();
6795 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006796 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006797 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006798 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006799 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006800 if (last) {
6801 mLeftVolFloat = mRightVolFloat = -1.0;
6802 if (mHwPaused) {
6803 doHwResume = true;
6804 mHwPaused = false;
6805 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006806 }
6807 }
6808
Eric Laurent81784c32012-11-19 14:55:58 -08006809 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006810 // for all its buffers to be filled before processing it.
6811 // Allow draining the buffer in case the client
6812 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006813 // hence the test on (track->retryCount() > 1).
6814 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006815 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6816 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006817 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006818
6819 // target retry count that we will use is based on the time we wait for retries.
6820 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6821 // the retry threshold is when we accept any size for PCM data. This is slightly
6822 // smaller than the retry count so we can push small bits of data without a glitch.
6823 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006824 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006825 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006826 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006827 minFrames = mNormalFrameCount;
6828 } else {
6829 minFrames = 1;
6830 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006831
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006832 const size_t framesReady = track->framesReady();
6833 const int trackId = track->id();
6834 if (ATRACE_ENABLED()) {
6835 std::string traceName("nRdy");
6836 traceName += std::to_string(trackId);
6837 ATRACE_INT(traceName.c_str(), framesReady);
6838 }
6839 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006840 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006841 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006842 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006843
Andy Hung8d31fd22023-06-26 19:20:57 -07006844 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6845 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006846 if (last) {
6847 // make sure processVolume_l() will apply new volume even if 0
6848 mLeftVolFloat = mRightVolFloat = -1.0;
6849 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006850 if (!mHwSupportsPause) {
6851 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006852 }
6853 }
6854
6855 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006856 processVolume_l(track, last);
6857 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006858 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006859 if (previousTrack != 0) {
6860 if (track != previousTrack.get()) {
6861 // Flush any data still being written from last track
6862 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006863 // Invalidate previous track to force a seek when resuming.
6864 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006865 }
6866 }
6867 mPreviousTrack = track;
6868
Eric Laurentd595b7c2013-04-03 17:27:56 -07006869 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006870 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006871 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006872 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006873 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006874 doHwResume = true;
6875 mHwPaused = false;
6876 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006877 }
Eric Laurent81784c32012-11-19 14:55:58 -08006878 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006879 // clear effect chain input buffer if the last active track started underruns
6880 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006881 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006882 mEffectChains[0]->clearInputBuffer();
6883 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006884 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006885 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006886 if (last && mHwPaused) {
6887 doHwResume = true;
6888 mHwPaused = false;
6889 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006890 }
6891 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6892 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006893 // We have consumed all the buffers of this track.
6894 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006895 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006896 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006897 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006898 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006899 if (presComplete) {
6900 mOutput->presentationComplete();
6901 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006902 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006903 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006904 }
Eric Laurent81784c32012-11-19 14:55:58 -08006905 if (track->isStopped()) {
6906 track->reset();
6907 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006908 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006909 }
6910 } else {
6911 // No buffers for this track. Give it a few chances to
6912 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006913 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006914 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006915 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006916 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006917 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006918 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006919 } else {
6920 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6921 tracksToRemove->add(track);
6922 // indicate to client process that the track was disabled because of
6923 // underrun; it will then automatically call start() when data is available
6924 track->disable();
6925 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6926 // unlike mixerthread, HAL can be paused for direct output
6927 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6928 "minFrames = %u, mFormat = %#x",
6929 framesReady, minFrames, mFormat);
6930 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6931 doHwPause = true;
6932 mHwPaused = true;
6933 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006934 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006935 } else if (last) {
6936 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006937 }
6938 }
6939 }
6940 }
6941
Eric Laurentd1f69b02014-12-15 14:33:13 -08006942 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006943 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006944 for (size_t i = 0; i < mTracks.size(); i++) {
6945 if (mTracks[i]->isFlushPending()) {
6946 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006947 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006948 }
6949 }
6950 }
6951
6952 // make sure the pause/flush/resume sequence is executed in the right order.
6953 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6954 // before flush and then resume HW. This can happen in case of pause/flush/resume
6955 // if resume is received before pause is executed.
6956 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006957 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006958 status_t result = mOutput->stream->pause();
6959 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006960 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006961 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006962 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006963 flushHw_l();
6964 }
6965 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006966 status_t result = mOutput->stream->resume();
6967 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006968 }
Eric Laurent81784c32012-11-19 14:55:58 -08006969 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006970 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006971
6972 return mixerStatus;
6973}
6974
Andy Hungee58e4a2023-07-07 13:47:37 -07006975void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006976{
Eric Laurent81784c32012-11-19 14:55:58 -08006977 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006978 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006979 // output audio to hardware
6980 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006981 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006982 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006983 status_t status = mActiveTrack->getNextBuffer(&buffer);
6984 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006985 // no need to pad with 0 for compressed audio
6986 if (audio_has_proportional_frames(mFormat)) {
6987 memset(curBuf, 0, frameCount * mFrameSize);
6988 }
Eric Laurent81784c32012-11-19 14:55:58 -08006989 break;
6990 }
6991 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6992 frameCount -= buffer.frameCount;
6993 curBuf += buffer.frameCount * mFrameSize;
6994 mActiveTrack->releaseBuffer(&buffer);
6995 }
Andy Hung2098f272014-02-27 14:00:06 -08006996 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006997 mSleepTimeUs = 0;
6998 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006999 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007000}
7001
Andy Hungee58e4a2023-07-07 13:47:37 -07007002void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007003{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007004 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007005 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007006 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007007 return;
7008 }
Andy Hung85ba3332021-04-27 17:40:26 -07007009 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7010 mSleepTimeUs = mActiveSleepTimeUs;
7011 } else {
7012 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007013 }
Andy Hung85ba3332021-04-27 17:40:26 -07007014 // Note: In S or later, we do not write zeroes for
7015 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007016}
7017
Andy Hungee58e4a2023-07-07 13:47:37 -07007018void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007019{
7020 {
Andy Hung972bec12023-08-31 16:13:39 -07007021 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007022 for (size_t i = 0; i < mTracks.size(); i++) {
7023 if (mTracks[i]->isFlushPending()) {
7024 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007025 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007026 }
7027 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007028 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007029 flushHw_l();
7030 }
7031 }
7032 PlaybackThread::threadLoop_exit();
7033}
7034
7035// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007036bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007037{
7038 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007039 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007040
7041 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
7042 // after a timeout and we will enter standby then.
7043 if (mTracks.size() > 0) {
7044 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07007045 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07007046 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007047 }
7048
Eric Laurent5cff4032015-05-26 13:49:58 -07007049 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08007050}
7051
Andy Hungc5007f82023-08-29 14:26:09 -07007052// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007053bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007054 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007055{
7056 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007057 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007058
Eric Laurent10351942014-05-08 18:49:52 -07007059 AudioParameter param = AudioParameter(keyValuePair);
7060 int value;
7061 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007062 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007063 }
Eric Laurent10351942014-05-08 18:49:52 -07007064 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7065 // do not accept frame count changes if tracks are open as the track buffer
7066 // size depends on frame count and correct behavior would not be garantied
7067 // if frame count is changed after track creation
7068 if (!mTracks.isEmpty()) {
7069 status = INVALID_OPERATION;
7070 } else {
7071 reconfig = true;
7072 }
7073 }
7074 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007075 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007076 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007077 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007078 if (!mStandby) {
7079 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007080 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007081 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007082 }
Eric Laurent10351942014-05-08 18:49:52 -07007083 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007084 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007085 }
7086 if (status == NO_ERROR && reconfig) {
7087 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007088 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007089 }
7090 }
7091
Dean Wheatley68918102021-03-19 22:09:19 +11007092 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007093}
7094
Andy Hungee58e4a2023-07-07 13:47:37 -07007095uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007096{
7097 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007098 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007099 time = PlaybackThread::activeSleepTimeUs();
7100 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007101 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007102 }
7103 return time;
7104}
7105
Andy Hungee58e4a2023-07-07 13:47:37 -07007106uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007107{
7108 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007109 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007110 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7111 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007112 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007113 }
7114 return time;
7115}
7116
Andy Hungee58e4a2023-07-07 13:47:37 -07007117uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007118{
7119 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007120 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007121 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7122 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007123 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007124 }
7125 return time;
7126}
7127
Andy Hungee58e4a2023-07-07 13:47:37 -07007128void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007129{
7130 PlaybackThread::cacheParameters_l();
7131
7132 // use shorter standby delay as on normal output to release
7133 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007134 // no delay on outputs with HW A/V sync
7135 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007136 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007137 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007138 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007139 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007140 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007141 }
Eric Laurent81784c32012-11-19 14:55:58 -08007142}
7143
Andy Hungee58e4a2023-07-07 13:47:37 -07007144void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007145{
ziyangch8f194f12021-12-01 13:48:04 -08007146 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007147 mOutput->flush();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007148 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007149 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007150 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007151 mMonotonicFrameCounter.onFlush();
Haofan Wang0770bc82024-10-03 17:37:55 +00007152 // We do not reset mHwPaused which is hidden from the Track client.
7153 // Note: the client track in Tracks.cpp and AudioTrack.cpp
7154 // has a FLUSHED state but the DirectOutputThread does not;
7155 // those tracks will continue to show isStopped().
Eric Laurente659ef42014-09-29 13:06:46 -07007156}
7157
Andy Hungee58e4a2023-07-07 13:47:37 -07007158int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007159 // If a VolumeShaper is active, we must wake up periodically to update volume.
7160 const int64_t NS_PER_MS = 1000000;
7161 return mVolumeShaperActive ?
7162 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7163}
7164
Eric Laurent81784c32012-11-19 14:55:58 -08007165// ----------------------------------------------------------------------------
7166
Andy Hungee58e4a2023-07-07 13:47:37 -07007167AsyncCallbackThread::AsyncCallbackThread(
7168 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007169 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007170 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007171 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007172 mDrainSequence(0),
7173 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007174{
7175}
7176
Andy Hungee58e4a2023-07-07 13:47:37 -07007177void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007178{
7179 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7180}
7181
Andy Hungee58e4a2023-07-07 13:47:37 -07007182bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007183{
7184 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007185 uint32_t writeAckSequence;
7186 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007187 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007188
7189 {
Andy Hungc5007f82023-08-29 14:26:09 -07007190 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007191 while (!((mWriteAckSequence & 1) ||
7192 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007193 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007194 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007195 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007196 }
7197
Eric Laurentbfb1b832013-01-07 09:53:42 -08007198 if (exitPending()) {
7199 break;
7200 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007201 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7202 mWriteAckSequence, mDrainSequence);
7203 writeAckSequence = mWriteAckSequence;
7204 mWriteAckSequence &= ~1;
7205 drainSequence = mDrainSequence;
7206 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007207 asyncError = mAsyncError;
7208 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007209 }
7210 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007211 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007212 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007213 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007214 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007215 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007216 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007217 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007218 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007219 if (asyncError) {
7220 playbackThread->onAsyncError();
7221 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007222 }
7223 }
7224 }
7225 return false;
7226}
7227
Andy Hungee58e4a2023-07-07 13:47:37 -07007228void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007229{
7230 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007231 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007232 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007233 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007234}
7235
Andy Hungee58e4a2023-07-07 13:47:37 -07007236void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007237{
Andy Hung972bec12023-08-31 16:13:39 -07007238 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007239 // bit 0 is cleared
7240 mWriteAckSequence = sequence << 1;
7241}
7242
Andy Hungee58e4a2023-07-07 13:47:37 -07007243void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007244{
Andy Hung972bec12023-08-31 16:13:39 -07007245 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007246 // ignore unexpected callbacks
7247 if (mWriteAckSequence & 2) {
7248 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007249 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007250 }
7251}
7252
Andy Hungee58e4a2023-07-07 13:47:37 -07007253void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007254{
Andy Hung972bec12023-08-31 16:13:39 -07007255 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007256 // bit 0 is cleared
7257 mDrainSequence = sequence << 1;
7258}
7259
Andy Hungee58e4a2023-07-07 13:47:37 -07007260void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007261{
Andy Hung972bec12023-08-31 16:13:39 -07007262 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007263 // ignore unexpected callbacks
7264 if (mDrainSequence & 2) {
7265 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007266 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007267 }
7268}
7269
Andy Hungee58e4a2023-07-07 13:47:37 -07007270void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007271{
Andy Hung972bec12023-08-31 16:13:39 -07007272 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007273 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007274 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007275}
7276
Eric Laurentbfb1b832013-01-07 09:53:42 -08007277
7278// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007279
7280/* static */
7281sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007282 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007283 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7284 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007285 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007286}
7287
Andy Hung583043b2023-07-17 17:05:00 -07007288OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007289 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7290 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007291 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007292 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007293{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007294 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007295 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007296 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007297}
7298
Andy Hungee58e4a2023-07-07 13:47:37 -07007299void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007300{
7301 if (mFlushPending || mHwPaused) {
7302 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007303 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007304 flushHw_l();
7305 } else {
7306 mMixerStatus = MIXER_DRAIN_ALL;
7307 threadLoop_drain();
7308 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007309 if (mUseAsyncWrite) {
7310 ALOG_ASSERT(mCallbackThread != 0);
7311 mCallbackThread->exit();
7312 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007313 PlaybackThread::threadLoop_exit();
7314}
7315
Andy Hungee58e4a2023-07-07 13:47:37 -07007316PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007317 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007318)
7319{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007320 size_t count = mActiveTracks.size();
7321
7322 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007323 bool doHwPause = false;
7324 bool doHwResume = false;
7325
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007326 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007327
Eric Laurentbfb1b832013-01-07 09:53:42 -08007328 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007329 for (const sp<IAfTrack>& t : mActiveTracks) {
7330 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007331#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007332 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007333#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007334 // Only consider last track started for volume and mixer state control.
7335 // In theory an older track could underrun and restart after the new one starts
7336 // but as we only care about the transition phase between two tracks on a
7337 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007338 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007339 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007340
Haynes Mathew George7844f672014-01-15 12:32:55 -08007341 if (track->isInvalid()) {
7342 ALOGW("An invalidated track shouldn't be in active list");
7343 tracksToRemove->add(track);
7344 continue;
7345 }
7346
Andy Hung8d31fd22023-06-26 19:20:57 -07007347 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007348 ALOGW("An idle track shouldn't be in active list");
7349 continue;
7350 }
7351
Kuowei Li23666472021-01-20 10:23:25 +08007352 if (track->isPausePending()) {
7353 track->pauseAck();
7354 // It is possible a track might have been flushed or stopped.
7355 // Other operations such as flush pending might occur on the next prepare.
7356 if (track->isPausing()) {
7357 track->setPaused();
7358 }
7359 // Always perform pause if last, as an immediate flush will change
7360 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007361 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007362 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007363 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007364 mHwPaused = true;
7365 }
7366 // If we were part way through writing the mixbuffer to
7367 // the HAL we must save this until we resume
7368 // BUG - this will be wrong if a different track is made active,
7369 // in that case we want to discard the pending data in the
7370 // mixbuffer and tell the client to present it again when the
7371 // track is resumed
7372 mPausedWriteLength = mCurrentWriteLength;
7373 mPausedBytesRemaining = mBytesRemaining;
7374 mBytesRemaining = 0; // stop writing
7375 }
7376 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007377 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007378 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007379 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007380 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007381 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007382 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007383 track->flushAck();
7384 if (last) {
7385 mFlushPending = true;
7386 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007387 } else if (track->isResumePending()){
7388 track->resumeAck();
7389 if (last) {
7390 if (mPausedBytesRemaining) {
7391 // Need to continue write that was interrupted
7392 mCurrentWriteLength = mPausedWriteLength;
7393 mBytesRemaining = mPausedBytesRemaining;
7394 mPausedBytesRemaining = 0;
7395 }
7396 if (mHwPaused) {
7397 doHwResume = true;
7398 mHwPaused = false;
7399 // threadLoop_mix() will handle the case that we need to
7400 // resume an interrupted write
7401 }
7402 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007403 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007404
Eric Laurent3df841a2016-07-15 15:15:40 -07007405 mLeftVolFloat = mRightVolFloat = -1.0;
7406
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007407 // Do not handle new data in this iteration even if track->framesReady()
7408 mixerStatus = MIXER_TRACKS_ENABLED;
7409 }
7410 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007411 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007412 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007413 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7414 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007415 if (last) {
7416 // make sure processVolume_l() will apply new volume even if 0
7417 mLeftVolFloat = mRightVolFloat = -1.0;
7418 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007419 }
7420
7421 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007422 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007423 if (previousTrack != 0) {
7424 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007425 // Flush any data still being written from last track
7426 mBytesRemaining = 0;
7427 if (mPausedBytesRemaining) {
7428 // Last track was paused so we also need to flush saved
7429 // mixbuffer state and invalidate track so that it will
7430 // re-submit that unwritten data when it is next resumed
7431 mPausedBytesRemaining = 0;
7432 // Invalidate is a bit drastic - would be more efficient
7433 // to have a flag to tell client that some of the
7434 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007435 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007436 }
7437 // flush data already sent to the DSP if changing audio session as audio
7438 // comes from a different source. Also invalidate previous track to force a
7439 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007440 if (previousTrack->sessionId() != track->sessionId()) {
7441 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007442 }
7443 }
7444 }
7445 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007446 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007447 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007448 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007449 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007450 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007451 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007452 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007453 mixerStatus = MIXER_TRACKS_READY;
7454 }
7455 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007456 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007457 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007458 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007459 // Hardware buffer can hold a large amount of audio so we must
7460 // wait for all current track's data to drain before we say
7461 // that the track is stopped.
7462 if (mBytesRemaining == 0) {
7463 // Only start draining when all data in mixbuffer
7464 // has been written
7465 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007466 track->setState(IAfTrackBase::STOPPING_2);
7467 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007468 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7469 if (last && !mStandby) {
7470 // do not modify drain sequence if we are already draining. This happens
7471 // when resuming from pause after drain.
7472 if ((mDrainSequence & 1) == 0) {
7473 mSleepTimeUs = 0;
7474 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7475 mixerStatus = MIXER_DRAIN_TRACK;
7476 mDrainSequence += 2;
7477 }
7478 if (mHwPaused) {
7479 // It is possible to move from PAUSED to STOPPING_1 without
7480 // a resume so we must ensure hardware is running
7481 doHwResume = true;
7482 mHwPaused = false;
7483 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007484 }
7485 }
Eric Laurente93cc032016-05-05 10:15:10 -07007486 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007487 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007488 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007489 }
7490 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007491 // Drain has completed or we are in standby, signal presentation complete
7492 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007493 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007494 mOutput->presentationComplete();
7495 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007496 track->reset();
7497 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007498 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007499 if (!mUseAsyncWrite) {
7500 // If we don't get explicit drain notification we must
7501 // register discontinuity regardless of whether this is
7502 // the previous (!last) or the upcoming (last) track
7503 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007504 mTimestampVerifier.discontinuity(
7505 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007506 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007507 }
7508 } else {
7509 // No buffers for this track. Give it a few chances to
7510 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007511 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007512 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007513 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007514 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007515 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007516 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007517 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7518 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007519 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007520 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007521 // it will then automatically call start() when data is available
7522 track->disable();
7523 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007524 } else if (last){
7525 mixerStatus = MIXER_TRACKS_ENABLED;
7526 }
7527 }
7528 }
7529 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007530 if (track->isReady()) { // check ready to prevent premature start.
7531 processVolume_l(track, last);
7532 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007533 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007534
Eric Laurentea0fade2013-10-04 16:23:48 -07007535 // make sure the pause/flush/resume sequence is executed in the right order.
7536 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7537 // before flush and then resume HW. This can happen in case of pause/flush/resume
7538 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007539 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007540 status_t result = mOutput->stream->pause();
7541 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007542 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007543 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007544 if (mFlushPending) {
7545 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007546 }
Eric Laurentfd477972013-10-25 18:10:40 -07007547 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007548 status_t result = mOutput->stream->resume();
7549 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007550 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007551
Eric Laurentbfb1b832013-01-07 09:53:42 -08007552 // remove all the tracks that need to be...
7553 removeTracks_l(*tracksToRemove);
7554
7555 return mixerStatus;
7556}
7557
Eric Laurentbfb1b832013-01-07 09:53:42 -08007558// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007559bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007560{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007561 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7562 mWriteAckSequence, mDrainSequence);
7563 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007564 return true;
7565 }
7566 return false;
7567}
7568
Andy Hungee58e4a2023-07-07 13:47:37 -07007569bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007570{
Andy Hung972bec12023-08-31 16:13:39 -07007571 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007572 return waitingAsyncCallback_l();
7573}
7574
Andy Hungee58e4a2023-07-07 13:47:37 -07007575void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007576{
Eric Laurente659ef42014-09-29 13:06:46 -07007577 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007578 // Flush anything still waiting in the mixbuffer
7579 mCurrentWriteLength = 0;
7580 mBytesRemaining = 0;
7581 mPausedWriteLength = 0;
7582 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007583 // reset bytes written count to reflect that DSP buffers are empty after flush.
7584 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007585
Eric Laurentbfb1b832013-01-07 09:53:42 -08007586 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007587 // discard any pending drain or write ack by incrementing sequence
7588 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7589 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007590 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007591 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7592 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007593 }
7594}
7595
Andy Hungee58e4a2023-07-07 13:47:37 -07007596void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007597{
Andy Hung972bec12023-08-31 16:13:39 -07007598 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007599 if (PlaybackThread::invalidateTracks_l(streamType)) {
7600 mFlushPending = true;
7601 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007602}
7603
Andy Hungee58e4a2023-07-07 13:47:37 -07007604void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007605 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007606 if (PlaybackThread::invalidateTracks_l(portIds)) {
7607 mFlushPending = true;
7608 }
7609}
7610
Eric Laurentbfb1b832013-01-07 09:53:42 -08007611// ----------------------------------------------------------------------------
7612
Andy Hungee58e4a2023-07-07 13:47:37 -07007613/* static */
7614sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007615 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007616 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007617 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007618}
7619
Andy Hung583043b2023-07-17 17:05:00 -07007620DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007621 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007622 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007623 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007624 mWaitTimeMs(UINT_MAX)
7625{
7626 addOutputTrack(mainThread);
7627}
7628
Andy Hungee58e4a2023-07-07 13:47:37 -07007629DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007630{
7631 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7632 mOutputTracks[i]->destroy();
7633 }
7634}
7635
Andy Hungee58e4a2023-07-07 13:47:37 -07007636void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007637{
7638 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007639 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007640 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007641 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007642 if (mMixerBufferValid) {
7643 memset(mMixerBuffer, 0, mMixerBufferSize);
7644 } else {
7645 memset(mSinkBuffer, 0, mSinkBufferSize);
7646 }
Eric Laurent81784c32012-11-19 14:55:58 -08007647 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007648 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007649 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007650 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007651 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007652}
7653
Andy Hungee58e4a2023-07-07 13:47:37 -07007654void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007655{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007656 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007657 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007658 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007659 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007660 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007661 }
7662 } else if (mBytesWritten != 0) {
7663 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7664 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007665 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007666 } else {
7667 // flush remaining overflow buffers in output tracks
7668 writeFrames = 0;
7669 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007670 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007671 }
7672}
7673
Andy Hungee58e4a2023-07-07 13:47:37 -07007674ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007675{
7676 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007677 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7678
7679 // Consider the first OutputTrack for timestamp and frame counting.
7680
7681 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7682 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7683 // we always claim success.
7684 if (i == 0) {
7685 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7686 ALOGD_IF(correction != 0 && writeFrames != 0,
7687 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7688 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7689 mFramesWritten -= correction;
7690 }
7691
7692 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007693 }
Andy Hungcf10d742020-04-28 15:38:24 -07007694 if (mStandby) {
7695 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007696 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007697 mStandby = false;
7698 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007699 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007700}
7701
Andy Hungee58e4a2023-07-07 13:47:37 -07007702void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007703{
7704 // DuplicatingThread implements standby by stopping all tracks
7705 for (size_t i = 0; i < outputTracks.size(); i++) {
7706 outputTracks[i]->stop();
7707 }
7708}
7709
Andy Hung8a5abfd2023-12-07 19:35:12 -08007710void DuplicatingThread::threadLoop_exit()
7711{
7712 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7713 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7714 // Do so here in the threadLoop_exit().
7715
7716 SortedVector <sp<IAfOutputTrack>> localTracks;
7717 {
7718 audio_utils::lock_guard l(mutex());
7719 localTracks = std::move(mOutputTracks);
7720 mOutputTracks.clear();
7721 }
7722 localTracks.clear();
7723 outputTracks.clear();
7724 PlaybackThread::threadLoop_exit();
7725}
7726
Andy Hungee58e4a2023-07-07 13:47:37 -07007727void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007728{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007729 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007730
7731 std::stringstream ss;
7732 const size_t numTracks = mOutputTracks.size();
7733 ss << " " << numTracks << " OutputTracks";
7734 if (numTracks > 0) {
7735 ss << ":";
7736 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007737 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007738 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007739 if (thread.get() != nullptr) {
7740 ss << thread.get() << ", " << thread->id();
7741 } else {
7742 ss << "null";
7743 }
7744 ss << ")";
7745 }
7746 }
7747 ss << "\n";
7748 std::string result = ss.str();
7749 write(fd, result.c_str(), result.size());
7750}
7751
Andy Hungee58e4a2023-07-07 13:47:37 -07007752void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007753{
7754 outputTracks = mOutputTracks;
7755}
7756
Andy Hungee58e4a2023-07-07 13:47:37 -07007757void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007758{
7759 outputTracks.clear();
7760}
7761
Andy Hungee58e4a2023-07-07 13:47:37 -07007762void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007763{
Andy Hung972bec12023-08-31 16:13:39 -07007764 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007765 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7766 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7767 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7768 const size_t frameCount =
7769 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7770 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7771 // from different OutputTracks and their associated MixerThreads (e.g. one may
7772 // nearly empty and the other may be dropping data).
7773
Svet Ganov33761132021-05-13 22:51:08 +00007774 // TODO b/182392769: use attribution source util, move to server edge
7775 AttributionSourceState attributionSource = AttributionSourceState();
7776 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007777 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007778 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007779 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007780 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007781 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007782 this,
7783 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007784 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007785 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007786 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007787 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007788 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7789 if (status != NO_ERROR) {
7790 ALOGE("addOutputTrack() initCheck failed %d", status);
7791 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007792 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007793 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7794 mOutputTracks.add(outputTrack);
7795 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7796 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007797}
7798
Andy Hungee58e4a2023-07-07 13:47:37 -07007799void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007800{
Andy Hung972bec12023-08-31 16:13:39 -07007801 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007802 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7803 if (mOutputTracks[i]->thread() == thread) {
7804 mOutputTracks[i]->destroy();
7805 mOutputTracks.removeAt(i);
7806 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007807 // NO_THREAD_SAFETY_ANALYSIS
7808 // Lambda workaround: as thread != this
7809 // we can safely call the remote thread getOutput.
7810 const bool equalOutput =
7811 [&](){ return thread->getOutput() == mOutput; }();
7812 if (equalOutput) {
7813 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007814 }
Eric Laurent81784c32012-11-19 14:55:58 -08007815 return;
7816 }
7817 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007818 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007819}
7820
Andy Hungc5007f82023-08-29 14:26:09 -07007821// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007822void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007823{
7824 mWaitTimeMs = UINT_MAX;
7825 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007826 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007827 if (strong != 0) {
7828 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7829 if (waitTimeMs < mWaitTimeMs) {
7830 mWaitTimeMs = waitTimeMs;
7831 }
7832 }
7833 }
7834}
7835
Andy Hungee58e4a2023-07-07 13:47:37 -07007836bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007837{
7838 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007839 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007840 if (thread == 0) {
7841 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7842 outputTracks[i].get());
7843 return false;
7844 }
Andy Hung87c693c2023-07-06 20:56:16 -07007845 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007846 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007847 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007848 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7849 thread.get());
7850 return false;
7851 }
7852 }
7853 return true;
7854}
7855
Andy Hungee58e4a2023-07-07 13:47:37 -07007856void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007857 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007858{
Kevin Rocard12381092018-04-11 09:19:59 -07007859 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7860 outputTrack->setMetadatas(metadata.tracks);
7861 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007862}
7863
Andy Hungee58e4a2023-07-07 13:47:37 -07007864uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007865{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007866 // return half the wait time in microseconds.
7867 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007868}
7869
Andy Hungee58e4a2023-07-07 13:47:37 -07007870void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007871{
7872 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7873 updateWaitTime_l();
7874
7875 MixerThread::cacheParameters_l();
7876}
7877
Eric Laurentb3f315a2021-07-13 15:09:05 +02007878// ----------------------------------------------------------------------------
7879
Andy Hungee58e4a2023-07-07 13:47:37 -07007880/* static */
7881sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007882 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007883 AudioStreamOut* output,
7884 audio_io_handle_t id,
7885 bool systemReady,
7886 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007887 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007888}
7889
Andy Hung583043b2023-07-17 17:05:00 -07007890SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007891 AudioStreamOut* output,
7892 audio_io_handle_t id,
7893 bool systemReady,
7894 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007895 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007896{
7897}
7898
Andy Hungee58e4a2023-07-07 13:47:37 -07007899void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007900 // if mSupportedLatencyModes is empty, the HAL stream does not support
7901 // latency mode control and we can exit.
7902 if (mSupportedLatencyModes.empty()) {
7903 return;
7904 }
Eric Laurent4c85e372024-02-23 16:50:06 +00007905 // Do not update the HAL latency mode if no track is active
7906 if (mActiveTracks.isEmpty()) {
7907 return;
7908 }
7909
Eric Laurent68a40a82022-05-03 18:15:04 +02007910 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7911 if (mSupportedLatencyModes.size() == 1) {
7912 // If the HAL only support one latency mode currently, confirm the choice
7913 latencyMode = mSupportedLatencyModes[0];
7914 } else if (mSupportedLatencyModes.size() > 1) {
7915 // Request low latency if:
7916 // - The low latency mode is requested by the spatializer controller
7917 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7918 // AND
7919 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007920 for (const auto& track : mActiveTracks) {
7921 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007922 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007923 break;
7924 }
7925 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007926 }
7927
7928 if (latencyMode != mSetLatencyMode) {
7929 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007930 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7931 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007932 if (status == NO_ERROR) {
7933 mSetLatencyMode = latencyMode;
7934 }
7935 }
7936}
7937
Andy Hungee58e4a2023-07-07 13:47:37 -07007938status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01007939 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007940 return BAD_VALUE;
7941 }
Andy Hung972bec12023-08-31 16:13:39 -07007942 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007943 mRequestedLatencyMode = mode;
7944 return NO_ERROR;
7945}
7946
Andy Hungee58e4a2023-07-07 13:47:37 -07007947void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007948NO_THREAD_SAFETY_ANALYSIS
7949// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007950{
7951 bool hasVirtualizer = false;
7952 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007953 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007954 {
Andy Hung972bec12023-08-31 16:13:39 -07007955 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007956 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007957 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007958 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007959 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7960 }
7961
7962 finalDownMixer = mFinalDownMixer;
7963 mFinalDownMixer.clear();
7964 }
7965
7966 if (hasVirtualizer) {
7967 if (finalDownMixer != nullptr) {
7968 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007969 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007970 }
7971 finalDownMixer.clear();
7972 } else if (!hasDownMixer) {
7973 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007974 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007975 EFFECT_UIID_DOWNMIX, &descriptors);
7976 if (status != NO_ERROR) {
7977 return;
7978 }
7979 ALOG_ASSERT(!descriptors.empty(),
7980 "%s getDescriptors() returned no error but empty list", __func__);
7981
7982 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7983 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007984 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007985
7986 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7987 ALOGW("%s error creating downmixer %d", __func__, status);
7988 finalDownMixer.clear();
7989 } else {
7990 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007991 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007992 }
7993 }
7994
7995 {
Andy Hung972bec12023-08-31 16:13:39 -07007996 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007997 mFinalDownMixer = finalDownMixer;
7998 }
7999}
8000
Andy Hunge2514462023-12-06 14:59:24 -08008001void SpatializerThread::threadLoop_exit()
8002{
8003 // The Spatializer EffectHandle must be released on the PlaybackThread
8004 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8005 mFinalDownMixer.clear();
8006
8007 PlaybackThread::threadLoop_exit();
8008}
8009
Eric Laurent81784c32012-11-19 14:55:58 -08008010// ----------------------------------------------------------------------------
8011// Record
8012// ----------------------------------------------------------------------------
8013
Andy Hung583043b2023-07-17 17:05:00 -07008014sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008015 AudioStreamIn* input,
8016 audio_io_handle_t id,
8017 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008018 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008019}
8020
Andy Hung583043b2023-07-17 17:05:00 -07008021RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008022 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008023 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008024 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008025 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008026 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008027 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008028 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008029 mActiveTracks(&this->mLocalLog),
8030 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008031 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008032 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008033 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8034 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008035 // mFastCapture below
8036 , mFastCaptureFutex(0)
8037 // mInputSource
8038 // mPipeSink
8039 // mPipeSource
8040 , mPipeFramesP2(0)
8041 // mPipeMemory
8042 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008043 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008044 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008045{
Glenn Kastend7dca052015-03-05 16:05:54 -08008046 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008047 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008048
George Burgess IVa8f90c12020-05-14 11:27:19 -07008049 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008050 mIsMsdDevice = strcmp(
8051 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8052 }
8053
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008054 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008055
Andy Hungc8fddf32018-08-08 18:32:37 -07008056 // TODO: We may also match on address as well as device type for
8057 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008058 // TODO: This property should be ensure that only contains one single device type.
8059 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8060 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008061 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8062 : AUDIO_DEVICE_NONE));
8063
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008064 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008065 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008066 size_t numCounterOffers = 0;
8067 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008068#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008069 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008070#else
8071 (void)
8072#endif
8073 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008074 ALOG_ASSERT(index == 0);
8075
8076 // initialize fast capture depending on configuration
8077 bool initFastCapture;
8078 switch (kUseFastCapture) {
8079 case FastCapture_Never:
8080 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008081 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008082 break;
8083 case FastCapture_Always:
8084 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008085 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008086 break;
8087 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008088 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008089 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008090 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008091 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8092 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8093 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008094 break;
8095 // case FastCapture_Dynamic:
8096 }
8097
8098 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008099 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008100 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008101 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8102 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008103 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008104 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008105 const sp<MemoryDealer> roHeap(readOnlyHeap());
8106 sp<IMemory> pipeMemory;
8107 if ((roHeap == 0) ||
8108 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008109 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008110 ALOGE("not enough memory for pipe buffer size=%zu; "
8111 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8112 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8113 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008114 goto failed;
8115 }
8116 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8117 memset(pipeBuffer, 0, pipeSize);
8118 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008119 const NBAIO_Format offersFast[1] = {format};
8120 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008121 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008122 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008123 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008124 mPipeSink = pipe;
8125 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008126 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008127 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008128 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008129 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008130 mPipeSource = pipeReader;
8131 mPipeFramesP2 = pipeFramesP2;
8132 mPipeMemory = pipeMemory;
8133
8134 // create fast capture
8135 mFastCapture = new FastCapture();
8136 FastCaptureStateQueue *sq = mFastCapture->sq();
8137#ifdef STATE_QUEUE_DUMP
8138 // FIXME
8139#endif
8140 FastCaptureState *state = sq->begin();
8141 state->mCblk = NULL;
8142 state->mInputSource = mInputSource.get();
8143 state->mInputSourceGen++;
8144 state->mPipeSink = pipe;
8145 state->mPipeSinkGen++;
8146 state->mFrameCount = mFrameCount;
8147 state->mCommand = FastCaptureState::COLD_IDLE;
8148 // already done in constructor initialization list
8149 //mFastCaptureFutex = 0;
8150 state->mColdFutexAddr = &mFastCaptureFutex;
8151 state->mColdGen++;
8152 state->mDumpState = &mFastCaptureDumpState;
8153#ifdef TEE_SINK
8154 // FIXME
8155#endif
Andy Hung583043b2023-07-17 17:05:00 -07008156 mFastCaptureNBLogWriter =
8157 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008158 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8159 sq->end();
8160 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8161
8162 // start the fast capture
8163 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8164 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008165 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008166 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008167#ifdef AUDIO_WATCHDOG
8168 // FIXME
8169#endif
8170
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008171 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008172 }
Andy Hung8946a282018-04-19 20:04:56 -07008173#ifdef TEE_SINK
8174 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8175 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8176#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008177failed: ;
8178
8179 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008180}
8181
Andy Hungee58e4a2023-07-07 13:47:37 -07008182RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008183{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008184 if (mFastCapture != 0) {
8185 FastCaptureStateQueue *sq = mFastCapture->sq();
8186 FastCaptureState *state = sq->begin();
8187 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8188 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8189 if (old == -1) {
8190 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8191 }
8192 }
8193 state->mCommand = FastCaptureState::EXIT;
8194 sq->end();
8195 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8196 mFastCapture->join();
8197 mFastCapture.clear();
8198 }
Andy Hung583043b2023-07-17 17:05:00 -07008199 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8200 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008201 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008202}
8203
Andy Hungee58e4a2023-07-07 13:47:37 -07008204void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008205{
Glenn Kastend7dca052015-03-05 16:05:54 -08008206 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008207}
8208
Andy Hungee58e4a2023-07-07 13:47:37 -07008209void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008210{
8211 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008212 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008213 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008214 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008215 track->invalidate();
8216 }
8217 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008218 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008219}
8220
Andy Hungee58e4a2023-07-07 13:47:37 -07008221bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008222{
Eric Laurent81784c32012-11-19 14:55:58 -08008223 nsecs_t lastWarning = 0;
8224
8225 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008226
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008227reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008228 {
Andy Hung972bec12023-08-31 16:13:39 -07008229 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008230 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008231 }
8232
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008233 // used to request a deferred sleep, to be executed later while mutex is unlocked
8234 uint32_t sleepUs = 0;
8235
Andy Hung95c94a22023-10-20 16:41:18 -07008236 // timestamp correction enable is determined under lock, used in processing step.
8237 bool timestampCorrectionEnabled = false;
8238
Andy Hung446f4df2019-02-21 12:26:41 -08008239 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8240
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008241 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008242 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008243 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8244 sp<IAfRecordTrack> activeTrack;
Andy Hung116bc262023-06-20 18:56:17 -07008245 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008246
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008247 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008248 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008249
Glenn Kasten735f45f2014-08-18 15:51:59 -07008250 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008251 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008252
Glenn Kasten735f45f2014-08-18 15:51:59 -07008253 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008254 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008255
Eric Laurent33403f02020-05-29 18:35:06 -07008256 bool silenceFastCapture = false;
8257
Andy Hungc5007f82023-08-29 14:26:09 -07008258 { // scope for mutex()
8259 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008260
Eric Laurent021cf962014-05-13 10:18:14 -07008261 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008262
Eric Laurent000a4192014-01-29 15:17:32 -08008263 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008264 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008265 if (exitPending()) {
8266 break;
8267 }
8268
Eric Laurent5c25d562016-07-13 17:17:45 -07008269 // sleep with mutex unlocked
8270 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008271 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008272 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008273 ATRACE_END();
8274 sleepUs = 0;
8275 continue;
8276 }
8277
Glenn Kasten2b806402013-11-20 16:37:38 -08008278 // if no active track(s), then standby and release wakelock
8279 size_t size = mActiveTracks.size();
8280 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008281 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008282 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008283 releaseWakeLock_l();
8284 ALOGV("RecordThread: loop stopping");
8285 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008286 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008287 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008288 goto reacquire_wakelock;
8289 }
8290
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008291 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008292 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008293 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008294
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008295 activeTrack = mActiveTracks[i];
8296 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008297 if (activeTrack->isFastTrack()) {
8298 ALOG_ASSERT(fastTrackToRemove == 0);
8299 fastTrackToRemove = activeTrack;
8300 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008301 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008302 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008303 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008304 continue;
8305 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008306
Andy Hung8d31fd22023-06-26 19:20:57 -07008307 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008308 switch (activeTrackState) {
8309
Andy Hung8d31fd22023-06-26 19:20:57 -07008310 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008311 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008312 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008313 if (activeTrack->isFastTrack()) {
8314 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8315 // Keep a ref on fast track to wait for FastCapture thread to get updated
8316 // state before potential track removal
8317 fastTrackToRemove = activeTrack;
8318 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008319 doBroadcast = true;
8320 size--;
8321 continue;
8322
Andy Hung8d31fd22023-06-26 19:20:57 -07008323 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008324 sleepUs = 10000;
8325 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008326 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008327 continue;
8328
Andy Hung8d31fd22023-06-26 19:20:57 -07008329 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008330 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008331 if (mStandby) {
8332 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008333 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008334 mStandby = false;
8335 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008336 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008337 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008338 break;
8339
Andy Hung8d31fd22023-06-26 19:20:57 -07008340 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008341 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008342 break;
8343
Andy Hung8d31fd22023-06-26 19:20:57 -07008344 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8345 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8346 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008347 default:
Andy Hungce685402018-10-05 17:23:27 -07008348 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8349 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008350 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008351
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008352 if (activeTrack->isFastTrack()) {
8353 ALOG_ASSERT(!mFastTrackAvail);
8354 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008355 // if the active fast track is silenced either:
8356 // 1) silence the whole capture from fast capture buffer if this is
8357 // the only active track
8358 // 2) invalidate this track: this will cause the client to reconnect and possibly
8359 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008360 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008361 if (activeTrack->isSilenced()) {
8362 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008363 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008364 } else {
8365 silenceFastCapture = true;
8366 }
8367 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008368 // Invalidate fast tracks if access to audio history is required as this is not
8369 // possible with fast tracks. Once the fast track has been invalidated, no new
8370 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8371 if (mMaxSharedAudioHistoryMs != 0) {
8372 invalidate = true;
8373 }
8374 if (invalidate) {
8375 activeTrack->invalidate();
8376 ALOG_ASSERT(fastTrackToRemove == 0);
8377 fastTrackToRemove = activeTrack;
8378 removeTrack_l(activeTrack);
8379 mActiveTracks.remove(activeTrack);
8380 size--;
8381 continue;
8382 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008383 fastTrack = activeTrack;
8384 }
Eric Laurent33403f02020-05-29 18:35:06 -07008385
8386 activeTracks.add(activeTrack);
8387 i++;
8388
Glenn Kasten9e982352013-08-14 14:39:50 -07008389 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008390
Andy Hungab65b182023-09-06 19:41:47 -07008391 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008392
Kevin Rocard069c2712018-03-29 19:09:14 -07008393 updateMetadata_l();
8394
Eric Laurent5c25d562016-07-13 17:17:45 -07008395 if (allStopped) {
8396 standbyIfNotAlreadyInStandby();
8397 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008398 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008399 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008400 }
8401
8402 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008403 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008404 if (sleepUs == 0) {
8405 sleepUs = kRecordThreadSleepUs;
8406 }
8407 continue;
8408 }
8409 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008410
Andy Hung95c94a22023-10-20 16:41:18 -07008411 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008412 lockEffectChains_l(effectChains);
8413 }
8414
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008415 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008416
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008417 size_t size = effectChains.size();
8418 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008419 // thread mutex is not locked, but effect chain is locked
8420 effectChains[i]->process_l();
8421 }
8422
Glenn Kasten735f45f2014-08-18 15:51:59 -07008423 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008424 if (mFastCapture != 0) {
8425 FastCaptureStateQueue *sq = mFastCapture->sq();
8426 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008427 bool didModify = false;
8428 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008429 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8430 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8431 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8432 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8433 if (old == -1) {
8434 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8435 }
8436 }
8437 state->mCommand = FastCaptureState::READ_WRITE;
8438#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008439 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008440 FastThreadDumpState::kSamplingNforLowRamDevice :
8441 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008442#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008443 didModify = true;
8444 }
8445 audio_track_cblk_t *cblkOld = state->mCblk;
8446 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8447 if (cblkNew != cblkOld) {
8448 state->mCblk = cblkNew;
8449 // block until acked if removing a fast track
8450 if (cblkOld != NULL) {
8451 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8452 }
8453 didModify = true;
8454 }
jiabin01c8f562018-07-19 17:47:28 -07008455 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8456 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8457 if (state->mFastPatchRecordBufferProvider != abp) {
8458 state->mFastPatchRecordBufferProvider = abp;
8459 state->mFastPatchRecordFormat = fastTrack == 0 ?
8460 AUDIO_FORMAT_INVALID : fastTrack->format();
8461 didModify = true;
8462 }
Eric Laurent33403f02020-05-29 18:35:06 -07008463 if (state->mSilenceCapture != silenceFastCapture) {
8464 state->mSilenceCapture = silenceFastCapture;
8465 didModify = true;
8466 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008467 sq->end(didModify);
8468 if (didModify) {
8469 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008470#if 0
8471 if (kUseFastCapture == FastCapture_Dynamic) {
8472 mNormalSource = mPipeSource;
8473 }
8474#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008475 }
8476 }
8477
Glenn Kasten735f45f2014-08-18 15:51:59 -07008478 // now run the fast track destructor with thread mutex unlocked
8479 fastTrackToRemove.clear();
8480
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008481 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8482 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8483 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8484 // If destination is non-contiguous, first read past the nominal end of buffer, then
8485 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008486
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008487 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008488 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008489 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008490
8491 // If an NBAIO source is present, use it to read the normal capture's data
8492 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008493 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008494
8495 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8496 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8497 // we immediately retry the read() to get data and prevent another overflow.
8498 for (int retries = 0; retries <= 2; ++retries) {
8499 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8500 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8501 framesToRead);
8502 if (framesRead != OVERRUN) break;
8503 }
8504
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008505 const ssize_t availableToRead = mPipeSource->availableToRead();
8506 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008507 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008508 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008509 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8510 "more frames to read than fifo size, %zd > %zu",
8511 availableToRead, mPipeFramesP2);
8512 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8513 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8514 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8515 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008516 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8517 }
8518 if (framesRead < 0) {
8519 status_t status = (status_t) framesRead;
8520 switch (status) {
8521 case OVERRUN:
8522 ALOGW("overrun on read from pipe");
8523 framesRead = 0;
8524 break;
8525 case NEGOTIATE:
8526 ALOGE("re-negotiation is needed");
8527 framesRead = -1; // Will cause an attempt to recover.
8528 break;
8529 default:
8530 ALOGE("unknown error %d on read from pipe", status);
8531 break;
8532 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008533 }
8534 // otherwise use the HAL / AudioStreamIn directly
8535 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008536 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008537 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008538 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008539 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008540 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008541 if (result < 0) {
8542 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008543 } else {
8544 framesRead = bytesRead / mFrameSize;
8545 }
8546 }
8547
Andy Hung446f4df2019-02-21 12:26:41 -08008548 const int64_t lastIoEndNs = systemTime(); // end IO timing
8549
Andy Hung3f0c9022016-01-15 17:49:46 -08008550 // Update server timestamp with server stats
8551 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008552 if (framesRead >= 0) {
8553 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8554 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8555 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008556
8557 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008558 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008559 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008560 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008561 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8562 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8563 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008564 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008565 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8566
8567 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008568 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008569 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008570 id(), (long long)time, (long long)position);
8571 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8572 position = correctedTimestamp.mFrames;
8573 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008574 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008575 id(), (long long)time, (long long)position);
8576 }
8577
Andy Hung3f0c9022016-01-15 17:49:46 -08008578 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8579 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8580 // Note: In general record buffers should tend to be empty in
8581 // a properly running pipeline.
8582 //
8583 // Also, it is not advantageous to call get_presentation_position during the read
8584 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008585 } else {
8586 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008587 }
8588 }
Andy Hunge6c37112019-02-26 17:38:10 -08008589
8590 // From the timestamp, input read latency is negative output write latency.
8591 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008592 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008593 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8594 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8595 mLatencyMs.add(latencyMs);
8596 }
8597
Andy Hung3f0c9022016-01-15 17:49:46 -08008598 // Use this to track timestamp information
8599 // ALOGD("%s", mTimestamp.toString().c_str());
8600
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008601 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008602 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008603 // Force input into standby so that it tries to recover at next read attempt
8604 inputStandBy();
8605 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008606 }
8607 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008608 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008609 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008610 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008611 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008612
Andy Hung8946a282018-04-19 20:04:56 -07008613#ifdef TEE_SINK
8614 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8615#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008616 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008617 {
8618 size_t part1 = mRsmpInFramesP2 - rear;
8619 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008620 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008621 (framesRead - part1) * mFrameSize);
8622 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008623 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008624 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008625
8626 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008627
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008628 // loop over each active track
8629 for (size_t i = 0; i < size; i++) {
8630 activeTrack = activeTracks[i];
8631
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008632 // skip fast tracks, as those are handled directly by FastCapture
8633 if (activeTrack->isFastTrack()) {
8634 continue;
8635 }
8636
Andy Hung73c02e42015-03-29 01:13:58 -07008637 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008638 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8639
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008640 enum {
8641 OVERRUN_UNKNOWN,
8642 OVERRUN_TRUE,
8643 OVERRUN_FALSE
8644 } overrun = OVERRUN_UNKNOWN;
8645
8646 // loop over getNextBuffer to handle circular sink
8647 for (;;) {
8648
Andy Hung8d31fd22023-06-26 19:20:57 -07008649 activeTrack->sinkBuffer().frameCount = ~0;
8650 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8651 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008652 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8653
Andy Hung73c02e42015-03-29 01:13:58 -07008654 // check available frames and handle overrun conditions
8655 // if the record track isn't draining fast enough.
8656 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008657 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008658 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008659 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008660 overrun = OVERRUN_TRUE;
8661 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008662 if (framesOut == 0 || framesIn == 0) {
8663 break;
8664 }
8665
Andy Hung6770c6f2015-04-07 13:43:36 -07008666 // Don't allow framesOut to be larger than what is possible with resampling
8667 // from framesIn.
8668 // This isn't strictly necessary but helps limit buffer resizing in
8669 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008670 if (audio_is_linear_pcm(activeTrack->format())) {
8671 framesOut = min(framesOut,
8672 destinationFramesPossible(
8673 framesIn, mSampleRate, activeTrack->sampleRate()));
8674 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008675
8676 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008677 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008678 // straight from RecordThread buffer to RecordTrack buffer.
8679 AudioBufferProvider::Buffer buffer;
8680 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008681 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008682 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008683 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008684 ALOGV_IF(buffer.frameCount != framesOut,
8685 "%s() read less than expected (%zu vs %zu)",
8686 __func__, buffer.frameCount, framesOut);
8687 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008688 memcpy(activeTrack->sinkBuffer().raw,
8689 buffer.raw, buffer.frameCount * mFrameSize);
8690 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008691 } else {
8692 framesOut = 0;
8693 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008694 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008695 }
8696 } else {
8697 // process frames from the RecordThread buffer provider to the RecordTrack
8698 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008699 framesOut = activeTrack->recordBufferConverter()->convert(
8700 activeTrack->sinkBuffer().raw,
8701 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008702 framesOut);
8703 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008704
8705 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8706 overrun = OVERRUN_FALSE;
8707 }
8708
Andy Hung93bb5732023-05-04 21:16:34 -07008709 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8710 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008711 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008712 if (framesToDrop == 0) {
8713 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008714 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008715 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008716 // Sanitize before releasing if the track has no access to the source data
8717 // An idle UID receives silence from non virtual devices until active
8718 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008719 memset(activeTrack->sinkBuffer().raw,
8720 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008721 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008722 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008723 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008724 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008725 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008726 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008727 }
8728 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008729
8730 switch (overrun) {
8731 case OVERRUN_TRUE:
8732 // client isn't retrieving buffers fast enough
8733 if (!activeTrack->setOverflow()) {
8734 nsecs_t now = systemTime();
8735 // FIXME should lastWarning per track?
8736 if ((now - lastWarning) > kWarningThrottleNs) {
8737 ALOGW("RecordThread: buffer overflow");
8738 lastWarning = now;
8739 }
8740 }
8741 break;
8742 case OVERRUN_FALSE:
8743 activeTrack->clearOverflow();
8744 break;
8745 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008746 break;
8747 }
8748
Andy Hung3f0c9022016-01-15 17:49:46 -08008749 // update frame information and push timestamp out
8750 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008751 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008752 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8753 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008754 }
8755
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008756unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008757 // enable changes in effect chain
8758 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008759 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008760 if (audio_has_proportional_frames(mFormat)
8761 && loopCount == lastLoopCountRead + 1) {
8762 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8763 const double jitterMs =
8764 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8765 {framesRead, readPeriodNs},
8766 {0, 0} /* lastTimestamp */, mSampleRate);
8767 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8768
Andy Hung972bec12023-08-31 16:13:39 -07008769 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008770 mIoJitterMs.add(jitterMs);
8771 mProcessTimeMs.add(processMs);
8772 }
8773 // update timing info.
8774 mLastIoBeginNs = lastIoBeginNs;
8775 mLastIoEndNs = lastIoEndNs;
8776 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008777 }
8778
Glenn Kasten93e471f2013-08-19 08:40:07 -07008779 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008780
8781 {
Andy Hung972bec12023-08-31 16:13:39 -07008782 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008783 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008784 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008785 track->invalidate();
8786 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008787 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008788 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008789 }
8790
8791 releaseWakeLock();
8792
8793 ALOGV("RecordThread %p exiting", this);
8794 return false;
8795}
8796
Andy Hungee58e4a2023-07-07 13:47:37 -07008797void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008798{
8799 if (!mStandby) {
8800 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008801 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008802 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008803 mStandby = true;
8804 }
8805}
8806
Andy Hungee58e4a2023-07-07 13:47:37 -07008807void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008808{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008809 // Idle the fast capture if it's currently running
8810 if (mFastCapture != 0) {
8811 FastCaptureStateQueue *sq = mFastCapture->sq();
8812 FastCaptureState *state = sq->begin();
8813 if (!(state->mCommand & FastCaptureState::IDLE)) {
8814 state->mCommand = FastCaptureState::COLD_IDLE;
8815 state->mColdFutexAddr = &mFastCaptureFutex;
8816 state->mColdGen++;
8817 mFastCaptureFutex = 0;
8818 sq->end();
8819 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8820 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8821#if 0
8822 if (kUseFastCapture == FastCapture_Dynamic) {
8823 // FIXME
8824 }
8825#endif
8826#ifdef AUDIO_WATCHDOG
8827 // FIXME
8828#endif
8829 } else {
8830 sq->end(false /*didModify*/);
8831 }
8832 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008833 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008834 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008835
8836 // If going into standby, flush the pipe source.
8837 if (mPipeSource.get() != nullptr) {
8838 const ssize_t flushed = mPipeSource->flush();
8839 if (flushed > 0) {
8840 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8841 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8842 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8843 }
8844 }
Eric Laurent81784c32012-11-19 14:55:58 -08008845}
8846
Andy Hungc5007f82023-08-29 14:26:09 -07008847// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008848sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008849 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008850 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008851 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008852 audio_format_t format,
8853 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008854 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008855 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008856 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008857 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008858 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008859 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008860 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008861 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008862 audio_port_handle_t portId,
8863 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008864{
Glenn Kasten74935e42013-12-19 08:56:45 -08008865 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008866 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008867 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008868 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008869 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008870 audio_input_flags_t requestedFlags = *flags;
8871 uint32_t sampleRate;
8872
8873 lStatus = initCheck();
8874 if (lStatus != NO_ERROR) {
8875 ALOGE("createRecordTrack_l() audio driver not initialized");
8876 goto Exit;
8877 }
8878
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008879 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8880 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8881 lStatus = BAD_VALUE;
8882 goto Exit;
8883 }
8884
Eric Laurentec376dc2021-04-08 20:41:22 +02008885 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008886 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008887 lStatus = PERMISSION_DENIED;
8888 goto Exit;
8889 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008890 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008891 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008892 lStatus = BAD_VALUE;
8893 goto Exit;
8894 }
8895 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008896 if (*pSampleRate == 0) {
8897 *pSampleRate = mSampleRate;
8898 }
8899 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008900
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008901 // special case for FAST flag considered OK if fast capture is present and access to
8902 // audio history is not required
8903 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008904 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8905 }
8906
Eric Laurentf14db3c2017-12-08 14:20:36 -08008907 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008908 if ((*flags & inputFlags) != *flags) {
8909 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8910 " input flags (%08x)",
8911 *flags, inputFlags);
8912 *flags = (audio_input_flags_t)(*flags & inputFlags);
8913 }
Eric Laurent81784c32012-11-19 14:55:58 -08008914
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008915 // client expresses a preference for FAST and no access to audio history,
8916 // but we get the final say
8917 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008918 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008919 // we formerly checked for a callback handler (non-0 tid),
8920 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008921 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008922 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008923 // Frame count is not specified (0), or is less than or equal the pipe depth.
8924 // It is OK to provide a higher capacity than requested.
8925 // We will force it to mPipeFramesP2 below.
8926 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008927 // PCM data
8928 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008929 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008930 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008931 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008932 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008933 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008934 hasFastCapture() &&
8935 // there are sufficient fast track slots available
8936 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008937 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008938 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008939 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008940 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008941 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008942 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008943 audio_input_flags_t old = *flags;
8944 chain->checkInputFlagCompatibility(flags);
8945 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008946 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8947 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008948 }
8949 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008950 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008951 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8952 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008953 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008954 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8955 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008956 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008957 this, frameCount, mFrameCount, mPipeFramesP2,
8958 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008959 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008960 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008961 }
8962 }
8963
Eric Laurentf14db3c2017-12-08 14:20:36 -08008964 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8965 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8966 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8967 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8968 lStatus = BAD_TYPE;
8969 goto Exit;
8970 }
8971
Glenn Kasten74105912014-07-03 12:28:53 -07008972 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008973 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008974 // fast track: frame count is exactly the pipe depth
8975 frameCount = mPipeFramesP2;
8976 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008977 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008978 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008979 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8980 // or 20 ms if there is a fast capture
8981 // TODO This could be a roundupRatio inline, and const
8982 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8983 * sampleRate + mSampleRate - 1) / mSampleRate;
8984 // minimum number of notification periods is at least kMinNotifications,
8985 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8986 static const size_t kMinNotifications = 3;
8987 static const uint32_t kMinMs = 30;
8988 // TODO This could be a roundupRatio inline
8989 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8990 // TODO This could be a roundupRatio inline
8991 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8992 maxNotificationFrames;
8993 const size_t minFrameCount = maxNotificationFrames *
8994 max(kMinNotifications, minNotificationsByMs);
8995 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008996 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8997 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008998 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008999 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009000 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009001 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009002
Andy Hungc5007f82023-08-29 14:26:09 -07009003 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009004 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009005 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009006 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009007 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009008 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009009 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009010 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009011 }
Eric Laurent81784c32012-11-19 14:55:58 -08009012
Andy Hung8d31fd22023-06-26 19:20:57 -07009013 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009014 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009015 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009016 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009017 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009018
Glenn Kasten03003332013-08-06 15:40:54 -07009019 lStatus = track->initCheck();
9020 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009021 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009022 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009023 goto Exit;
9024 }
9025 mTracks.add(track);
9026
Eric Laurent05067782016-06-01 18:27:28 -07009027 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009028 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9029 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9030 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009031 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009032 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009033
9034 if (maxSharedAudioHistoryMs != 0) {
9035 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9036 }
Eric Laurent81784c32012-11-19 14:55:58 -08009037 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009038
Eric Laurent81784c32012-11-19 14:55:58 -08009039 lStatus = NO_ERROR;
9040
9041Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009042 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009043 return track;
9044}
9045
Andy Hungee58e4a2023-07-07 13:47:37 -07009046status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009047 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009048 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009049{
9050 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9051 sp<ThreadBase> strongMe = this;
9052 status_t status = NO_ERROR;
9053
9054 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009055 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009056 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009057 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009058 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009059 event, triggerSession,
9060 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009061 }
9062
9063 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009064 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009065 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009066 if (recordTrack->isInvalid()) {
9067 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009068 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9069 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009070 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009071 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009072 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009073 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9074 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009075 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009076 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009077 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009078 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009079 }
9080 return status;
9081 }
9082
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009083 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9084 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9085 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009086 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009087 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009088 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009089 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009090 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009091 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009092 if (recordTrack->isInvalid()) {
9093 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009094 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9095 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009096 // STARTING_2 forces destroy to call stopInput.
9097 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009098 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9099 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009100 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009101 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009102 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009103 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009104 // Someone else has changed state, let them take over,
9105 // leave mState in the new state.
9106 recordTrack->clearSyncStartEvent();
9107 return INVALID_OPERATION;
9108 }
9109 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009110 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009111 ALOGW("%s(%d): startInput failed, status %d",
9112 __func__, recordTrack->id(), status);
9113 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9114 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009115 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009116 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009117 return status;
9118 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009119 sendIoConfigEvent_l(
9120 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009121 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009122
9123 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9124
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009125 // Catch up with current buffer indices if thread is already running.
9126 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9127 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9128 // see previously buffered data before it called start(), but with greater risk of overrun.
9129
Andy Hung8d31fd22023-06-26 19:20:57 -07009130 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009131 if (!recordTrack->isDirect()) {
9132 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009133 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009134 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009135 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009136 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009137 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009138 return status;
9139 }
Eric Laurent81784c32012-11-19 14:55:58 -08009140}
9141
Andy Hungee58e4a2023-07-07 13:47:37 -07009142void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009143{
Andy Hungee58e4a2023-07-07 13:47:37 -07009144 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009145
9146 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009147 sp<IAfTrackBase> ptr =
9148 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9149 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009150 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009151 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009152 }
Eric Laurent81784c32012-11-19 14:55:58 -08009153 }
9154}
9155
Andy Hungee58e4a2023-07-07 13:47:37 -07009156bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009157 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009158 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009159 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009160 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009161 return false;
9162 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009163 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009164 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009165
Andy Hungabfab202019-03-07 19:45:54 -08009166 // NOTE: Waiting here is important to keep stop synchronous.
9167 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009168 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009169 mWaitWorkCV.notify_all(); // signal thread to stop
9170 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009171 }
Andy Hungce685402018-10-05 17:23:27 -07009172
Andy Hung8d31fd22023-06-26 19:20:57 -07009173 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009174 ALOGV("Record stopped OK");
9175 return true;
9176 }
Andy Hungce685402018-10-05 17:23:27 -07009177
9178 // don't handle anything - we've been invalidated or restarted and in a different state
9179 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009180 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009181 return false;
9182}
9183
Andy Hungee58e4a2023-07-07 13:47:37 -07009184bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009185{
9186 return false;
9187}
9188
Andy Hungee58e4a2023-07-07 13:47:37 -07009189status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009190{
9191#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9192 if (!isValidSyncEvent(event)) {
9193 return BAD_VALUE;
9194 }
9195
Glenn Kastend848eb42016-03-08 13:42:11 -08009196 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009197 status_t ret = NAME_NOT_FOUND;
9198
Andy Hung972bec12023-08-31 16:13:39 -07009199 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009200
9201 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009202 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009203 if (eventSession == track->sessionId()) {
9204 (void) track->setSyncEvent(event);
9205 ret = NO_ERROR;
9206 }
9207 }
9208 return ret;
9209#else
9210 return BAD_VALUE;
9211#endif
9212}
9213
Andy Hungee58e4a2023-07-07 13:47:37 -07009214status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009215 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009216{
9217 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009218 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009219 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009220 return NO_INIT;
9221 }
jiabin9ff780e2018-03-19 18:19:52 -07009222 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9223 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009224}
9225
Andy Hungee58e4a2023-07-07 13:47:37 -07009226status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009227 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009228{
Paul McLean12340082019-03-19 09:35:05 -06009229 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009230 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009231 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009232 return NO_INIT;
9233 }
Paul McLean12340082019-03-19 09:35:05 -06009234 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009235}
9236
Andy Hungee58e4a2023-07-07 13:47:37 -07009237status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009238{
Paul McLean12340082019-03-19 09:35:05 -06009239 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009240 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009241 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009242 return NO_INIT;
9243 }
Paul McLean12340082019-03-19 09:35:05 -06009244 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009245}
9246
Andy Hungee58e4a2023-07-07 13:47:37 -07009247status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009248 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9249 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009250 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009251 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9252}
9253
Andy Hungee58e4a2023-07-07 13:47:37 -07009254status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009255 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9256 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009257
Eric Laurentec376dc2021-04-08 20:41:22 +02009258 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9259 return BAD_VALUE;
9260 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009261
9262 if (sharedAudioStartMs < 0
9263 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009264 return BAD_VALUE;
9265 }
9266
Eric Laurent2407ce32021-04-26 14:56:03 +02009267 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9268 // As we cannot detect more than one wraparound, only accept values up current write position
9269 // after one wraparound
9270 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9271 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009272 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009273 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9274 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009275 // Bring the start frame position within the input buffer to match the documented
9276 // "best effort" behavior of the API.
9277 if (sharedOffset < 0) {
9278 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009279 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009280 sharedAudioStartFrames =
9281 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009282 }
9283
Eric Laurentec376dc2021-04-08 20:41:22 +02009284 mSharedAudioPackageName = sharedAudioPackageName;
9285 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009286 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009287 } else {
9288 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009289 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009290 }
9291 return NO_ERROR;
9292}
9293
Andy Hungee58e4a2023-07-07 13:47:37 -07009294void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009295 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9296 mSharedAudioStartFrames = -1;
9297 mSharedAudioPackageName = "";
9298}
9299
Andy Hungee58e4a2023-07-07 13:47:37 -07009300ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009301{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009302 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009303 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009304 }
9305 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009306 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009307 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009308 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009309 }
9310 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009311 MetadataUpdate change;
9312 change.recordMetadataUpdate = metadata.tracks;
9313 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009314}
9315
Andy Hungc5007f82023-08-29 14:26:09 -07009316// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009317void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009318{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009319 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009320 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009321
Eric Laurent81784c32012-11-19 14:55:58 -08009322 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009323 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009324 removeTrack_l(track);
9325 }
9326}
9327
Andy Hungee58e4a2023-07-07 13:47:37 -07009328void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009329{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009330 String8 result;
9331 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009332 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009333
Eric Laurent81784c32012-11-19 14:55:58 -08009334 mTracks.remove(track);
9335 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009336 if (track->isFastTrack()) {
9337 ALOG_ASSERT(!mFastTrackAvail);
9338 mFastTrackAvail = true;
9339 }
Eric Laurent81784c32012-11-19 14:55:58 -08009340}
9341
Andy Hungee58e4a2023-07-07 13:47:37 -07009342void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009343{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009344 AudioStreamIn *input = mInput;
9345 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9346 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009347 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009348 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009349 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009350 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009351 }
Andy Hungbfa64962017-06-12 14:43:19 -07009352
9353 if (input != nullptr) {
9354 dprintf(fd, " Hal stream dump:\n");
9355 (void)input->stream->dump(fd);
9356 }
9357
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009358 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009359 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009360
Glenn Kasten2f90c512015-12-02 11:40:09 -08009361 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9362 // while we are dumping it. It may be inconsistent, but it won't mutate!
9363 // This is a large object so we place it on the heap.
9364 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009365 const std::unique_ptr<FastCaptureDumpState> copy =
9366 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009367 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009368}
9369
Andy Hungee58e4a2023-07-07 13:47:37 -07009370void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009371{
Eric Laurent81784c32012-11-19 14:55:58 -08009372 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009373 size_t numtracks = mTracks.size();
9374 size_t numactive = mActiveTracks.size();
9375 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009376 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009377 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009378 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009379 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009380 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009381 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009382 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009383 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009384 if (track != 0) {
9385 bool active = mActiveTracks.indexOf(track) >= 0;
9386 if (active) {
9387 numactiveseen++;
9388 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009389 result.append(prefix);
9390 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009391 }
Eric Laurent81784c32012-11-19 14:55:58 -08009392 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009393 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009394 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009395 }
9396
Marco Nelissenb2208842014-02-07 14:00:50 -08009397 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009398 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009399 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009400 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009401 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009402 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009403 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009404 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009405 result.append(prefix);
9406 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009407 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009408 }
Eric Laurent81784c32012-11-19 14:55:58 -08009409
9410 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009411 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009412}
9413
Andy Hungee58e4a2023-07-07 13:47:37 -07009414void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009415{
Andy Hung972bec12023-08-31 16:13:39 -07009416 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009417 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009418 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009419 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009420 track->setSilenced(silenced);
9421 }
9422 }
9423}
Andy Hung73c02e42015-03-29 01:13:58 -07009424
Andy Hung8d31fd22023-06-26 19:20:57 -07009425void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009426{
Andy Hung87c693c2023-07-06 20:56:16 -07009427 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009428 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009429 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009430 const int32_t rear = recordThread->mRsmpInRear;
9431 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009432 if (mRecordTrack->startFrames() >= 0) {
9433 int32_t startFrames = mRecordTrack->startFrames();
9434 // Accept a recent wraparound of mRsmpInRear
9435 if (startFrames <= rear) {
9436 deltaFrames = rear - startFrames;
9437 } else {
9438 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009439 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009440 // start frame cannot be further in the past than start of resampling buffer
9441 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9442 deltaFrames = recordThread->mRsmpInFrames;
9443 }
9444 }
9445 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009446}
9447
Andy Hung8d31fd22023-06-26 19:20:57 -07009448void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009449 size_t *framesAvailable, bool *hasOverrun)
9450{
Andy Hung87c693c2023-07-06 20:56:16 -07009451 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009452 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009453 const int32_t rear = recordThread->mRsmpInRear;
9454 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009455 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009456
9457 size_t framesIn;
9458 bool overrun = false;
9459 if (filled < 0) {
9460 // should not happen, but treat like a massive overrun and re-sync
9461 framesIn = 0;
9462 mRsmpInFront = rear;
9463 overrun = true;
9464 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9465 framesIn = (size_t) filled;
9466 } else {
9467 // client is not keeping up with server, but give it latest data
9468 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009469 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9470 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009471 overrun = true;
9472 }
9473 if (framesAvailable != NULL) {
9474 *framesAvailable = framesIn;
9475 }
9476 if (hasOverrun != NULL) {
9477 *hasOverrun = overrun;
9478 }
9479}
9480
Eric Laurent81784c32012-11-19 14:55:58 -08009481// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009482status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009483 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009484{
Andy Hung87c693c2023-07-06 20:56:16 -07009485 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009486 if (threadBase == 0) {
9487 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009488 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009489 return NOT_ENOUGH_DATA;
9490 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009491 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009492 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009493 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009494 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009495 // FIXME should not be P2 (don't want to increase latency)
9496 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009497 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009498 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009499
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009500 front &= recordThread->mRsmpInFramesP2 - 1;
9501 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009502 if (part1 > (size_t) filled) {
9503 part1 = filled;
9504 }
9505 size_t ask = buffer->frameCount;
9506 ALOG_ASSERT(ask > 0);
9507 if (part1 > ask) {
9508 part1 = ask;
9509 }
9510 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009511 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009512 buffer->raw = NULL;
9513 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009514 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009515 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009516 }
9517
Andy Hung57446612015-04-19 23:56:46 -07009518 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009519 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009520 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009521 return NO_ERROR;
9522}
9523
9524// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009525void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009526 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009527{
Hongwei Wang95e37682019-04-12 11:13:36 -07009528 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009529 if (stepCount == 0) {
9530 return;
9531 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009532 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009533 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009534 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009535 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009536 buffer->frameCount = 0;
9537}
9538
Andy Hungee58e4a2023-07-07 13:47:37 -07009539void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009540{
Andy Hung972bec12023-08-31 16:13:39 -07009541 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009542 checkBtNrec_l();
9543}
9544
Andy Hungee58e4a2023-07-07 13:47:37 -07009545void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009546{
9547 // disable AEC and NS if the device is a BT SCO headset supporting those
9548 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009549 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009550 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009551 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9552 for (size_t i = 0; i < mEffectChains.size(); i++) {
9553 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9554 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9555 }
9556 }
9557}
9558
Andy Hung97a893e2015-03-29 01:03:07 -07009559
Andy Hungee58e4a2023-07-07 13:47:37 -07009560bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009561 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009562{
9563 bool reconfig = false;
9564
Eric Laurent10351942014-05-08 18:49:52 -07009565 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009566
Eric Laurent10351942014-05-08 18:49:52 -07009567 audio_format_t reqFormat = mFormat;
9568 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009569 // 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 +08009570 [[maybe_unused]] audio_channel_mask_t channelMask =
9571 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009572
9573 AudioParameter param = AudioParameter(keyValuePair);
9574 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009575
9576 // scope for AutoPark extends to end of method
9577 AutoPark<FastCapture> park(mFastCapture);
9578
Eric Laurent10351942014-05-08 18:49:52 -07009579 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9580 // channel count change can be requested. Do we mandate the first client defines the
9581 // HAL sampling rate and channel count or do we allow changes on the fly?
9582 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9583 samplingRate = value;
9584 reconfig = true;
9585 }
9586 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009587 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009588 status = BAD_VALUE;
9589 } else {
9590 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009591 reconfig = true;
9592 }
Eric Laurent10351942014-05-08 18:49:52 -07009593 }
9594 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9595 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009596 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009597 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009598 status = BAD_VALUE;
9599 } else {
9600 channelMask = mask;
9601 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009602 }
Eric Laurent10351942014-05-08 18:49:52 -07009603 }
9604 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9605 // do not accept frame count changes if tracks are open as the track buffer
9606 // size depends on frame count and correct behavior would not be guaranteed
9607 // if frame count is changed after track creation
9608 if (mActiveTracks.size() > 0) {
9609 status = INVALID_OPERATION;
9610 } else {
9611 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009612 }
Eric Laurent10351942014-05-08 18:49:52 -07009613 }
9614 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009615 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009616 }
9617 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9618 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009619 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009620 }
Glenn Kastene198c362013-08-13 09:13:36 -07009621
Eric Laurent10351942014-05-08 18:49:52 -07009622 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009623 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009624 if (status == INVALID_OPERATION) {
9625 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009626 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009627 }
9628 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009629 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009630 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9631 if (mInput->stream->getAudioProperties(&config) == OK &&
9632 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9633 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009634 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009635 status = NO_ERROR;
9636 }
Eric Laurent81784c32012-11-19 14:55:58 -08009637 }
Eric Laurent10351942014-05-08 18:49:52 -07009638 if (status == NO_ERROR) {
9639 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009640 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009641 }
9642 }
Eric Laurent81784c32012-11-19 14:55:58 -08009643 }
Eric Laurent10351942014-05-08 18:49:52 -07009644
Eric Laurent81784c32012-11-19 14:55:58 -08009645 return reconfig;
9646}
9647
Andy Hungee58e4a2023-07-07 13:47:37 -07009648String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009649{
Andy Hung972bec12023-08-31 16:13:39 -07009650 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009651 if (initCheck() == NO_ERROR) {
9652 String8 out_s8;
9653 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9654 return out_s8;
9655 }
Eric Laurent81784c32012-11-19 14:55:58 -08009656 }
Andy Hung920f6572022-10-06 12:09:49 -07009657 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009658}
9659
Andy Hungab65b182023-09-06 19:41:47 -07009660void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009661 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009662 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009663 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009664 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009665 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009666 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009667 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9668 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009669 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009670 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009671 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009672 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009673 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009674 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009675 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009676 break;
9677 }
Andy Hungab65b182023-09-06 19:41:47 -07009678 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009679}
9680
Andy Hungee58e4a2023-07-07 13:47:37 -07009681void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009682{
Dean Wheatley6c009512023-10-23 09:34:14 +11009683 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9684 mSampleRate = audioConfig.sample_rate;
9685 mChannelMask = audioConfig.channel_mask;
9686 if (!audio_is_input_channel(mChannelMask)) {
9687 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9688 }
9689
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009690 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009691
9692 // Get actual HAL format.
9693 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9694 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9695 // Get format from the shim, which will be different than the HAL format
9696 // if recording compressed audio from IEC61937 wrapped sources.
9697 mFormat = audioConfig.format;
9698 if (!audio_is_valid_format(mFormat)) {
9699 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9700 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009701 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009702 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9703 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009704 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009705 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009706 ALOGI("HAL format %#x is not linear pcm", mFormat);
9707 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009708 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009709 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9710 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009711 result = mInput->stream->getBufferSize(&mBufferSize);
9712 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009713 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009714 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9715 "mBufferSize=%zu, mFrameCount=%zu",
9716 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009717
Eric Laurentec376dc2021-04-08 20:41:22 +02009718 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9719 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009720 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009721
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009722 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9723 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009724
9725 audio_input_flags_t flags = mInput->flags;
9726 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9727 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009728 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009729 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9730 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9731 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9732 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9733 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9734 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009735}
9736
Andy Hungee58e4a2023-07-07 13:47:37 -07009737uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009738{
Andy Hung972bec12023-08-31 16:13:39 -07009739 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009740 uint32_t result;
9741 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9742 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009743 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009744 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009745}
9746
Andy Hungee58e4a2023-07-07 13:47:37 -07009747KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009748{
Glenn Kastend848eb42016-03-08 13:42:11 -08009749 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009750 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009751 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009752 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009753 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009754 if (ids.indexOfKey(sessionId) < 0) {
9755 ids.add(sessionId, true);
9756 }
9757 }
9758 return ids;
9759}
9760
Andy Hungee58e4a2023-07-07 13:47:37 -07009761AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009762{
Andy Hung972bec12023-08-31 16:13:39 -07009763 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009764 AudioStreamIn *input = mInput;
9765 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009766 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009767 return input;
9768}
9769
Andy Hungc5007f82023-08-29 14:26:09 -07009770// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009771sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009772{
9773 if (mInput == NULL) {
9774 return NULL;
9775 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009776 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009777}
9778
Andy Hungee58e4a2023-07-07 13:47:37 -07009779status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009780{
Eric Laurent81784c32012-11-19 14:55:58 -08009781 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009782 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009783 chain->setInBuffer(NULL);
9784 chain->setOutBuffer(NULL);
9785
9786 checkSuspendOnAddEffectChain_l(chain);
9787
Eric Laurent1b928682014-10-02 19:41:47 -07009788 // make sure enabled pre processing effects state is communicated to the HAL as we
9789 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009790 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009791
Eric Laurent81784c32012-11-19 14:55:58 -08009792 mEffectChains.add(chain);
9793
9794 return NO_ERROR;
9795}
9796
Andy Hungee58e4a2023-07-07 13:47:37 -07009797size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009798{
9799 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009800
9801 for (size_t i = 0; i < mEffectChains.size(); i++) {
9802 if (chain == mEffectChains[i]) {
9803 mEffectChains.removeAt(i);
9804 break;
9805 }
Eric Laurent81784c32012-11-19 14:55:58 -08009806 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009807 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009808}
9809
Andy Hungee58e4a2023-07-07 13:47:37 -07009810status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009811 audio_patch_handle_t *handle)
9812{
9813 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009814
9815 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009816 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009817 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009818 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009819 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009820 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009821 }
9822
Eric Laurentd8365c52017-07-16 15:27:05 -07009823 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009824
9825 // store new source and send to effects
9826 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9827 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009828 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009829 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009830 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009831 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009832
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009833 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009834 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9835 status = hwDevice->createAudioPatch(patch->num_sources,
9836 patch->sources,
9837 patch->num_sinks,
9838 patch->sinks,
9839 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009840 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009841 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9842 patch->sinks[0].ext.mix.usecase.source,
9843 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009844 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009845 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009846
jiabinc52b1ff2019-10-31 17:20:42 -07009847 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009848 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009849 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009850 }
Eric Laurent296fb132015-05-01 11:38:42 -07009851
Andy Hungc2b11cb2020-04-22 09:04:01 -07009852 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009853 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009854 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009855 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009856 // also dispatch to active AudioRecords
9857 for (const auto &track : mActiveTracks) {
9858 track->logEndInterval();
9859 track->logBeginInterval(pathSourcesAsString);
9860 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009861 // Force meteadata update after a route change
9862 mActiveTracks.setHasChanged();
9863
Eric Laurent1c333e22014-05-20 10:48:17 -07009864 return status;
9865}
9866
Andy Hungee58e4a2023-07-07 13:47:37 -07009867status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009868{
9869 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009870
jiabinc52b1ff2019-10-31 17:20:42 -07009871 mPatch = audio_patch{};
9872 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009873
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009874 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009875 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9876 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009877 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009878 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009879 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009880 // Force meteadata update after a route change
9881 mActiveTracks.setHasChanged();
9882
Eric Laurent1c333e22014-05-20 10:48:17 -07009883 return status;
9884}
9885
Andy Hungee58e4a2023-07-07 13:47:37 -07009886void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009887{
Andy Hung972bec12023-08-31 16:13:39 -07009888 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009889 mOutDevices = outDevices;
9890 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9891 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009892 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009893 }
9894}
9895
Andy Hungee58e4a2023-07-07 13:47:37 -07009896int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009897{
9898 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009899 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009900 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009901 int32_t oldestFront = mRsmpInRear;
9902 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009903 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009904 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009905 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009906 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009907 if (filled > maxFilled) {
9908 oldestFront = front;
9909 maxFilled = filled;
9910 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009911 }
Andy Hung920f6572022-10-06 12:09:49 -07009912 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009913 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9914 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009915 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009916}
9917
Andy Hungee58e4a2023-07-07 13:47:37 -07009918void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009919{
9920 if (offset == 0) {
9921 return;
9922 }
9923 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009924 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009925 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009926 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009927 }
9928}
9929
Andy Hungee58e4a2023-07-07 13:47:37 -07009930void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009931{
9932 // This is the formula for calculating the temporary buffer size.
9933 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9934 // 1 full output buffer, regardless of the alignment of the available input.
9935 // The value is somewhat arbitrary, and could probably be even larger.
9936 // A larger value should allow more old data to be read after a track calls start(),
9937 // without increasing latency.
9938 //
9939 // Note this is independent of the maximum downsampling ratio permitted for capture.
9940 size_t minRsmpInFrames = mFrameCount * 7;
9941
9942 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9943 // capture history available to another client using the same session ID:
9944 // dimension the resampler input buffer accordingly.
9945
9946 // Get oldest client read position: getOldestFront_l() must be called before altering
9947 // mRsmpInRear, or mRsmpInFrames
9948 int32_t previousFront = getOldestFront_l();
9949 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9950 int32_t previousRear = mRsmpInRear;
9951 mRsmpInRear = 0;
9952
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009953 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009954 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009955 "resizeInputBuffer_l() called with invalid max shared history %d",
9956 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009957 if (maxSharedAudioHistoryMs != 0) {
9958 // resizeInputBuffer_l should never be called with a non zero shared history if the
9959 // buffer was not already allocated
9960 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9961 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9962 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9963 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009964 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009965 return;
9966 }
9967 mRsmpInFrames = rsmpInFrames;
9968 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009969 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009970 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9971 // initialized
9972 if (mRsmpInFrames < minRsmpInFrames) {
9973 mRsmpInFrames = minRsmpInFrames;
9974 }
9975 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9976
9977 // TODO optimize audio capture buffer sizes ...
9978 // Here we calculate the size of the sliding buffer used as a source
9979 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9980 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9981 // be better to have it derived from the pipe depth in the long term.
9982 // The current value is higher than necessary. However it should not add to latency.
9983
9984 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9985 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9986
9987 void *rsmpInBuffer;
9988 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9989 // if posix_memalign fails, will segv here.
9990 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9991
9992 // Copy audio history if any from old buffer before freeing it
9993 if (previousRear != 0) {
9994 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9995 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9996
9997 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9998 previousFront &= previousRsmpInFramesP2 - 1;
9999 size_t part1 = previousRsmpInFramesP2 - previousFront;
10000 if (part1 > (size_t) unread) {
10001 part1 = unread;
10002 }
10003 if (part1 != 0) {
10004 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10005 part1 * mFrameSize);
10006 mRsmpInRear = part1;
10007 part1 = unread - part1;
10008 if (part1 != 0) {
10009 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10010 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10011 mRsmpInRear += part1;
10012 }
10013 }
10014 // Update front for all clients according to new rear
10015 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10016 } else {
10017 mRsmpInRear = 0;
10018 }
10019 free(mRsmpInBuffer);
10020 mRsmpInBuffer = rsmpInBuffer;
10021}
10022
Andy Hungee58e4a2023-07-07 13:47:37 -070010023void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010024{
Andy Hung972bec12023-08-31 16:13:39 -070010025 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010026 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010027 if (record->getSource()) {
10028 mSource = record->getSource();
10029 }
Eric Laurent83b88082014-06-20 18:31:16 -070010030}
10031
Andy Hungee58e4a2023-07-07 13:47:37 -070010032void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010033{
Andy Hung972bec12023-08-31 16:13:39 -070010034 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010035 if (mSource == record->getSource()) {
10036 mSource = mInput;
10037 }
Eric Laurent83b88082014-06-20 18:31:16 -070010038 destroyTrack_l(record);
10039}
10040
Andy Hungee58e4a2023-07-07 13:47:37 -070010041void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010042{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010043 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010044 config->role = AUDIO_PORT_ROLE_SINK;
10045 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10046 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010047 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10048 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10049 config->flags.input = mInput->flags;
10050 }
Eric Laurent83b88082014-06-20 18:31:16 -070010051}
Eric Laurent1c333e22014-05-20 10:48:17 -070010052
Eric Laurent6acd1d42017-01-04 14:23:29 -080010053// ----------------------------------------------------------------------------
10054// Mmap
10055// ----------------------------------------------------------------------------
10056
Andy Hung7aa7d102023-07-07 15:58:48 -070010057// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10058// MmapPlaybackThread or MmapCaptureThread instance.
10059class MmapThreadHandle : public MmapStreamInterface {
10060public:
10061 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10062 ~MmapThreadHandle() override;
10063
10064 // MmapStreamInterface virtuals
10065 status_t createMmapBuffer(int32_t minSizeFrames,
10066 struct audio_mmap_buffer_info* info) final;
10067 status_t getMmapPosition(struct audio_mmap_position* position) final;
10068 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10069 status_t start(const AudioClient& client,
10070 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10071 status_t stop(audio_port_handle_t handle) final;
10072 status_t standby() final;
10073 status_t reportData(const void* buffer, size_t frameCount) final;
10074private:
10075 const sp<IAfMmapThread> mThread;
10076};
10077
10078/* static */
10079sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10080 const sp<IAfMmapThread>& mmapThread) {
10081 return sp<MmapThreadHandle>::make(mmapThread);
10082}
10083
10084MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010085 : mThread(thread)
10086{
Phil Burk9fabbf82017-08-03 12:02:00 -070010087 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010088}
10089
Andy Hung7aa7d102023-07-07 15:58:48 -070010090// MmapStreamInterface could be directly implemented by MmapThread excepting this
10091// special handling on adapter dtor.
10092MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010093{
Phil Burk9fabbf82017-08-03 12:02:00 -070010094 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010095}
10096
Andy Hung7aa7d102023-07-07 15:58:48 -070010097status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010098 struct audio_mmap_buffer_info *info)
10099{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010100 return mThread->createMmapBuffer(minSizeFrames, info);
10101}
10102
Andy Hung7aa7d102023-07-07 15:58:48 -070010103status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010104{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010105 return mThread->getMmapPosition(position);
10106}
10107
Andy Hung7aa7d102023-07-07 15:58:48 -070010108status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010109 int64_t *timeNanos) {
10110 return mThread->getExternalPosition(position, timeNanos);
10111}
10112
Andy Hung7aa7d102023-07-07 15:58:48 -070010113status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010114 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010115{
jiabind1f1cb62020-03-24 11:57:57 -070010116 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010117}
10118
Andy Hung7aa7d102023-07-07 15:58:48 -070010119status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010120{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010121 return mThread->stop(handle);
10122}
10123
Andy Hung7aa7d102023-07-07 15:58:48 -070010124status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010125{
Eric Laurent18b57012017-02-13 16:23:52 -080010126 return mThread->standby();
10127}
10128
Andy Hung7aa7d102023-07-07 15:58:48 -070010129status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10130{
jiabinfc791ee2023-02-15 19:43:40 +000010131 return mThread->reportData(buffer, frameCount);
10132}
10133
Eric Laurent6acd1d42017-01-04 14:23:29 -080010134
Andy Hungee58e4a2023-07-07 13:47:37 -070010135MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010136 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010137 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010138 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010139 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010140 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010141 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010142 mActiveTracks(&this->mLocalLog),
10143 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10144 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010145{
Eric Laurent18b57012017-02-13 16:23:52 -080010146 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010147 readHalParameters_l();
10148}
10149
Andy Hungee58e4a2023-07-07 13:47:37 -070010150void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010151{
10152 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10153}
10154
Andy Hungee58e4a2023-07-07 13:47:37 -070010155void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156{
Andy Hung8d31fd22023-06-26 19:20:57 -070010157 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010158 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010159 {
Andy Hung972bec12023-08-31 16:13:39 -070010160 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010161 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010162 activeTracks.add(t);
10163 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010164 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010165 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010166 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167 stop(t->portId());
10168 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010169 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010170 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010171 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010172 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010173 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174 }
10175}
10176
10177
Andy Hung8d672e02023-09-15 18:19:28 -070010178void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010179 audio_stream_type_t streamType __unused,
10180 audio_session_t sessionId,
10181 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010182 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010183 audio_port_handle_t portId)
10184{
10185 mAttr = *attr;
10186 mSessionId = sessionId;
10187 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010188 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010189 mPortId = portId;
10190}
10191
Andy Hungee58e4a2023-07-07 13:47:37 -070010192status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010193 struct audio_mmap_buffer_info *info)
10194{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010195 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196 if (mHalStream == 0) {
10197 return NO_INIT;
10198 }
Eric Laurent18b57012017-02-13 16:23:52 -080010199 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010200 return mHalStream->createMmapBuffer(minSizeFrames, info);
10201}
10202
Andy Hungee58e4a2023-07-07 13:47:37 -070010203status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010204{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010205 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010206 if (mHalStream == 0) {
10207 return NO_INIT;
10208 }
10209 return mHalStream->getMmapPosition(position);
10210}
10211
Andy Hungee58e4a2023-07-07 13:47:37 -070010212status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010213{
Eric Laurentdda206a2022-07-08 17:28:35 +020010214 // The HAL must receive track metadata before starting the stream
10215 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010216 status_t ret = mHalStream->start();
10217 if (ret != NO_ERROR) {
10218 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10219 return ret;
10220 }
Andy Hungcf10d742020-04-28 15:38:24 -070010221 if (mStandby) {
10222 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010223 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010224 mStandby = false;
10225 }
Eric Laurent331679c2018-04-16 17:03:16 -070010226 return NO_ERROR;
10227}
10228
Andy Hungee58e4a2023-07-07 13:47:37 -070010229status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010230 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231 audio_port_handle_t *handle)
10232{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010233 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010234 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010235 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010236 if (mHalStream == 0) {
10237 return NO_INIT;
10238 }
10239
10240 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010241
Eric Laurentdda206a2022-07-08 17:28:35 +020010242 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010243 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010244 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010245 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010246 }
10247
10248 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10249
10250 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010251 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010252 client.attributionSource);
10253
Andy Hung3f49ebb2023-09-19 14:48:41 -070010254 const auto localSessionId = mSessionId;
10255 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010256 if (isOutput()) {
10257 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10258 config.sample_rate = mSampleRate;
10259 config.channel_mask = mChannelMask;
10260 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010261 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010262 audio_output_flags_t flags =
10263 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010264 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010265 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010266 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010267 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010268 mutex().unlock();
10269 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10270 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010271 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010272 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010273 &config,
10274 flags,
10275 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010276 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010277 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010278 &isSpatialized,
10279 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010280 mutex().lock();
10281 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010282 ALOGD_IF(!secondaryOutputs.empty(),
10283 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010284 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010285 audio_config_base_t config;
10286 config.sample_rate = mSampleRate;
10287 config.channel_mask = mChannelMask;
10288 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010289 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010290 mutex().unlock();
10291 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010292 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010293 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010294 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010295 &config,
10296 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10297 &deviceId,
10298 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010299 mutex().lock();
10300 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010301 }
10302 // APM should not chose a different input or output stream for the same set of attributes
10303 // and audo configuration
10304 if (ret != NO_ERROR || io != mId) {
10305 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10306 __FUNCTION__, ret, io, mId);
10307 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010308 }
10309
10310 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010311 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010312 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010313 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 } else {
jiabin09609032022-06-15 19:26:01 +000010315 {
10316 // Add the track record before starting input so that the silent status for the
10317 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010318 setClientSilencedState_l(portId, false /*silenced*/);
10319 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010320 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010321 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010322 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010323 }
10324
10325 // abort if start is rejected by audio policy manager
10326 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010327 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010328 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010329 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010330 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010331 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010333 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010334 }
Andy Hungc5007f82023-08-29 14:26:09 -070010335 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010336 } else {
10337 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338 }
jiabin09609032022-06-15 19:26:01 +000010339 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340 return PERMISSION_DENIED;
10341 }
10342
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010343 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010344 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10345 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010346 mChannelMask, mSessionId, isOutput(),
10347 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010348 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010349 if (!isOutput()) {
10350 track->setSilenced_l(isClientSilenced_l(portId));
10351 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352
Eric Laurent4eb58f12018-12-07 16:41:02 -080010353 if (isOutput()) {
10354 // force volume update when a new track is added
10355 mHalVolFloat = -1.0f;
10356 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010357 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010358 if (t->isSilenced_l()
10359 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010360 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010361 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010362 }
10363 }
10364
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010366 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010367 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010368 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369 chain->incTrackCnt();
10370 chain->incActiveTrackCnt();
10371 }
10372
Andy Hungc2b11cb2020-04-22 09:04:01 -070010373 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010375
10376 if (mActiveTracks.size() == 1) {
10377 ret = exitStandby_l();
10378 }
10379
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380 broadcast_l();
10381
Eric Laurentdda206a2022-07-08 17:28:35 +020010382 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010383
Eric Laurentdda206a2022-07-08 17:28:35 +020010384 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385}
10386
Andy Hungee58e4a2023-07-07 13:47:37 -070010387status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010389 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010390 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010391
10392 if (mHalStream == 0) {
10393 return NO_INIT;
10394 }
10395
Eric Laurenta54f1282017-07-01 19:39:32 -070010396 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010397 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010398 return NO_ERROR;
10399 }
10400
Andy Hung8d31fd22023-06-26 19:20:57 -070010401 sp<IAfMmapTrack> track;
10402 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010403 if (handle == t->portId()) {
10404 track = t;
10405 break;
10406 }
10407 }
10408 if (track == 0) {
10409 return BAD_VALUE;
10410 }
10411
10412 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010413 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414
Andy Hungc5007f82023-08-29 14:26:09 -070010415 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010416 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010417 AudioSystem::stopOutput(track->portId());
10418 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010419 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010420 AudioSystem::stopInput(track->portId());
10421 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422 }
Andy Hungc5007f82023-08-29 14:26:09 -070010423 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010424
Andy Hung116bc262023-06-20 18:56:17 -070010425 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426 if (chain != 0) {
10427 chain->decActiveTrackCnt();
10428 chain->decTrackCnt();
10429 }
10430
Eric Laurentdda206a2022-07-08 17:28:35 +020010431 if (mActiveTracks.isEmpty()) {
10432 mHalStream->stop();
10433 }
10434
Eric Laurent6acd1d42017-01-04 14:23:29 -080010435 broadcast_l();
10436
Eric Laurent6acd1d42017-01-04 14:23:29 -080010437 return NO_ERROR;
10438}
10439
Andy Hungee58e4a2023-07-07 13:47:37 -070010440status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010441NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010442{
10443 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010444 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010445
10446 if (mHalStream == 0) {
10447 return NO_INIT;
10448 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010449 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010450 return INVALID_OPERATION;
10451 }
10452 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010453 if (!mStandby) {
10454 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010455 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010456 mStandby = true;
10457 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010458 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010459 return NO_ERROR;
10460}
10461
Andy Hungee58e4a2023-07-07 13:47:37 -070010462status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010463 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10464 return INVALID_OPERATION;
10465}
10466
Andy Hungee58e4a2023-07-07 13:47:37 -070010467void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468{
10469 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10470 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10471 mFormat = mHALFormat;
10472 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10473 result = mHalStream->getFrameSize(&mFrameSize);
10474 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010475 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10476 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010477 result = mHalStream->getBufferSize(&mBufferSize);
10478 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10479 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010480
Andy Hungcf10d742020-04-28 15:38:24 -070010481 // TODO: make a readHalParameters call?
10482 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010483 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010484 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010485 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10486 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10487 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10488 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10489 /*
10490 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10491 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10492 (int32_t)mHapticChannelMask)
10493 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10494 (int32_t)mHapticChannelCount)
10495 */
10496 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010497 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010498 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10499 (int32_t)mFrameCount) // sic - added HAL
10500 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501}
10502
Andy Hungee58e4a2023-07-07 13:47:37 -070010503bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010504{
Andy Hungab65b182023-09-06 19:41:47 -070010505 {
10506 audio_utils::unique_lock _l(mutex());
10507 checkSilentMode_l();
10508 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010509
10510 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10511
10512 while (!exitPending())
10513 {
Andy Hung116bc262023-06-20 18:56:17 -070010514 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010515
Andy Hung13850be2019-03-14 11:33:09 -070010516 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010517 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010518
Eric Laurent6acd1d42017-01-04 14:23:29 -080010519 if (mSignalPending) {
10520 // A signal was raised while we were unlocked
10521 mSignalPending = false;
10522 } else {
10523 if (mConfigEvents.isEmpty()) {
10524 // we're about to wait, flush the binder command buffer
10525 IPCThreadState::self()->flushCommands();
10526
10527 if (exitPending()) {
10528 break;
10529 }
10530
Eric Laurent6acd1d42017-01-04 14:23:29 -080010531 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010532 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010533 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010534 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010535
10536 checkSilentMode_l();
10537
10538 continue;
10539 }
10540 }
10541
10542 processConfigEvents_l();
10543
10544 processVolume_l();
10545
10546 checkInvalidTracks_l();
10547
Andy Hungab65b182023-09-06 19:41:47 -070010548 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010549
Kevin Rocard069c2712018-03-29 19:09:14 -070010550 updateMetadata_l();
10551
Eric Laurent6acd1d42017-01-04 14:23:29 -080010552 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010553 } // release Thread lock
10554
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010556 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010557 }
Andy Hung13850be2019-03-14 11:33:09 -070010558
10559 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560 unlockEffectChains(effectChains);
10561 // Effect chains will be actually deleted here if they were removed from
10562 // mEffectChains list during mixing or effects processing
10563 }
10564
10565 threadLoop_exit();
10566
10567 if (!mStandby) {
10568 threadLoop_standby();
10569 mStandby = true;
10570 }
10571
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572 ALOGV("Thread %p type %d exiting", this, mType);
10573 return false;
10574}
10575
Andy Hungc5007f82023-08-29 14:26:09 -070010576// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010577bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578 status_t& status)
10579{
10580 AudioParameter param = AudioParameter(keyValuePair);
10581 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010582 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010583 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010584 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010586 if (sendToHal) {
10587 status = mHalStream->setParameters(keyValuePair);
10588 } else {
10589 status = NO_ERROR;
10590 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591
10592 return false;
10593}
10594
Andy Hungee58e4a2023-07-07 13:47:37 -070010595String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010596{
Andy Hung972bec12023-08-31 16:13:39 -070010597 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010598 String8 out_s8;
10599 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10600 return out_s8;
10601 }
Andy Hung920f6572022-10-06 12:09:49 -070010602 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603}
10604
Andy Hungab65b182023-09-06 19:41:47 -070010605void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010606 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010607 sp<AudioIoDescriptor> desc;
10608 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010609 switch (event) {
10610 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010611 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010612 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010613 isInput = true;
10614 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010616 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010617 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010618 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10619 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010620 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621 case AUDIO_INPUT_CLOSED:
10622 case AUDIO_OUTPUT_CLOSED:
10623 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010624 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010625 break;
10626 }
Andy Hungab65b182023-09-06 19:41:47 -070010627 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010628}
10629
Andy Hungee58e4a2023-07-07 13:47:37 -070010630status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010631 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010632NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010633{
10634 status_t status = NO_ERROR;
10635
10636 // store new device and send to effects
10637 audio_devices_t type = AUDIO_DEVICE_NONE;
10638 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010639 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10640 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10641 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010642 if (isOutput()) {
10643 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010644 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10645 && !mAudioHwDev->supportsAudioPatches(),
10646 "Enumerated device type(%#x) must not be used "
10647 "as it does not support audio patches",
10648 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010649 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010650 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10651 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652 }
10653 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010654 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010655 } else {
10656 type = patch->sources[0].ext.device.type;
10657 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010658 numDevices = mPatch.num_sources;
10659 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010660 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010661 }
10662
10663 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010664 if (isOutput()) {
10665 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10666 } else {
10667 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10668 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669 }
10670
jiabinc52b1ff2019-10-31 17:20:42 -070010671 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010672 // store new source and send to effects
10673 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10674 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10675 for (size_t i = 0; i < mEffectChains.size(); i++) {
10676 mEffectChains[i]->setAudioSource_l(mAudioSource);
10677 }
10678 }
10679 }
10680
jiabin78b86f22024-02-22 00:39:29 +000010681 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10682 // okay to notify the client earlier before the new patch creation.
10683 if (mDeviceId != deviceId) {
10684 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10685 // The aaudioservice handle the routing changed event asynchronously. In that case,
10686 // it is safe to hold the lock here.
10687 callback->onRoutingChanged(deviceId);
10688 }
10689 }
10690
Eric Laurent6acd1d42017-01-04 14:23:29 -080010691 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010692 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10693 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010694 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010695 audio_port_config port;
10696 std::optional<audio_source_t> source;
10697 if (isOutput()) {
10698 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010699 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010700 port = patch->sources[0];
10701 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010703 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010704 *handle = AUDIO_PATCH_HANDLE_NONE;
10705 }
10706
jiabinc52b1ff2019-10-31 17:20:42 -070010707 if (numDevices == 0 || mDeviceId != deviceId) {
10708 if (isOutput()) {
10709 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10710 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010711 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010712 } else {
10713 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10714 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10715 }
jiabinc52b1ff2019-10-31 17:20:42 -070010716 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010717 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010718 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010719 // Force meteadata update after a route change
10720 mActiveTracks.setHasChanged();
10721
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722 return status;
10723}
10724
Andy Hungee58e4a2023-07-07 13:47:37 -070010725status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010726{
10727 status_t status = NO_ERROR;
10728
jiabinc52b1ff2019-10-31 17:20:42 -070010729 mPatch = audio_patch{};
10730 mOutDeviceTypeAddrs.clear();
10731 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010732
10733 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10734 supportsAudioPatches : false;
10735
10736 if (supportsAudioPatches) {
10737 status = mHalDevice->releaseAudioPatch(handle);
10738 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010739 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010741 // Force meteadata update after a route change
10742 mActiveTracks.setHasChanged();
10743
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744 return status;
10745}
10746
Andy Hungee58e4a2023-07-07 13:47:37 -070010747void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010748NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010749{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010750 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010751 if (isOutput()) {
10752 config->role = AUDIO_PORT_ROLE_SOURCE;
10753 config->ext.mix.hw_module = mAudioHwDev->handle();
10754 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10755 } else {
10756 config->role = AUDIO_PORT_ROLE_SINK;
10757 config->ext.mix.hw_module = mAudioHwDev->handle();
10758 config->ext.mix.usecase.source = mAudioSource;
10759 }
10760}
10761
Andy Hungee58e4a2023-07-07 13:47:37 -070010762status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763{
10764 audio_session_t session = chain->sessionId();
10765
10766 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10767 // Attach all tracks with same session ID to this chain.
10768 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010769 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010770 if (session == track->sessionId()) {
10771 chain->incTrackCnt();
10772 chain->incActiveTrackCnt();
10773 }
10774 }
10775
10776 chain->setThread(this);
10777 chain->setInBuffer(nullptr);
10778 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010779 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780
10781 mEffectChains.add(chain);
10782 checkSuspendOnAddEffectChain_l(chain);
10783 return NO_ERROR;
10784}
10785
Andy Hungee58e4a2023-07-07 13:47:37 -070010786size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787{
10788 audio_session_t session = chain->sessionId();
10789
10790 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10791
10792 for (size_t i = 0; i < mEffectChains.size(); i++) {
10793 if (chain == mEffectChains[i]) {
10794 mEffectChains.removeAt(i);
10795 // detach all active tracks from the chain
10796 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010797 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798 if (session == track->sessionId()) {
10799 chain->decActiveTrackCnt();
10800 chain->decTrackCnt();
10801 }
10802 }
10803 break;
10804 }
10805 }
10806 return mEffectChains.size();
10807}
10808
Andy Hungee58e4a2023-07-07 13:47:37 -070010809void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010810{
10811 mHalStream->standby();
10812}
10813
Andy Hungee58e4a2023-07-07 13:47:37 -070010814void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010815{
Phil Burk7dce7282017-09-27 13:51:41 -070010816 // Do not call callback->onTearDown() because it is redundant for thread exit
10817 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010818}
10819
Andy Hungee58e4a2023-07-07 13:47:37 -070010820status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010821{
10822 return BAD_VALUE;
10823}
10824
Andy Hungee58e4a2023-07-07 13:47:37 -070010825bool MmapThread::isValidSyncEvent(
10826 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010827{
10828 return false;
10829}
10830
Andy Hungee58e4a2023-07-07 13:47:37 -070010831status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010832 const effect_descriptor_t *desc, audio_session_t sessionId)
10833{
10834 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010835 if (audio_is_global_session(sessionId)) {
10836 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837 desc->name, mThreadName);
10838 return BAD_VALUE;
10839 }
10840
10841 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10842 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10843 desc->name);
10844 return BAD_VALUE;
10845 }
10846 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010847 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10848 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010849 return BAD_VALUE;
10850 }
10851
10852 // Only allow effects without processing load or latency
10853 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10854 return BAD_VALUE;
10855 }
10856
Andy Hung116bc262023-06-20 18:56:17 -070010857 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010858 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10859 return BAD_VALUE;
10860 }
10861
Eric Laurent6acd1d42017-01-04 14:23:29 -080010862 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010863}
10864
Andy Hungee58e4a2023-07-07 13:47:37 -070010865void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010866{
Andy Hung8d31fd22023-06-26 19:20:57 -070010867 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010868 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010869 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10870 // The aaudioservice handle the routing changed event asynchronously. In that case,
10871 // it is safe to hold the lock here.
10872 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10873 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010874 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10875 mNoCallbackWarningCount++;
10876 }
10877 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010878 }
10879 }
10880}
10881
Andy Hungee58e4a2023-07-07 13:47:37 -070010882void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010883{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010884 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10885 mAttr.content_type, mAttr.usage, mAttr.source);
10886 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010887 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010888 dprintf(fd, " No active clients\n");
10889 }
10890}
10891
Andy Hungee58e4a2023-07-07 13:47:37 -070010892void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010893{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010894 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010895 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010896 dprintf(fd, " %zu Tracks\n", numtracks);
10897 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010898 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010899 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010900 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010901 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010902 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010903 result.append(prefix);
10904 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010905 }
10906 } else {
10907 dprintf(fd, "\n");
10908 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010909 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010910}
10911
Andy Hungee58e4a2023-07-07 13:47:37 -070010912/* static */
10913sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010914 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010915 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010916 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010917}
10918
10919MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010920 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010921 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010922 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010923 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010924 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010925{
10926 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10927 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010928 mMasterVolume = afThreadCallback->masterVolume_l();
10929 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010930
10931 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10932 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10933 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010934 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010935 }
10936 // Audio patch and call assistant volume are always max
10937 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10938 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10939 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10940 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10941
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942 if (mAudioHwDev) {
10943 if (mAudioHwDev->canSetMasterVolume()) {
10944 mMasterVolume = 1.0;
10945 }
10946
10947 if (mAudioHwDev->canSetMasterMute()) {
10948 mMasterMute = false;
10949 }
10950 }
10951}
10952
Andy Hungee58e4a2023-07-07 13:47:37 -070010953void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954 audio_stream_type_t streamType,
10955 audio_session_t sessionId,
10956 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010957 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010958 audio_port_handle_t portId)
10959{
Andy Hung8d672e02023-09-15 18:19:28 -070010960 audio_utils::lock_guard l(mutex());
10961 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010962 mStreamType = streamType;
10963}
10964
Andy Hungee58e4a2023-07-07 13:47:37 -070010965AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010966{
Andy Hung972bec12023-08-31 16:13:39 -070010967 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010968 AudioStreamOut *output = mOutput;
10969 mOutput = NULL;
10970 return output;
10971}
10972
Andy Hungee58e4a2023-07-07 13:47:37 -070010973void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010974{
Andy Hung972bec12023-08-31 16:13:39 -070010975 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010976 // Don't apply master volume in SW if our HAL can do it for us.
10977 if (mAudioHwDev &&
10978 mAudioHwDev->canSetMasterVolume()) {
10979 mMasterVolume = 1.0;
10980 } else {
10981 mMasterVolume = value;
10982 }
10983}
10984
Andy Hungee58e4a2023-07-07 13:47:37 -070010985void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010986{
Andy Hung972bec12023-08-31 16:13:39 -070010987 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010988 // Don't apply master mute in SW if our HAL can do it for us.
10989 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10990 mMasterMute = false;
10991 } else {
10992 mMasterMute = muted;
10993 }
10994}
10995
Andy Hungee58e4a2023-07-07 13:47:37 -070010996void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010997{
Andy Hung972bec12023-08-31 16:13:39 -070010998 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010999 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011000 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011001 broadcast_l();
11002 }
11003}
11004
Andy Hungee58e4a2023-07-07 13:47:37 -070011005float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011006{
Andy Hung972bec12023-08-31 16:13:39 -070011007 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011008 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011009}
11010
Andy Hungee58e4a2023-07-07 13:47:37 -070011011void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011012{
Andy Hung972bec12023-08-31 16:13:39 -070011013 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011014 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011015 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011016 broadcast_l();
11017 }
11018}
11019
Andy Hungee58e4a2023-07-07 13:47:37 -070011020void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011021{
Andy Hung972bec12023-08-31 16:13:39 -070011022 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011023 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011024 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011025 track->invalidate();
11026 }
11027 broadcast_l();
11028 }
11029}
11030
Andy Hungee58e4a2023-07-07 13:47:37 -070011031void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011032{
Andy Hung972bec12023-08-31 16:13:39 -070011033 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011034 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011035 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011036 if (portIds.find(track->portId()) != portIds.end()) {
11037 track->invalidate();
11038 trackMatch = true;
11039 portIds.erase(track->portId());
11040 }
11041 if (portIds.empty()) {
11042 break;
11043 }
11044 }
11045 if (trackMatch) {
11046 broadcast_l();
11047 }
11048}
11049
Andy Hungee58e4a2023-07-07 13:47:37 -070011050void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011051NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011052{
11053 float volume;
11054
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011055 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011056 volume = 0;
11057 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011058 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059 }
11060
11061 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011062 // Convert volumes from float to 8.24
11063 uint32_t vol = (uint32_t)(volume * (1 << 24));
11064
11065 // Delegate volume control to effect in track effect chain if needed
11066 // only one effect chain can be present on DirectOutputThread, so if
11067 // there is one, the track is connected to it
11068 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011069 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011070 volume = (float)vol / (1 << 24);
11071 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011072 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011073 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11074 mHalVolFloat = volume; // HW volume control worked, so update value.
11075 mNoCallbackWarningCount = 0;
11076 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011077 sp<MmapStreamCallback> callback = mCallback.promote();
11078 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011079 mHalVolFloat = volume; // SW volume control worked, so update value.
11080 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011081 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011082 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011083 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011084 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011085 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11086 ALOGW("Could not set MMAP stream volume: no volume callback!");
11087 mNoCallbackWarningCount++;
11088 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011089 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011090 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011091 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011092 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070011093 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011094 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011095 streamVolume_l() == 0.f,
11096 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011097 // TODO(b/241533526): adjust logic to include mute from AppOps
11098 false /*muteFromPlaybackRestricted*/,
11099 false /*muteFromClientVolume*/,
11100 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011101 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011102 }
11103}
11104
Andy Hungee58e4a2023-07-07 13:47:37 -070011105ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011106{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011107 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011108 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011109 }
11110 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011111 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011112 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011113 playback_track_metadata_v7_t trackMetadata;
11114 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011115 .usage = track->attributes().usage,
11116 .content_type = track->attributes().content_type,
11117 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011118 };
11119 trackMetadata.channel_mask = track->channelMask(),
11120 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11121 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011122 }
11123 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011124
11125 MetadataUpdate change;
11126 change.playbackMetadataUpdate = metadata.tracks;
11127 return change;
11128};
Kevin Rocard069c2712018-03-29 19:09:14 -070011129
Andy Hungee58e4a2023-07-07 13:47:37 -070011130void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011131{
11132 if (!mMasterMute) {
11133 char value[PROPERTY_VALUE_MAX];
11134 if (property_get("ro.audio.silent", value, "0") > 0) {
11135 char *endptr;
11136 unsigned long ul = strtoul(value, &endptr, 0);
11137 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011138 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011139 // The setprop command will not allow a property to be changed after
11140 // the first time it is set, so we don't have to worry about un-muting.
11141 setMasterMute_l(true);
11142 }
11143 }
11144 }
11145}
11146
Andy Hungee58e4a2023-07-07 13:47:37 -070011147void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011148{
11149 MmapThread::toAudioPortConfig(config);
11150 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11151 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11152 config->flags.output = mOutput->flags;
11153 }
11154}
11155
Andy Hungee58e4a2023-07-07 13:47:37 -070011156status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011157 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011158{
11159 if (mOutput == nullptr) {
11160 return NO_INIT;
11161 }
11162 struct timespec timestamp;
11163 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11164 if (status == NO_ERROR) {
11165 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11166 }
11167 return status;
11168}
11169
Andy Hungee58e4a2023-07-07 13:47:37 -070011170status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011171 // Send to MelProcessor for sound dose measurement.
11172 auto processor = mMelProcessor.load();
11173 if (processor) {
11174 processor->process(buffer, frameCount * mFrameSize);
11175 }
11176
jiabinfc791ee2023-02-15 19:43:40 +000011177 return NO_ERROR;
11178}
11179
Andy Hungc5007f82023-08-29 14:26:09 -070011180// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011181void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011182 const sp<audio_utils::MelProcessor>& processor)
11183{
11184 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011185 mMelProcessor.store(processor);
11186 if (processor) {
11187 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011188 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011189
11190 // no need to update output format for MMapPlaybackThread since it is
11191 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011192}
11193
Andy Hungc5007f82023-08-29 14:26:09 -070011194// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011195void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011196{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011197 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11198 auto melProcessor = mMelProcessor.load();
11199 if (melProcessor != nullptr) {
11200 melProcessor->pause();
11201 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011202}
11203
Andy Hungee58e4a2023-07-07 13:47:37 -070011204void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011205{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011206 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011207
Glenn Kastend3bb6452016-12-05 18:14:37 -080011208 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011209 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011210 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11211}
11212
Andy Hungee58e4a2023-07-07 13:47:37 -070011213/* static */
11214sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011215 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011216 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011217 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011218}
11219
11220MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011221 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011222 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011223 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011224 mInput(input)
11225{
11226 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11227 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11228}
11229
Andy Hungee58e4a2023-07-07 13:47:37 -070011230status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011231{
Phil Burkf054fc32018-12-06 09:45:59 -080011232 {
11233 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011234 if (mInput != nullptr && mInput->stream != nullptr) {
11235 mInput->stream->setGain(1.0f);
11236 }
11237 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011238 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011239}
11240
Andy Hungee58e4a2023-07-07 13:47:37 -070011241AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011242{
Andy Hung972bec12023-08-31 16:13:39 -070011243 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011244 AudioStreamIn *input = mInput;
11245 mInput = NULL;
11246 return input;
11247}
Kevin Rocard069c2712018-03-29 19:09:14 -070011248
Andy Hungee58e4a2023-07-07 13:47:37 -070011249void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011250{
11251 bool changed = false;
11252 bool silenced = false;
11253
11254 sp<MmapStreamCallback> callback = mCallback.promote();
11255 if (callback == 0) {
11256 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11257 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11258 mNoCallbackWarningCount++;
11259 }
11260 }
11261
11262 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11263 // track is silenced and unmute otherwise
11264 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11265 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11266 changed = true;
11267 silenced = mActiveTracks[i]->isSilenced_l();
11268 }
11269 }
11270
11271 if (changed) {
11272 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11273 }
11274}
11275
Andy Hungee58e4a2023-07-07 13:47:37 -070011276ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011277{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011278 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011279 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011280 }
11281 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011282 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011283 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011284 record_track_metadata_v7_t trackMetadata;
11285 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011286 .source = track->attributes().source,
11287 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011288 };
11289 trackMetadata.channel_mask = track->channelMask(),
11290 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11291 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011292 }
11293 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011294 MetadataUpdate change;
11295 change.recordMetadataUpdate = metadata.tracks;
11296 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011297}
11298
Andy Hungee58e4a2023-07-07 13:47:37 -070011299void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011300{
Andy Hung972bec12023-08-31 16:13:39 -070011301 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011302 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011303 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011304 mActiveTracks[i]->setSilenced_l(silenced);
11305 broadcast_l();
11306 }
11307 }
jiabin09609032022-06-15 19:26:01 +000011308 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011309}
11310
Andy Hungee58e4a2023-07-07 13:47:37 -070011311void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011312{
11313 MmapThread::toAudioPortConfig(config);
11314 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11315 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11316 config->flags.input = mInput->flags;
11317 }
11318}
11319
Andy Hungee58e4a2023-07-07 13:47:37 -070011320status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011321 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011322{
11323 if (mInput == nullptr) {
11324 return NO_INIT;
11325 }
11326 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11327}
11328
jiabinc658e452022-10-21 20:52:21 +000011329// ----------------------------------------------------------------------------
11330
Andy Hungee58e4a2023-07-07 13:47:37 -070011331/* static */
11332sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011333 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011334 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011335 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011336}
11337
Andy Hung583043b2023-07-17 17:05:00 -070011338BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011339 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011340 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011341
Andy Hungee58e4a2023-07-07 13:47:37 -070011342PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011343 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011344 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11345 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011346 float volumeLeft = 1.0f;
11347 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011348 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11349 const int trackId = mActiveTracks[0]->id();
11350 mAudioMixer->setParameter(
11351 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11352 mAudioMixer->setParameter(
11353 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11354 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011355 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011356 mIsBitPerfect = true;
11357 } else {
11358 mIsBitPerfect = false;
11359 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11360 // active.
11361 for (const auto& track : mActiveTracks) {
11362 const int trackId = track->id();
11363 mAudioMixer->setParameter(
11364 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11365 }
11366 }
jiabin76d94692022-12-15 21:51:21 +000011367 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11368 mVolumeLeft = volumeLeft;
11369 mVolumeRight = volumeRight;
11370 setVolumeForOutput_l(volumeLeft, volumeRight);
11371 }
jiabinc658e452022-10-21 20:52:21 +000011372 return result;
11373}
11374
Andy Hungee58e4a2023-07-07 13:47:37 -070011375void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011376 MixerThread::threadLoop_mix();
11377 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11378}
11379
Glenn Kasten63238ef2015-03-02 15:50:29 -080011380} // namespace android