blob: 8c9e7c82e363f5ce7d3915c1478c4c29a110f5ff [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>
jiabin220eea12024-05-17 17:55:20 +000036#include <com_android_media_audioserver.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070037#ifdef DEBUG_CPU_USAGE
38#include <audio_utils/Statistics.h>
39#include <cpustats/ThreadCpuUsage.h>
40#endif
41#include <audio_utils/channels.h>
42#include <audio_utils/format.h>
43#include <audio_utils/minifloat.h>
44#include <audio_utils/mono_blend.h>
45#include <audio_utils/primitives.h>
46#include <audio_utils/safe_math.h>
47#include <audiomanager/AudioManager.h>
48#include <binder/IPCThreadState.h>
49#include <binder/IServiceManager.h>
50#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010051#include <com_android_media_audio.h>
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020052#include <com_android_media_audioserver.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070053#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080054#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070055#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070056#include <media/AudioContainers.h>
57#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070058#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070059#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070060#ifdef ADD_BATTERY_DATA
61#include <media/IMediaPlayerService.h>
62#include <media/IMediaDeathNotifier.h>
63#endif
64#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080065#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070066#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070067#include <media/audiohal/EffectsFactoryHalInterface.h>
68#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070069#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070#include <media/nbaio/AudioStreamOutSink.h>
71#include <media/nbaio/MonoPipe.h>
72#include <media/nbaio/MonoPipeReader.h>
73#include <media/nbaio/Pipe.h>
74#include <media/nbaio/PipeReader.h>
75#include <media/nbaio/SourceAudioBufferProvider.h>
Atneya Nair5997a652024-06-14 17:24:45 -070076#include <media/ValidatedAttributionSourceState.h>
Wei Jia3f273d12015-11-24 09:06:49 -080077#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070078#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070079#include <mediautils/SchedulingPolicyService.h>
80#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070081#include <powermanager/PowerManager.h>
82#include <private/android_filesystem_config.h>
83#include <private/media/AudioTrackShared.h>
84#include <system/audio_effects/effect_aec.h>
85#include <system/audio_effects/effect_downmix.h>
86#include <system/audio_effects/effect_ns.h>
87#include <system/audio_effects/effect_spatializer.h>
88#include <utils/Log.h>
89#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080090
Andy Hung25a80ac2023-07-19 12:47:35 -070091#include <fcntl.h>
92#include <linux/futex.h>
93#include <math.h>
94#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080095#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070096#include <sstream>
97#include <string>
98#include <sys/stat.h>
99#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101// ----------------------------------------------------------------------------
102
103// Note: the following macro is used for extremely verbose logging message. In
104// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
105// 0; but one side effect of this is to turn all LOGV's as well. Some messages
106// are so verbose that we want to suppress them even when we have ALOG_ASSERT
107// turned on. Do not uncomment the #def below unless you really know what you
108// are doing and want to see all of the extremely verbose messages.
109//#define VERY_VERY_VERBOSE_LOGGING
110#ifdef VERY_VERY_VERBOSE_LOGGING
111#define ALOGVV ALOGV
112#else
113#define ALOGVV(a...) do { } while(0)
114#endif
115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700117#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700118
Andy Hung6770c6f2015-04-07 13:43:36 -0700119template <typename T>
120static inline T min(const T& a, const T& b)
121{
122 return a < b ? a : b;
123}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700124
Atneya Nair5997a652024-06-14 17:24:45 -0700125using com::android::media::permission::ValidatedAttributionSourceState;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +0200126namespace audioserver_flags = com::android::media::audioserver;
Atneya Nair5997a652024-06-14 17:24:45 -0700127
Eric Laurent81784c32012-11-19 14:55:58 -0800128namespace android {
129
Andy Hungee58e4a2023-07-07 13:47:37 -0700130using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000132using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700133
Andy Hung25a80ac2023-07-19 12:47:35 -0700134// Keep in sync with java definition in media/java/android/media/AudioRecord.java
135static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
136
Eric Laurent81784c32012-11-19 14:55:58 -0800137// retry counts for buffer fill timeout
138// 50 * ~20msecs = 1 second
139static const int8_t kMaxTrackRetries = 50;
140static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700141
Eric Laurent81784c32012-11-19 14:55:58 -0800142// allow less retry attempts on direct output thread.
143// direct outputs can be a scarce resource in audio hardware and should
144// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700145// Notes:
146// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
147// in case the data write is bursty for the AudioTrack. The application
148// should endeavor to write at least once every kMaxTrackRetriesDirectMs
149// to prevent an underrun situation. If the data is bursty, then
150// the application can also throttle the data sent to be even.
151// 2) For compressed audio data, any data present in the AudioTrack buffer
152// will be sent and reset the retry count. This delivers data as
153// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
154// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
155// of data to be available, then any remaining data is delivered.
156// This is required to ensure the last bit of data is delivered before underrun.
157//
158// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
159// or the size of the HAL period for proportional / linear PCM tracks.
160static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800161
162// don't warn about blocked writes or record buffer overflows more often than this
163static const nsecs_t kWarningThrottleNs = seconds(5);
164
165// RecordThread loop sleep time upon application overrun or audio HAL read error
166static const int kRecordThreadSleepUs = 5000;
167
Eric Laurent10351942014-05-08 18:49:52 -0700168// maximum time to wait in sendConfigEvent_l() for a status to be received
169static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800170
171// minimum sleep time for the mixer thread loop when tracks are active but in underrun
172static const uint32_t kMinThreadSleepTimeUs = 5000;
173// maximum divider applied to the active sleep time in the mixer thread loop
174static const uint32_t kMaxThreadSleepTimeShift = 2;
175
Andy Hung09a50072014-02-27 14:30:47 -0800176// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700177// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800178static const uint32_t kMinNormalSinkBufferSizeMs = 20;
179// maximum normal sink buffer size
180static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700182// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
183// FIXME This should be based on experimentally observed scheduling jitter
184static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
185
Eric Laurent972a1732013-09-04 09:42:59 -0700186// Offloaded output thread standby delay: allows track transition without going to standby
187static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
188
Eric Laurent51716182016-02-29 18:00:56 -0800189// Direct output thread minimum sleep time in idle or active(underrun) state
190static const nsecs_t kDirectMinSleepTimeUs = 10000;
191
Brian Lindahl65e90012022-07-27 18:01:07 +0200192// Minimum amount of time between checking to see if the timestamp is advancing
193// for underrun detection. If we check too frequently, we may not detect a
194// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800195static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200196
Glenn Kasten1b291842016-07-18 14:55:21 -0700197// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
198// balance between power consumption and latency, and allows threads to be scheduled reliably
199// by the CFS scheduler.
200// FIXME Express other hardcoded references to 20ms with references to this constant and move
201// it appropriately.
202#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800203
Eric Laurent81784c32012-11-19 14:55:58 -0800204// Whether to use fast mixer
205static const enum {
206 FastMixer_Never, // never initialize or use: for debugging only
207 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
208 // normal mixer multiplier is 1
209 FastMixer_Static, // initialize if needed, then use all the time if initialized,
210 // multiplier is calculated based on min & max normal mixer buffer size
211 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
212 // multiplier is calculated based on min & max normal mixer buffer size
213 // FIXME for FastMixer_Dynamic:
214 // Supporting this option will require fixing HALs that can't handle large writes.
215 // For example, one HAL implementation returns an error from a large write,
216 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
217 // We could either fix the HAL implementations, or provide a wrapper that breaks
218 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
219} kUseFastMixer = FastMixer_Static;
220
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700221// Whether to use fast capture
222static const enum {
223 FastCapture_Never, // never initialize or use: for debugging only
224 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
225 FastCapture_Static, // initialize if needed, then use all the time if initialized
226} kUseFastCapture = FastCapture_Static;
227
Eric Laurent81784c32012-11-19 14:55:58 -0800228// Priorities for requestPriority
229static const int kPriorityAudioApp = 2;
230static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700231static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000232// Request real-time priority for PlaybackThread in ARC
233static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800234
Glenn Kastenea38ee72016-04-18 11:08:01 -0700235// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
236// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
237// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700238
239// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800240static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800241
Glenn Kasten03490092014-05-27 12:30:54 -0700242// The minimum and maximum allowed values
243static const int kFastTrackMultiplierMin = 1;
244static const int kFastTrackMultiplierMax = 2;
245
246// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
247static int sFastTrackMultiplier = kFastTrackMultiplier;
248
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700249// See Thread::readOnlyHeap().
250// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
251// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
252// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700253static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700254
Andy Hung25a80ac2023-07-19 12:47:35 -0700255static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700256
257static nsecs_t getStandbyTimeInNanos() {
258 static nsecs_t standbyTimeInNanos = []() {
259 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
260 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
261 ALOGI("%s: Using %d ms as standby time", __func__, ms);
262 return milliseconds(ms);
263 }();
264 return standbyTimeInNanos;
265}
266
Andy Hung81994d62023-07-20 21:44:14 -0700267// Set kEnableExtendedChannels to true to enable greater than stereo output
268// for the MixerThread and device sink. Number of channels allowed is
269// FCC_2 <= channels <= FCC_LIMIT.
270constexpr bool kEnableExtendedChannels = true;
271
272// Returns true if channel mask is permitted for the PCM sink in the MixerThread
273/* static */
274bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
275 switch (audio_channel_mask_get_representation(channelMask)) {
276 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
277 // Haptic channel mask is only applicable for channel position mask.
278 const uint32_t channelCount = audio_channel_count_from_out_mask(
279 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
280 const uint32_t maxChannelCount = kEnableExtendedChannels
281 ? FCC_LIMIT : FCC_2;
282 if (channelCount < FCC_2 // mono is not supported at this time
283 || channelCount > maxChannelCount) {
284 return false;
285 }
286 // check that channelMask is the "canonical" one we expect for the channelCount.
287 return audio_channel_position_mask_is_out_canonical(channelMask);
288 }
289 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
290 if (kEnableExtendedChannels) {
291 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
292 if (channelCount >= FCC_2 // mono is not supported at this time
293 && channelCount <= FCC_LIMIT) {
294 return true;
295 }
296 }
297 return false;
298 default:
299 return false;
300 }
301}
302
303// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
304constexpr bool kEnableExtendedPrecision = true;
305
306// Returns true if format is permitted for the PCM sink in the MixerThread
307/* static */
308bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
309 switch (format) {
310 case AUDIO_FORMAT_PCM_16_BIT:
311 return true;
312 case AUDIO_FORMAT_PCM_FLOAT:
313 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
314 case AUDIO_FORMAT_PCM_32_BIT:
315 case AUDIO_FORMAT_PCM_8_24_BIT:
316 return kEnableExtendedPrecision;
317 default:
318 return false;
319 }
320}
321
Eric Laurent81784c32012-11-19 14:55:58 -0800322// ----------------------------------------------------------------------------
323
Andy Hung25a80ac2023-07-19 12:47:35 -0700324// formatToString() needs to be exact for MediaMetrics purposes.
325// Do not use media/TypeConverter.h toString().
326/* static */
327std::string IAfThreadBase::formatToString(audio_format_t format) {
328 std::string result;
329 FormatConverter::toString(format, result);
330 return result;
331}
332
Andy Hungb68f5eb2019-12-03 16:49:17 -0800333// TODO: move all toString helpers to audio.h
334// under #ifdef __cplusplus #endif
335static std::string patchSinksToString(const struct audio_patch *patch)
336{
337 std::stringstream ss;
338 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700339 if (i > 0) {
340 ss << "|";
341 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800342 ss << "(" << toString(patch->sinks[i].ext.device.type)
343 << ", " << patch->sinks[i].ext.device.address << ")";
344 }
345 return ss.str();
346}
347
348static std::string patchSourcesToString(const struct audio_patch *patch)
349{
350 std::stringstream ss;
351 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700352 if (i > 0) {
353 ss << "|";
354 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800355 ss << "(" << toString(patch->sources[i].ext.device.type)
356 << ", " << patch->sources[i].ext.device.address << ")";
357 }
358 return ss.str();
359}
360
Andy Hung4bd53e72022-11-17 17:21:45 -0800361static std::string toString(audio_latency_mode_t mode) {
362 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000363 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
364 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800365}
366
367// Could be made a template, but other toString overloads for std::vector are confused.
368static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
369 std::string s("{ ");
370 for (const auto& e : elements) {
371 s.append(toString(e));
372 s.append(" ");
373 }
374 s.append("}");
375 return s;
376}
377
Glenn Kasten03490092014-05-27 12:30:54 -0700378static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
379
380static void sFastTrackMultiplierInit()
381{
382 char value[PROPERTY_VALUE_MAX];
383 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
384 char *endptr;
385 unsigned long ul = strtoul(value, &endptr, 0);
386 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
387 sFastTrackMultiplier = (int) ul;
388 }
389 }
390}
391
392// ----------------------------------------------------------------------------
393
Eric Laurent81784c32012-11-19 14:55:58 -0800394#ifdef ADD_BATTERY_DATA
395// To collect the amplifier usage
396static void addBatteryData(uint32_t params) {
397 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
398 if (service == NULL) {
399 // it already logged
400 return;
401 }
402
403 service->addBatteryData(params);
404}
405#endif
406
Andy Hung3f0c9022016-01-15 17:49:46 -0800407// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
408struct {
409 // call when you acquire a partial wakelock
410 void acquire(const sp<IBinder> &wakeLockToken) {
411 pthread_mutex_lock(&mLock);
412 if (wakeLockToken.get() == nullptr) {
413 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
414 } else {
415 if (mCount == 0) {
416 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
417 }
418 ++mCount;
419 }
420 pthread_mutex_unlock(&mLock);
421 }
422
423 // call when you release a partial wakelock.
424 void release(const sp<IBinder> &wakeLockToken) {
425 if (wakeLockToken.get() == nullptr) {
426 return;
427 }
428 pthread_mutex_lock(&mLock);
429 if (--mCount < 0) {
430 ALOGE("negative wakelock count");
431 mCount = 0;
432 }
433 pthread_mutex_unlock(&mLock);
434 }
435
436 // retrieves the boottime timebase offset from monotonic.
437 int64_t getBoottimeOffset() {
438 pthread_mutex_lock(&mLock);
439 int64_t boottimeOffset = mBoottimeOffset;
440 pthread_mutex_unlock(&mLock);
441 return boottimeOffset;
442 }
443
444 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
445 // and the selected timebase.
446 // Currently only TIMEBASE_BOOTTIME is allowed.
447 //
448 // This only needs to be called upon acquiring the first partial wakelock
449 // after all other partial wakelocks are released.
450 //
451 // We do an empirical measurement of the offset rather than parsing
452 // /proc/timer_list since the latter is not a formal kernel ABI.
453 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
454 int clockbase;
455 switch (timebase) {
456 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
457 clockbase = SYSTEM_TIME_BOOTTIME;
458 break;
459 default:
460 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
461 break;
462 }
463 // try three times to get the clock offset, choose the one
464 // with the minimum gap in measurements.
465 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700466 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800467 for (int i = 0; i < tries; ++i) {
468 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
469 const nsecs_t tbase = systemTime(clockbase);
470 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
471 const nsecs_t gap = tmono2 - tmono;
472 if (i == 0 || gap < bestGap) {
473 bestGap = gap;
474 measured = tbase - ((tmono + tmono2) >> 1);
475 }
476 }
477
478 // to avoid micro-adjusting, we don't change the timebase
479 // unless it is significantly different.
480 //
481 // Assumption: It probably takes more than toleranceNs to
482 // suspend and resume the device.
483 static int64_t toleranceNs = 10000; // 10 us
484 if (llabs(*offset - measured) > toleranceNs) {
485 ALOGV("Adjusting timebase offset old: %lld new: %lld",
486 (long long)*offset, (long long)measured);
487 *offset = measured;
488 }
489 }
490
491 pthread_mutex_t mLock;
492 int32_t mCount;
493 int64_t mBoottimeOffset;
494} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800495
496// ----------------------------------------------------------------------------
497// CPU Stats
498// ----------------------------------------------------------------------------
499
500class CpuStats {
501public:
502 CpuStats();
503 void sample(const String8 &title);
504#ifdef DEBUG_CPU_USAGE
505private:
506 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700507 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800508
Andy Hung16698b82018-08-01 10:48:38 -0700509 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800510
511 int mCpuNum; // thread's current CPU number
512 int mCpukHz; // frequency of thread's current CPU in kHz
513#endif
514};
515
516CpuStats::CpuStats()
517#ifdef DEBUG_CPU_USAGE
518 : mCpuNum(-1), mCpukHz(-1)
519#endif
520{
521}
522
Glenn Kasten0f11b512014-01-31 16:18:54 -0800523void CpuStats::sample(const String8 &title
524#ifndef DEBUG_CPU_USAGE
525 __unused
526#endif
527 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800528#ifdef DEBUG_CPU_USAGE
529 // get current thread's delta CPU time in wall clock ns
530 double wcNs;
531 bool valid = mCpuUsage.sampleAndEnable(wcNs);
532
533 // record sample for wall clock statistics
534 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700535 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800536 }
537
538 // get the current CPU number
539 int cpuNum = sched_getcpu();
540
541 // get the current CPU frequency in kHz
542 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
543
544 // check if either CPU number or frequency changed
545 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
546 mCpuNum = cpuNum;
547 mCpukHz = cpukHz;
548 // ignore sample for purposes of cycles
549 valid = false;
550 }
551
552 // if no change in CPU number or frequency, then record sample for cycle statistics
553 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700554 const double cycles = wcNs * cpukHz * 0.000001;
555 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800556 }
557
Eric Tan5b13ff82018-07-27 11:20:17 -0700558 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800559 // mCpuUsage.elapsed() is expensive, so don't call it every loop
560 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700561 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800562 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700563 const double perLoop = elapsed / (double) n;
564 const double perLoop100 = perLoop * 0.01;
565 const double perLoop1k = perLoop * 0.001;
566 const double mean = mWcStats.getMean();
567 const double stddev = mWcStats.getStdDev();
568 const double minimum = mWcStats.getMin();
569 const double maximum = mWcStats.getMax();
570 const double meanCycles = mHzStats.getMean();
571 const double stddevCycles = mHzStats.getStdDev();
572 const double minCycles = mHzStats.getMin();
573 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800574 mCpuUsage.resetElapsed();
575 mWcStats.reset();
576 mHzStats.reset();
577 ALOGD("CPU usage for %s over past %.1f secs\n"
578 " (%u mixer loops at %.1f mean ms per loop):\n"
579 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
580 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
581 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000582 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800583 elapsed * .000000001, n, perLoop * .000001,
584 mean * .001,
585 stddev * .001,
586 minimum * .001,
587 maximum * .001,
588 mean / perLoop100,
589 stddev / perLoop100,
590 minimum / perLoop100,
591 maximum / perLoop100,
592 meanCycles / perLoop1k,
593 stddevCycles / perLoop1k,
594 minCycles / perLoop1k,
595 maxCycles / perLoop1k);
596
597 }
598 }
599#endif
600};
601
602// ----------------------------------------------------------------------------
603// ThreadBase
604// ----------------------------------------------------------------------------
605
Glenn Kasten97b7b752014-09-28 13:04:24 -0700606// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700607const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700608{
609 switch (type) {
610 case MIXER:
611 return "MIXER";
612 case DIRECT:
613 return "DIRECT";
614 case DUPLICATING:
615 return "DUPLICATING";
616 case RECORD:
617 return "RECORD";
618 case OFFLOAD:
619 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700620 case MMAP_PLAYBACK:
621 return "MMAP_PLAYBACK";
622 case MMAP_CAPTURE:
623 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200624 case SPATIALIZER:
625 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000626 case BIT_PERFECT:
627 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700628 default:
629 return "unknown";
630 }
631}
632
Andy Hung583043b2023-07-17 17:05:00 -0700633ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700634 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800635 : Thread(false /*canCallJava*/),
636 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700637 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700638 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
639 isOut),
640 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700641 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800642 // are set by PlaybackThread::readOutputParameters_l() or
643 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700644 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700645 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700646 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800647 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700648 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800649 mSystemReady(systemReady),
650 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800651{
Andy Hungcf10d742020-04-28 15:38:24 -0700652 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700653 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800654}
655
Andy Hungee58e4a2023-07-07 13:47:37 -0700656ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800657{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700658 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700659 mConfigEvents.clear();
660
Eric Laurent81784c32012-11-19 14:55:58 -0800661 // do not lock the mutex in destructor
662 releaseWakeLock_l();
663 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800664 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800665 binder->unlinkToDeath(mDeathRecipient);
666 }
Andy Hungd0979812019-02-21 15:51:44 -0800667
668 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800669}
670
Andy Hungee58e4a2023-07-07 13:47:37 -0700671status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700672{
673 status_t status = initCheck();
674 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800675 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700676 } else {
677 ALOGE("No working audio driver found.");
678 }
679 return status;
680}
681
Andy Hungee58e4a2023-07-07 13:47:37 -0700682void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800683{
684 ALOGV("ThreadBase::exit");
685 // do any cleanup required for exit to succeed
686 preExit();
687 {
688 // This lock prevents the following race in thread (uniprocessor for illustration):
689 // if (!exitPending()) {
690 // // context switch from here to exit()
691 // // exit() calls requestExit(), what exitPending() observes
692 // // exit() calls signal(), which is dropped since no waiters
693 // // context switch back from exit() to here
694 // mWaitWorkCV.wait(...);
695 // // now thread is hung
696 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700697 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800698 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700699 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800700 }
701 // When Thread::requestExitAndWait is made virtual and this method is renamed to
702 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700703
704 // For TimeCheck: track waiting on the thread join of getTid().
705 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
706
Eric Laurent81784c32012-11-19 14:55:58 -0800707 requestExitAndWait();
708}
709
Andy Hungee58e4a2023-07-07 13:47:37 -0700710status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800711{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000712 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700713 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800714
Eric Laurent10351942014-05-08 18:49:52 -0700715 return sendSetParameterConfigEvent_l(keyValuePairs);
716}
717
718// sendConfigEvent_l() must be called with ThreadBase::mLock held
719// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700720status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700721NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700722{
723 status_t status = NO_ERROR;
724
Eric Laurent72e3f392015-05-20 14:43:50 -0700725 if (event->mRequiresSystemReady && !mSystemReady) {
726 event->mWaitStatus = false;
727 mPendingConfigEvents.add(event);
728 return status;
729 }
Eric Laurent10351942014-05-08 18:49:52 -0700730 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700731 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700732 mWaitWorkCV.notify_one();
733 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700734 {
Andy Hungc5007f82023-08-29 14:26:09 -0700735 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700736 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800737 if (event->mCondition.wait_for(
738 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
739 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700740 event->mStatus = TIMED_OUT;
741 event->mWaitStatus = false;
742 }
743 }
744 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800745 }
Andy Hungc5007f82023-08-29 14:26:09 -0700746 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800747 return status;
748}
749
Andy Hungee58e4a2023-07-07 13:47:37 -0700750void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700751 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800752{
Andy Hung972bec12023-08-31 16:13:39 -0700753 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700754 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800755}
756
Andy Hungc5007f82023-08-29 14:26:09 -0700757// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700758void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700759 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800760{
Andy Hungd0979812019-02-21 15:51:44 -0800761 // The audio statistics history is exponentially weighted to forget events
762 // about five or more seconds in the past. In order to have
763 // crisper statistics for mediametrics, we reset the statistics on
764 // an IoConfigEvent, to reflect different properties for a new device.
765 mIoJitterMs.reset();
766 mLatencyMs.reset();
767 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000768 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100769 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800770
Eric Laurent09f1ed22019-04-24 17:45:17 -0700771 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700772 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800773}
774
Andy Hungee58e4a2023-07-07 13:47:37 -0700775void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700776{
Andy Hung972bec12023-08-31 16:13:39 -0700777 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800778 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700779}
780
Andy Hungc5007f82023-08-29 14:26:09 -0700781// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700782void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800783 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800784{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800785 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700786 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800787}
788
Andy Hungc5007f82023-08-29 14:26:09 -0700789// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700790status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800791{
Andy Hung2ddee192015-12-18 17:34:44 -0800792 sp<ConfigEvent> configEvent;
793 AudioParameter param(keyValuePair);
794 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700795 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800796 setMasterMono_l(value != 0);
797 if (param.size() == 1) {
798 return NO_ERROR; // should be a solo parameter - we don't pass down
799 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700800 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800801 configEvent = new SetParameterConfigEvent(param.toString());
802 } else {
803 configEvent = new SetParameterConfigEvent(keyValuePair);
804 }
Eric Laurent10351942014-05-08 18:49:52 -0700805 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700806}
807
Andy Hungee58e4a2023-07-07 13:47:37 -0700808status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700809 const struct audio_patch *patch,
810 audio_patch_handle_t *handle)
811{
Andy Hung972bec12023-08-31 16:13:39 -0700812 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
814 status_t status = sendConfigEvent_l(configEvent);
815 if (status == NO_ERROR) {
816 CreateAudioPatchConfigEventData *data =
817 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
818 *handle = data->mHandle;
819 }
820 return status;
821}
822
Andy Hungee58e4a2023-07-07 13:47:37 -0700823status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700824 const audio_patch_handle_t handle)
825{
Andy Hung972bec12023-08-31 16:13:39 -0700826 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700827 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
828 return sendConfigEvent_l(configEvent);
829}
830
Andy Hungee58e4a2023-07-07 13:47:37 -0700831status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700832 const DeviceDescriptorBaseVector& outDevices)
833{
834 if (type() != RECORD) {
835 // The update out device operation is only for record thread.
836 return INVALID_OPERATION;
837 }
Andy Hung972bec12023-08-31 16:13:39 -0700838 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700839 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
840 return sendConfigEvent_l(configEvent);
841}
842
Andy Hungee58e4a2023-07-07 13:47:37 -0700843void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200844{
845 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
846 sp<ConfigEvent> configEvent =
847 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
848 sendConfigEvent_l(configEvent);
849}
Eric Laurent1c333e22014-05-20 10:48:17 -0700850
Andy Hungee58e4a2023-07-07 13:47:37 -0700851void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200852{
Andy Hung972bec12023-08-31 16:13:39 -0700853 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200854 sendCheckOutputStageEffectsEvent_l();
855}
856
Andy Hungee58e4a2023-07-07 13:47:37 -0700857void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200858{
859 sp<ConfigEvent> configEvent =
860 (ConfigEvent *)new CheckOutputStageEffectsEvent();
861 sendConfigEvent_l(configEvent);
862}
863
Andy Hungee58e4a2023-07-07 13:47:37 -0700864void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200865{
866 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
867 sendConfigEvent_l(configEvent);
868}
869
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700870// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700871void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700872{
Eric Laurent10351942014-05-08 18:49:52 -0700873 bool configChanged = false;
874
Eric Laurent81784c32012-11-19 14:55:58 -0800875 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700876 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700877 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800878 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700879 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700880 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700881 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
882 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800883 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700884 true /*asynchronous*/);
885 if (err != 0) {
886 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700887 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700888 }
889 } break;
890 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700891 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700892 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700893 } break;
894 case CFG_EVENT_SET_PARAMETER: {
895 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
896 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
897 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700898 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000899 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700900 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700901 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700903 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700904 CreateAudioPatchConfigEventData *data =
905 (CreateAudioPatchConfigEventData *)event->mData.get();
906 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700907 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200908 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700909 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
910 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
911 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700912 } break;
913 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700914 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700915 ReleaseAudioPatchConfigEventData *data =
916 (ReleaseAudioPatchConfigEventData *)event->mData.get();
917 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700918 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200919 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700920 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
921 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
922 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
923 } break;
924 case CFG_EVENT_UPDATE_OUT_DEVICE: {
925 UpdateOutDevicesConfigEventData *data =
926 (UpdateOutDevicesConfigEventData *)event->mData.get();
927 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700928 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200929 case CFG_EVENT_RESIZE_BUFFER: {
930 ResizeBufferConfigEventData *data =
931 (ResizeBufferConfigEventData *)event->mData.get();
932 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
933 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200934
935 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
936 setCheckOutputStageEffects();
937 } break;
938
Eric Laurent68a40a82022-05-03 18:15:04 +0200939 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
940 onHalLatencyModesChanged_l();
941 } break;
942
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700943 default:
Eric Laurent10351942014-05-08 18:49:52 -0700944 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700945 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800946 }
Eric Laurent10351942014-05-08 18:49:52 -0700947 {
Andy Hung972bec12023-08-31 16:13:39 -0700948 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700949 if (event->mWaitStatus) {
950 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700951 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700952 }
953 }
954 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
955 }
956
957 if (configChanged) {
958 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800959 }
Eric Laurent81784c32012-11-19 14:55:58 -0800960}
961
Marco Nelissenb2208842014-02-07 14:00:50 -0800962String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
963 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700964 const audio_channel_representation_t representation =
965 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700966
967 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800968 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700969 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
970 if (output) {
971 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
972 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
973 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700974 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700975 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
976 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
977 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
978 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
979 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
980 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
981 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
982 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
983 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
984 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
985 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
986 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700987 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
988 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
989 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
990 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
991 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
992 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
993 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700994 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700995 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
996 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700997 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
998 } else {
999 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
1000 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
1001 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
1002 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
1003 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
1004 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1005 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1006 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1007 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1008 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1009 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1010 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001011 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1012 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1013 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001014 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001015 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1016 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001017 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1018 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1019 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1020 }
1021 const int len = s.length();
1022 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001023 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001024 s.unlockBuffer(len - 2); // remove trailing ", "
1025 }
1026 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001027 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001028 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1029 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1030 return s;
1031 default:
1032 s.appendFormat("unknown mask, representation:%d bits:%#x",
1033 representation, audio_channel_mask_get_bits(mask));
1034 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001035 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001036}
1037
Andy Hungee58e4a2023-07-07 13:47:37 -07001038void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001039NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001040{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001041 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1042 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1043
Andy Hungc5007f82023-08-29 14:26:09 -07001044 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001045 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001046 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001047 }
1048
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001049 dumpBase_l(fd, args);
1050 dumpInternals_l(fd, args);
1051 dumpTracks_l(fd, args);
1052 dumpEffectChains_l(fd, args);
1053
1054 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001055 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001056 }
1057
1058 dprintf(fd, " Local log:\n");
1059 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001060
1061 // --all does the statistics
1062 bool dumpAll = false;
1063 for (const auto &arg : args) {
1064 if (arg == String16("--all")) {
1065 dumpAll = true;
1066 }
1067 }
1068 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001069 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001070 if (!sched.empty()) {
1071 (void)write(fd, sched.c_str(), sched.size());
1072 }
1073 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001074}
1075
Andy Hungee58e4a2023-07-07 13:47:37 -07001076void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001077{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001078 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001079 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001080 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001081 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001082 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1083 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001084 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001085 dprintf(fd, " Channel count: %u\n", mChannelCount);
1086 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001087 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001088 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1089 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001090 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001091 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001092 size_t numConfig = mConfigEvents.size();
1093 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001094 const size_t SIZE = 256;
1095 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001096 for (size_t i = 0; i < numConfig; i++) {
1097 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001098 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001099 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001100 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001101 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001102 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001103 }
Andy Hung293558a2017-03-21 12:19:20 -07001104 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001105 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001106 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001107 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001108 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001109 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001110
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001111 // Dump timestamp statistics for the Thread types that support it.
1112 if (mType == RECORD
1113 || mType == MIXER
1114 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001115 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001116 || mType == OFFLOAD
1117 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001118 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001119 dprintf(fd, " Timestamp corrected: %s\n",
1120 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001121 }
1122
Andy Hung446f4df2019-02-21 12:26:41 -08001123 if (mLastIoBeginNs > 0) { // MMAP may not set this
1124 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1125 isOutput() ? "write" : "read",
1126 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1127 }
1128
1129 if (mProcessTimeMs.getN() > 0) {
1130 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1131 }
1132
1133 if (mIoJitterMs.getN() > 0) {
1134 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1135 isOutput() ? "write" : "read",
1136 mIoJitterMs.toString().c_str());
1137 }
1138
Andy Hunge6c37112019-02-26 17:38:10 -08001139 if (mLatencyMs.getN() > 0) {
1140 dprintf(fd, " Threadloop %s latency stats: %s\n",
1141 isOutput() ? "write" : "read",
1142 mLatencyMs.toString().c_str());
1143 }
Robert Wu06db0a32021-08-10 19:05:34 +00001144
1145 if (mMonopipePipeDepthStats.getN() > 0) {
1146 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1147 isOutput() ? "write" : "read",
1148 mMonopipePipeDepthStats.toString().c_str());
1149 }
Eric Laurent81784c32012-11-19 14:55:58 -08001150}
1151
Andy Hungee58e4a2023-07-07 13:47:37 -07001152void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001153{
1154 const size_t SIZE = 256;
1155 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001156
Marco Nelissenb2208842014-02-07 14:00:50 -08001157 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001158 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001159 write(fd, buffer, strlen(buffer));
1160
Marco Nelissenb2208842014-02-07 14:00:50 -08001161 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001162 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001163 if (chain != 0) {
1164 chain->dump(fd, args);
1165 }
1166 }
1167}
1168
Andy Hungee58e4a2023-07-07 13:47:37 -07001169void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001170{
Andy Hung972bec12023-08-31 16:13:39 -07001171 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001172 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001173}
1174
Andy Hungee58e4a2023-07-07 13:47:37 -07001175String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001176{
1177 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001178 case MIXER:
1179 return String16("AudioMix");
1180 case DIRECT:
1181 return String16("AudioDirectOut");
1182 case DUPLICATING:
1183 return String16("AudioDup");
1184 case RECORD:
1185 return String16("AudioIn");
1186 case OFFLOAD:
1187 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001188 case MMAP_PLAYBACK:
1189 return String16("MmapPlayback");
1190 case MMAP_CAPTURE:
1191 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001192 case SPATIALIZER:
1193 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001194 default:
1195 ALOG_ASSERT(false);
1196 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001197 }
1198}
1199
Andy Hungee58e4a2023-07-07 13:47:37 -07001200void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001201{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001202 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001203 if (mPowerManager != 0) {
1204 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001205 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001206 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1207 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001208 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001209 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001210 {} /* workSource */,
1211 {} /* historyTag */);
1212 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001213 mWakeLockToken = binder;
1214 }
Chris Ye6597d732020-02-28 22:38:25 -08001215 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001216 }
Wei Jia3f273d12015-11-24 09:06:49 -08001217
Andy Hung3f0c9022016-01-15 17:49:46 -08001218 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001219 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1220 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001221}
1222
Andy Hungee58e4a2023-07-07 13:47:37 -07001223void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001224{
Andy Hung972bec12023-08-31 16:13:39 -07001225 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001226 releaseWakeLock_l();
1227}
1228
Andy Hungee58e4a2023-07-07 13:47:37 -07001229void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001230{
Andy Hung3f0c9022016-01-15 17:49:46 -08001231 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001232 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001233 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001234 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001235 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001236 }
1237 mWakeLockToken.clear();
1238 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001239}
1240
Andy Hungee58e4a2023-07-07 13:47:37 -07001241void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001242 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001243 // use checkService() to avoid blocking if power service is not up yet
1244 sp<IBinder> binder =
1245 defaultServiceManager()->checkService(String16("power"));
1246 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001247 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001248 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001249 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001250 binder->linkToDeath(mDeathRecipient);
1251 }
1252 }
1253}
1254
Andy Hungee58e4a2023-07-07 13:47:37 -07001255void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001256 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001257
1258#if !LOG_NDEBUG
1259 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001260 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001261 s << uid << " ";
1262 }
1263 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1264#endif
1265
Andy Hung438e7572015-12-14 15:51:17 -08001266 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1267 if (mSystemReady) {
1268 ALOGE("no wake lock to update, but system ready!");
1269 } else {
1270 ALOGW("no wake lock to update, system not ready yet");
1271 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001272 return;
1273 }
1274 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001275 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001276 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1277 mWakeLockToken, uidsAsInt);
1278 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001279 }
1280}
1281
Andy Hungee58e4a2023-07-07 13:47:37 -07001282void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001283{
Andy Hung972bec12023-08-31 16:13:39 -07001284 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001285 releaseWakeLock_l();
1286 mPowerManager.clear();
1287}
1288
Andy Hungee58e4a2023-07-07 13:47:37 -07001289void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001290 const DeviceDescriptorBaseVector& outDevices __unused)
1291{
1292 ALOGE("%s should only be called in RecordThread", __func__);
1293}
1294
Andy Hungee58e4a2023-07-07 13:47:37 -07001295void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001296{
1297 ALOGE("%s should only be called in RecordThread", __func__);
1298}
1299
Andy Hungee58e4a2023-07-07 13:47:37 -07001300void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001301{
1302 sp<ThreadBase> thread = mThread.promote();
1303 if (thread != 0) {
1304 thread->clearPowerManager();
1305 }
1306 ALOGW("power manager service died !!!");
1307}
1308
Andy Hungee58e4a2023-07-07 13:47:37 -07001309void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001310 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001311{
Andy Hung116bc262023-06-20 18:56:17 -07001312 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001313 if (chain != 0) {
1314 if (type != NULL) {
1315 chain->setEffectSuspended_l(type, suspend);
1316 } else {
1317 chain->setEffectSuspendedAll_l(suspend);
1318 }
1319 }
1320
1321 updateSuspendedSessions_l(type, suspend, sessionId);
1322}
1323
Andy Hungee58e4a2023-07-07 13:47:37 -07001324void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001325{
1326 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1327 if (index < 0) {
1328 return;
1329 }
1330
1331 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1332 mSuspendedSessions.valueAt(index);
1333
1334 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001335 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001336 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001337 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001338 chain->setEffectSuspendedAll_l(true);
1339 } else {
1340 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1341 desc->mType.timeLow);
1342 chain->setEffectSuspended_l(&desc->mType, true);
1343 }
1344 }
1345 }
1346}
1347
Andy Hungee58e4a2023-07-07 13:47:37 -07001348void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001349 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001350 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001351{
1352 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1353
1354 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1355
1356 if (suspend) {
1357 if (index >= 0) {
1358 sessionEffects = mSuspendedSessions.valueAt(index);
1359 } else {
1360 mSuspendedSessions.add(sessionId, sessionEffects);
1361 }
1362 } else {
1363 if (index < 0) {
1364 return;
1365 }
1366 sessionEffects = mSuspendedSessions.valueAt(index);
1367 }
1368
1369
Andy Hung116bc262023-06-20 18:56:17 -07001370 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001371 if (type != NULL) {
1372 key = type->timeLow;
1373 }
1374 index = sessionEffects.indexOfKey(key);
1375
1376 sp<SuspendedSessionDesc> desc;
1377 if (suspend) {
1378 if (index >= 0) {
1379 desc = sessionEffects.valueAt(index);
1380 } else {
1381 desc = new SuspendedSessionDesc();
1382 if (type != NULL) {
1383 desc->mType = *type;
1384 }
1385 sessionEffects.add(key, desc);
1386 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1387 }
1388 desc->mRefCount++;
1389 } else {
1390 if (index < 0) {
1391 return;
1392 }
1393 desc = sessionEffects.valueAt(index);
1394 if (--desc->mRefCount == 0) {
1395 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1396 sessionEffects.removeItemsAt(index);
1397 if (sessionEffects.isEmpty()) {
1398 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1399 sessionId);
1400 mSuspendedSessions.removeItem(sessionId);
1401 }
1402 }
1403 }
1404 if (!sessionEffects.isEmpty()) {
1405 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1406 }
1407}
1408
Andy Hungee58e4a2023-07-07 13:47:37 -07001409void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001410 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001411 bool threadLocked)
1412NO_THREAD_SAFETY_ANALYSIS // manual locking
1413{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001414 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001415 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001416 }
Eric Laurent81784c32012-11-19 14:55:58 -08001417
Eric Laurent81784c32012-11-19 14:55:58 -08001418 if (mType != RECORD) {
1419 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1420 // another session. This gives the priority to well behaved effect control panels
1421 // and applications not using global effects.
1422 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1423 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001424 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001425 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1426 }
1427 }
1428
Eric Laurent6b446ce2019-12-13 10:56:31 -08001429 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001430 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001431 }
1432}
1433
Andy Hungc5007f82023-08-29 14:26:09 -07001434// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001435status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001436 const effect_descriptor_t *desc, audio_session_t sessionId)
1437{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001438 // No global output effect sessions on record threads
1439 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1440 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001441 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1442 desc->name, mThreadName);
1443 return BAD_VALUE;
1444 }
1445 // only pre processing effects on record thread
1446 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1447 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1448 desc->name, mThreadName);
1449 return BAD_VALUE;
1450 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001451
1452 // always allow effects without processing load or latency
1453 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1454 return NO_ERROR;
1455 }
1456
Eric Laurent4c415062016-06-17 16:14:16 -07001457 audio_input_flags_t flags = mInput->flags;
1458 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1459 if (flags & AUDIO_INPUT_FLAG_RAW) {
1460 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1461 desc->name, mThreadName);
1462 return BAD_VALUE;
1463 }
1464 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1465 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1466 desc->name, mThreadName);
1467 return BAD_VALUE;
1468 }
1469 }
jiabineb3bda02020-06-30 14:07:03 -07001470
Andy Hung116bc262023-06-20 18:56:17 -07001471 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001472 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1473 return BAD_VALUE;
1474 }
Eric Laurent4c415062016-06-17 16:14:16 -07001475 return NO_ERROR;
1476}
1477
Andy Hungc5007f82023-08-29 14:26:09 -07001478// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001479status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001480 const effect_descriptor_t *desc, audio_session_t sessionId)
1481{
1482 // no preprocessing on playback threads
1483 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001484 ALOGW("%s: pre processing effect %s created on playback"
1485 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001486 return BAD_VALUE;
1487 }
1488
Eric Laurent3e4de772017-07-16 16:55:08 -07001489 // always allow effects without processing load or latency
1490 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1491 return NO_ERROR;
1492 }
1493
Andy Hung116bc262023-06-20 18:56:17 -07001494 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001495 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1496 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001497 return BAD_VALUE;
1498 }
1499
Eric Laurent4eb45d02023-12-20 12:07:17 +01001500 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001501 && mType != SPATIALIZER) {
1502 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1503 __func__, mType);
1504 return BAD_VALUE;
1505 }
1506
Eric Laurent4c415062016-06-17 16:14:16 -07001507 switch (mType) {
1508 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001509 audio_output_flags_t flags = mOutput->flags;
1510 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1511 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1512 // global effects are applied only to non fast tracks if they are SW
1513 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1514 break;
1515 }
1516 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1517 // only post processing on output stage session
1518 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001519 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1520 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001521 return BAD_VALUE;
1522 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001523 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1524 // only post processing on output stage session
1525 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001526 ALOGW("%s: non post processing effect %s not allowed on device session",
1527 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001528 return BAD_VALUE;
1529 }
Eric Laurent4c415062016-06-17 16:14:16 -07001530 } else {
1531 // no restriction on effects applied on non fast tracks
1532 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1533 break;
1534 }
1535 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001536
Eric Laurent4c415062016-06-17 16:14:16 -07001537 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001538 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001539 return BAD_VALUE;
1540 }
1541 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001542 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1543 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001544 return BAD_VALUE;
1545 }
1546 }
1547 } break;
1548 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001549 // nothing actionable on offload threads, if the effect:
1550 // - is offloadable: the effect can be created
1551 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1552 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001553 break;
1554 case DIRECT:
1555 // Reject any effect on Direct output threads for now, since the format of
1556 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001557 ALOGW("%s: effect %s on DIRECT output thread %s",
1558 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001559 return BAD_VALUE;
1560 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001561 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001562 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1563 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001564 return BAD_VALUE;
1565 }
1566 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001567 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1568 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001569 return BAD_VALUE;
1570 }
1571 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001572 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1573 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001574 return BAD_VALUE;
1575 }
1576 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001577 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001578 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1579 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1580 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1581 // are supported and added after the spatializer.
1582 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1583 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1584 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001585 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001586 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1587 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001588 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001589 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1590 break;
1591 }
1592 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1593 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1594 __func__, desc->name);
1595 return BAD_VALUE;
1596 }
1597 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1598 // only post processing on output stage session
1599 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1600 ALOGW("%s: non post processing effect %s not allowed on device session",
1601 __func__, desc->name);
1602 return BAD_VALUE;
1603 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001604 }
1605 break;
jiabinc658e452022-10-21 20:52:21 +00001606 case BIT_PERFECT:
1607 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1608 // Allow HW accelerated effects of tunnel type
1609 break;
1610 }
1611 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1612 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1613 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1614 // 3) there is any bit-perfect track with the given session id.
1615 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1616 sessionId == AUDIO_SESSION_DEVICE) {
1617 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1618 __func__, desc->name, mThreadName);
1619 return BAD_VALUE;
1620 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1621 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1622 __func__, desc->name, sessionId);
1623 return BAD_VALUE;
1624 }
1625 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001626 default:
1627 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1628 }
1629
1630 return NO_ERROR;
1631}
1632
Andy Hungc5007f82023-08-29 14:26:09 -07001633// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001634sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001635 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001636 const sp<IEffectClient>& effectClient,
1637 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001638 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001639 effect_descriptor_t *desc,
1640 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001641 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001642 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001643 bool probe,
1644 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001645{
Andy Hung116bc262023-06-20 18:56:17 -07001646 sp<IAfEffectModule> effect;
1647 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001648 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001649 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001650 bool chainCreated = false;
1651 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001652 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001653
1654 lStatus = initCheck();
1655 if (lStatus != NO_ERROR) {
1656 ALOGW("createEffect_l() Audio driver not initialized.");
1657 goto Exit;
1658 }
1659
Eric Laurent81784c32012-11-19 14:55:58 -08001660 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1661
Andy Hungc5007f82023-08-29 14:26:09 -07001662 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001663 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001664
Eric Laurent4c415062016-06-17 16:14:16 -07001665 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001666 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001667 goto Exit;
1668 }
1669
Eric Laurent81784c32012-11-19 14:55:58 -08001670 // check for existing effect chain with the requested audio session
1671 chain = getEffectChain_l(sessionId);
1672 if (chain == 0) {
1673 // create a new chain for this session
1674 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001675 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001676 addEffectChain_l(chain);
1677 chain->setStrategy(getStrategyForSession_l(sessionId));
1678 chainCreated = true;
1679 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001680 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001681 }
1682
1683 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1684
1685 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001686 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001687 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001688 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001689 if (lStatus != NO_ERROR) {
1690 goto Exit;
1691 }
1692 effectCreated = true;
1693
jiabinc52b1ff2019-10-31 17:20:42 -07001694 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001695 effect->setDevices(outDeviceTypeAddrs());
1696 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001697 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001698 effect->setAudioSource(mAudioSource);
1699 }
jiabin1319f5a2021-03-30 22:21:24 +00001700 if (effect->isHapticGenerator()) {
1701 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1702 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001703 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001704 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001705 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001706 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001707 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001708 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001709 }
1710 }
Eric Laurent81784c32012-11-19 14:55:58 -08001711 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001712 handle = IAfEffectHandle::create(
1713 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001714 lStatus = handle->initCheck();
1715 if (lStatus == OK) {
1716 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001717 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001718 }
Eric Laurent81784c32012-11-19 14:55:58 -08001719 if (enabled != NULL) {
1720 *enabled = (int)effect->isEnabled();
1721 }
1722 }
1723
1724Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001725 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001726 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001727 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001728 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001729 }
Eric Laurent81784c32012-11-19 14:55:58 -08001730 if (chainCreated) {
1731 removeEffectChain_l(chain);
1732 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001733 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001734 }
1735
Glenn Kasten9156ef32013-08-06 15:39:08 -07001736 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001737 return handle;
1738}
1739
Andy Hungee58e4a2023-07-07 13:47:37 -07001740void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001741 bool unpinIfLast)
1742{
1743 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001744 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001745 {
Andy Hung972bec12023-08-31 16:13:39 -07001746 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001747 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001748 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001749 return;
1750 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001751 effect = effectBase->asEffectModule();
1752 if (effect == nullptr) {
1753 return;
1754 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001755 // restore suspended effects if the disconnected handle was enabled and the last one.
1756 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1757 if (remove) {
1758 removeEffect_l(effect, true);
1759 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001760 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001761 }
1762 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001763 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001764 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001765 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001766 }
1767 }
1768}
1769
Andy Hungee58e4a2023-07-07 13:47:37 -07001770void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001771 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001772 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001773 broadcast_l();
1774 }
1775 if (!effect->isOffloadable()) {
1776 if (mType == ThreadBase::OFFLOAD) {
1777 PlaybackThread *t = (PlaybackThread *)this;
1778 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1779 }
1780 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001781 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001782 }
1783 }
1784}
1785
Andy Hungee58e4a2023-07-07 13:47:37 -07001786void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001787 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001788 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001789 broadcast_l();
1790 }
1791}
1792
Andy Hungee58e4a2023-07-07 13:47:37 -07001793sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001794 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001795{
Andy Hung972bec12023-08-31 16:13:39 -07001796 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001797 return getEffect_l(sessionId, effectId);
1798}
1799
Andy Hungee58e4a2023-07-07 13:47:37 -07001800sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001801 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001802{
Andy Hung116bc262023-06-20 18:56:17 -07001803 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001804 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1805}
1806
Andy Hungee58e4a2023-07-07 13:47:37 -07001807std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001808{
Andy Hung116bc262023-06-20 18:56:17 -07001809 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001810 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001811}
1812
Andy Hung972bec12023-08-31 16:13:39 -07001813// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1814// ThreadBase::mutex() held
1815status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001816{
1817 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001818 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001819 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001820 bool chainCreated = false;
1821
Eric Laurent5baf2af2013-09-12 17:37:00 -07001822 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001823 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1824 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001825
Eric Laurent81784c32012-11-19 14:55:58 -08001826 if (chain == 0) {
1827 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001828 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001829 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001830 addEffectChain_l(chain);
1831 chain->setStrategy(getStrategyForSession_l(sessionId));
1832 chainCreated = true;
1833 }
Andy Hung972bec12023-08-31 16:13:39 -07001834 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001835
1836 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001837 ALOGW("%s: %p effect %s already present in chain %p",
1838 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001839 return BAD_VALUE;
1840 }
1841
Shunkai Yaod125e402024-01-20 03:19:06 +00001842 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001843
Shunkai Yao29d10572024-03-19 04:31:47 +00001844 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001845 if (status != NO_ERROR) {
1846 if (chainCreated) {
1847 removeEffectChain_l(chain);
1848 }
1849 return status;
1850 }
1851
jiabin8f278ee2019-11-11 12:16:27 -08001852 effect->setDevices(outDeviceTypeAddrs());
1853 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001854 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001855 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001856
Eric Laurent81784c32012-11-19 14:55:58 -08001857 return NO_ERROR;
1858}
1859
Andy Hungee58e4a2023-07-07 13:47:37 -07001860void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001861
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001862 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001863 effect_descriptor_t desc = effect->desc();
1864 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1865 detachAuxEffect_l(effect->id());
1866 }
1867
Andy Hung116bc262023-06-20 18:56:17 -07001868 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001869 if (chain != 0) {
1870 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001871 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001872 removeEffectChain_l(chain);
1873 }
1874 } else {
1875 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1876 }
1877}
1878
Shunkai Yaof4847652024-01-12 00:25:20 +00001879void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1880 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001881{
1882 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001883 for (const auto& effectChain : effectChains) {
1884 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001885 }
1886}
1887
Shunkai Yaof4847652024-01-12 00:25:20 +00001888void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1889 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001890{
Shunkai Yaof4847652024-01-12 00:25:20 +00001891 for (const auto& effectChain : effectChains) {
1892 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001893 }
1894}
1895
Andy Hungee58e4a2023-07-07 13:47:37 -07001896sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001897{
Andy Hung972bec12023-08-31 16:13:39 -07001898 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001899 return getEffectChain_l(sessionId);
1900}
1901
Andy Hungee58e4a2023-07-07 13:47:37 -07001902sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001903 const
Eric Laurent81784c32012-11-19 14:55:58 -08001904{
1905 size_t size = mEffectChains.size();
1906 for (size_t i = 0; i < size; i++) {
1907 if (mEffectChains[i]->sessionId() == sessionId) {
1908 return mEffectChains[i];
1909 }
1910 }
1911 return 0;
1912}
1913
Andy Hungee58e4a2023-07-07 13:47:37 -07001914void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001915{
Andy Hung972bec12023-08-31 16:13:39 -07001916 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001917 size_t size = mEffectChains.size();
1918 for (size_t i = 0; i < size; i++) {
1919 mEffectChains[i]->setMode_l(mode);
1920 }
1921}
1922
Andy Hungee58e4a2023-07-07 13:47:37 -07001923void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001924{
1925 config->type = AUDIO_PORT_TYPE_MIX;
1926 config->ext.mix.handle = mId;
1927 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001928 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001929 config->channel_mask = mChannelMask;
1930 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1931 AUDIO_PORT_CONFIG_FORMAT;
1932}
1933
Andy Hungee58e4a2023-07-07 13:47:37 -07001934void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001935{
Andy Hung972bec12023-08-31 16:13:39 -07001936 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001937 if (mSystemReady) {
1938 return;
1939 }
1940 mSystemReady = true;
1941
1942 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1943 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1944 }
1945 mPendingConfigEvents.clear();
1946}
1947
Andy Hungdae27702016-10-31 14:01:16 -07001948template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001949ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001950 ssize_t index = mActiveTracks.indexOf(track);
1951 if (index >= 0) {
1952 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1953 return index;
1954 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001955 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001956 mActiveTracksGeneration++;
1957 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001958 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001959 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001960 return mActiveTracks.add(track);
1961}
1962
1963template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001964ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001965 ssize_t index = mActiveTracks.remove(track);
1966 if (index < 0) {
1967 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1968 return index;
1969 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001970 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001971 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001972 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001973 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001974 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001975#ifdef TEE_SINK
1976 track->dumpTee(-1 /* fd */, "_REMOVE");
1977#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001978 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001979 return index;
1980}
1981
1982template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001983void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001984 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001985 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001986 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001987 }
1988 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001989 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001990 mActiveTracks.clear();
1991 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001992}
1993
1994template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001995void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001996 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001997 // Updates ActiveTracks client uids to the thread wakelock.
1998 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1999 thread->updateWakeLockUids_l(getWakeLockUids());
2000 mLastActiveTracksGeneration = mActiveTracksGeneration;
2001 }
Andy Hungdae27702016-10-31 14:01:16 -07002002}
Eric Laurent83b88082014-06-20 18:31:16 -07002003
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002004template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002005bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002006 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002007 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002008
2009 for (const sp<T> &track : mActiveTracks) {
2010 // Do not short-circuit as all hasChanged states must be reset
2011 // as all the metadata are going to be sent
2012 hasChanged |= track->readAndClearHasChanged();
2013 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002014 return hasChanged;
2015}
2016
2017template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002018void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002019 const char *funcName, const sp<T> &track) const {
2020 if (mLocalLog != nullptr) {
2021 String8 result;
2022 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002023 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002024 }
2025}
2026
Andy Hungee58e4a2023-07-07 13:47:37 -07002027void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002028{
2029 // Thread could be blocked waiting for async
2030 // so signal it to handle state changes immediately
2031 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2032 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2033 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002034 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002035}
2036
Andy Hungd0979812019-02-21 15:51:44 -08002037// Call only from threadLoop() or when it is idle.
2038// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002039void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002040NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002041{
2042 // Do not log if we have no stats.
2043 // We choose the timestamp verifier because it is the most likely item to be present.
2044 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2045 if (nstats == 0) {
2046 return;
2047 }
2048
2049 // Don't log more frequently than once per 12 hours.
2050 // We use BOOTTIME to include suspend time.
2051 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2052 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2053 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2054 return;
2055 }
2056
2057 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2058 mLastRecordedTimeNs = timeNs;
2059
Ray Essickf27e9872019-12-07 06:28:46 -08002060 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002061
2062#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2063
2064 // thread configuration
2065 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2066 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2067 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2068 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2069 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2070 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2071 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002072 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2073 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002074
2075 // thread statistics
2076 if (mIoJitterMs.getN() > 0) {
2077 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2078 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2079 }
2080 if (mProcessTimeMs.getN() > 0) {
2081 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2082 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2083 }
2084 const auto tsjitter = mTimestampVerifier.getJitterMs();
2085 if (tsjitter.getN() > 0) {
2086 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2087 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2088 }
2089 if (mLatencyMs.getN() > 0) {
2090 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2091 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2092 }
Robert Wu06db0a32021-08-10 19:05:34 +00002093 if (mMonopipePipeDepthStats.getN() > 0) {
2094 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2095 mMonopipePipeDepthStats.getMean());
2096 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2097 mMonopipePipeDepthStats.getStdDev());
2098 }
Andy Hungd0979812019-02-21 15:51:44 -08002099
2100 item->selfrecord();
2101}
2102
Andy Hungee58e4a2023-07-07 13:47:37 -07002103product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002104{
Andy Hung583043b2023-07-17 17:05:00 -07002105 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002106 return PRODUCT_STRATEGY_NONE;
2107 }
2108 return AudioSystem::getStrategyForStream(stream);
2109}
2110
Andy Hungc5007f82023-08-29 14:26:09 -07002111// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002112void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002113 const sp<audio_utils::MelProcessor>& /*processor*/)
2114{
2115 // Do nothing
2116 ALOGW("%s: ThreadBase does not support CSD", __func__);
2117}
2118
Andy Hungc5007f82023-08-29 14:26:09 -07002119// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002120void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002121{
2122 // Do nothing
2123 ALOGW("%s: ThreadBase does not support CSD", __func__);
2124}
2125
Eric Laurent81784c32012-11-19 14:55:58 -08002126// ----------------------------------------------------------------------------
2127// Playback
2128// ----------------------------------------------------------------------------
2129
Andy Hung583043b2023-07-17 17:05:00 -07002130PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002131 AudioStreamOut* output,
2132 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002133 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002134 bool systemReady,
2135 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002136 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002137 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002138 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002139 mMixerBuffer(NULL),
2140 mMixerBufferSize(0),
2141 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2142 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002143 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002144 mEffectBuffer(NULL),
2145 mEffectBufferSize(0),
2146 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2147 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002148 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002149 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002150 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002151 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002152 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002153 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002154 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002155 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002156 mMixerStatus(MIXER_IDLE),
2157 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002158 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002159 mBytesRemaining(0),
2160 mCurrentWriteLength(0),
2161 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002162 mWriteAckSequence(0),
2163 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002164 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002165 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002166 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002167 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002168 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002169 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002170 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002171{
Glenn Kastend7dca052015-03-05 16:05:54 -08002172 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002173 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002174
Andy Hungc5007f82023-08-29 14:26:09 -07002175 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002176 // it would be safer to explicitly pass initial masterVolume/masterMute as
2177 // parameter.
2178 //
2179 // If the HAL we are using has support for master volume or master mute,
2180 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2181 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002182 mMasterVolume = afThreadCallback->masterVolume_l();
2183 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002184 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002185 if (mOutput->audioHwDev->canSetMasterVolume()) {
2186 mMasterVolume = 1.0;
2187 }
2188
2189 if (mOutput->audioHwDev->canSetMasterMute()) {
2190 mMasterMute = false;
2191 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002192 mIsMsdDevice = strcmp(
2193 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002194 }
2195
Eric Laurentf1f22e72021-07-13 14:04:14 +02002196 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2197 mMixerChannelMask = mixerConfig->channel_mask;
2198 }
2199
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002200 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002201
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002202 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002203 && mMixerChannelMask != mChannelMask) {
2204 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2205 mChannelMask, mMixerChannelMask);
2206 }
2207
Andy Hungc8fddf32018-08-08 18:32:37 -07002208 // TODO: We may also match on address as well as device type for
2209 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002210 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002211 // TODO: This property should be ensure that only contains one single device type.
2212 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2213 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002214 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2215 : AUDIO_DEVICE_NONE));
2216 }
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02002217 if (!audioserver_flags::portid_volume_management()) {
2218 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2219 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2220 mStreamTypes[stream].volume = 0.0f;
2221 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
2222 }
2223 // Audio patch and call assistant volume are always max
2224 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2225 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2226 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2227 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002228 }
Eric Laurent81784c32012-11-19 14:55:58 -08002229}
2230
Andy Hungee58e4a2023-07-07 13:47:37 -07002231PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002232{
Andy Hung583043b2023-07-17 17:05:00 -07002233 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002234 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002235 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002236 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002237 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002238}
2239
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002240// Thread virtuals
2241
Andy Hungee58e4a2023-07-07 13:47:37 -07002242void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002243{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002244 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002245 ALOGE("The stream is not open yet"); // This should not happen.
2246 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002247 // Callbacks take strong or weak pointers as a parameter.
2248 // Since PlaybackThread passes itself as a callback handler, it can only
2249 // be done outside of the constructor. Creating weak and especially strong
2250 // pointers to a refcounted object in its own constructor is strongly
2251 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2252 // Even if a function takes a weak pointer, it is possible that it will
2253 // need to convert it to a strong pointer down the line.
2254 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2255 mOutput->stream->setCallback(this) == OK) {
2256 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002257 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002258 }
2259
jiabinf6eb4c32020-02-25 14:06:25 -08002260 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002261 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002262 }
2263 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002264 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002265 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002266}
2267
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002268// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002269void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002270{
2271 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002272 status_t result = mOutput->stream->exit();
2273 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002274}
2275
Andy Hungee58e4a2023-07-07 13:47:37 -07002276void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002277{
Eric Laurent81784c32012-11-19 14:55:58 -08002278 String8 result;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02002279 if (!audioserver_flags::portid_volume_management()) {
2280 result.appendFormat(" Stream volumes in dB: ");
2281 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2282 const stream_type_t *st = &mStreamTypes[i];
2283 if (i > 0) {
2284 result.appendFormat(", ");
2285 }
2286 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2287 if (st->mute) {
2288 result.append("M");
2289 }
Eric Laurent81784c32012-11-19 14:55:58 -08002290 }
2291 }
2292 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002293 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002294 result.clear();
2295
Eric Laurent81784c32012-11-19 14:55:58 -08002296 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2297 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002298 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002299 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002300
2301 size_t numtracks = mTracks.size();
2302 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002303 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002304 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002305 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002306 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002307 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002308 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002309 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002310 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002311 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002312 if (track != 0) {
2313 bool active = mActiveTracks.indexOf(track) >= 0;
2314 if (active) {
2315 numactiveseen++;
2316 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002317 result.append(prefix);
2318 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002319 }
2320 }
2321 } else {
2322 result.append("\n");
2323 }
2324 if (numactiveseen != numactive) {
2325 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002326 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002327 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002328 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002329 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002330 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002331 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002332 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002333 result.append(prefix);
2334 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002335 }
2336 }
2337 }
2338
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002339 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002340}
2341
Andy Hungee58e4a2023-07-07 13:47:37 -07002342void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002343{
Andy Hung04cb8f72020-03-20 13:44:33 -07002344 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002345 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002346 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2347 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002348 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2349 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2350 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2351 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002352 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002353 dprintf(fd, " Total writes: %d\n", mNumWrites);
2354 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2355 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002356 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002357 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002358 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002359 AudioStreamOut *output = mOutput;
2360 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002361 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002362 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002363 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2364 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2365 if (mPipeSink.get() != nullptr) {
2366 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2367 }
2368 if (output != nullptr) {
2369 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002370 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002371 }
Eric Laurent81784c32012-11-19 14:55:58 -08002372}
2373
Andy Hungc5007f82023-08-29 14:26:09 -07002374// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002375sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002376 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002377 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002378 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002379 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002380 audio_format_t format,
2381 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002382 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002383 size_t *pNotificationFrameCount,
2384 uint32_t notificationsPerBuffer,
2385 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002386 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002387 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002388 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002389 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002390 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002391 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002392 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002393 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002394 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002395 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002396 bool isBitPerfect,
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02002397 audio_output_flags_t *afTrackFlags,
2398 float volume)
Eric Laurent81784c32012-11-19 14:55:58 -08002399{
Glenn Kasten74935e42013-12-19 08:56:45 -08002400 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002401 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002402 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002403 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002404 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002405 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002406 uint32_t sampleRate;
2407
2408 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2409 lStatus = BAD_VALUE;
2410 goto Exit;
2411 }
Eric Laurent21da6472017-11-09 16:29:26 -08002412
2413 if (*pSampleRate == 0) {
2414 *pSampleRate = mSampleRate;
2415 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002416 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002417
2418 // special case for FAST flag considered OK if fast mixer is present
2419 if (hasFastMixer()) {
2420 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2421 }
2422
2423 // Check if requested flags are compatible with output stream flags
2424 if ((*flags & outputFlags) != *flags) {
2425 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2426 *flags, outputFlags);
2427 *flags = (audio_output_flags_t)(*flags & outputFlags);
2428 }
Eric Laurent81784c32012-11-19 14:55:58 -08002429
jiabinc658e452022-10-21 20:52:21 +00002430 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002431 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002432 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002433 if (chain.get() != nullptr) {
2434 // Bit-perfect is required according to the configuration and preferred mixer
2435 // attributes, but it is not in the output flag from the client's request. Explicitly
2436 // adding bit-perfect flag to check the compatibility
2437 audio_output_flags_t flagsToCheck =
2438 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2439 chain->checkOutputFlagCompatibility(&flagsToCheck);
2440 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2441 ALOGE("%s cannot create track as there is data-processing effect attached to "
2442 "given session id(%d)", __func__, sessionId);
2443 lStatus = BAD_VALUE;
2444 goto Exit;
2445 }
2446 *flags = flagsToCheck;
2447 }
2448 }
2449
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002451 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002452 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002453 // PCM data
2454 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002455 // TODO: extract as a data library function that checks that a computationally
2456 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002457 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002458 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2459 (channelMask == AUDIO_CHANNEL_OUT_MONO
2460 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002461 // hardware sample rate
2462 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002463 // normal mixer has an associated fast mixer
2464 hasFastMixer() &&
2465 // there are sufficient fast track slots available
2466 (mFastTrackAvailMask != 0)
2467 // FIXME test that MixerThread for this fast track has a capable output HAL
2468 // FIXME add a permission test also?
2469 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002470 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2471 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002472 // read the fast track multiplier property the first time it is needed
2473 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2474 if (ok != 0) {
2475 ALOGE("%s pthread_once failed: %d", __func__, ok);
2476 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002477 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002478 }
Eric Laurent4c415062016-06-17 16:14:16 -07002479
2480 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002481 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002482 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002483 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002484 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002485 AUDIO_SESSION_OUTPUT_STAGE,
2486 AUDIO_SESSION_OUTPUT_MIX,
2487 sessionId,
2488 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002489 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002490 if (chain.get() != nullptr) {
2491 audio_output_flags_t old = *flags;
2492 chain->checkOutputFlagCompatibility(flags);
2493 if (old != *flags) {
2494 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2495 (int)session, (int)old, (int)*flags);
2496 }
Eric Laurent4c415062016-06-17 16:14:16 -07002497 }
2498 }
2499 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002500 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002501 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2502 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002503 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002504 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002505 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002506 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002507 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002508 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002509 audio_is_linear_pcm(format), channelMask, sampleRate,
2510 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002511 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002512 }
2513 }
Eric Laurent21da6472017-11-09 16:29:26 -08002514
2515 if (!audio_has_proportional_frames(format)) {
2516 if (sharedBuffer != 0) {
2517 // Same comment as below about ignoring frameCount parameter for set()
2518 frameCount = sharedBuffer->size();
2519 } else if (frameCount == 0) {
2520 frameCount = mNormalFrameCount;
2521 }
2522 if (notificationFrameCount != frameCount) {
2523 notificationFrameCount = frameCount;
2524 }
2525 } else if (sharedBuffer != 0) {
2526 // FIXME: Ensure client side memory buffers need
2527 // not have additional alignment beyond sample
2528 // (e.g. 16 bit stereo accessed as 32 bit frame).
2529 size_t alignment = audio_bytes_per_sample(format);
2530 if (alignment & 1) {
2531 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2532 alignment = 1;
2533 }
2534 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2535 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2536 if (channelCount > 1) {
2537 // More than 2 channels does not require stronger alignment than stereo
2538 alignment <<= 1;
2539 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002540 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002541 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002542 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002543 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002544 goto Exit;
2545 }
Eric Laurent21da6472017-11-09 16:29:26 -08002546
2547 // When initializing a shared buffer AudioTrack via constructors,
2548 // there's no frameCount parameter.
2549 // But when initializing a shared buffer AudioTrack via set(),
2550 // there _is_ a frameCount parameter. We silently ignore it.
2551 frameCount = sharedBuffer->size() / frameSize;
2552 } else {
2553 size_t minFrameCount = 0;
2554 // For fast tracks we try to respect the application's request for notifications per buffer.
2555 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2556 if (notificationsPerBuffer > 0) {
2557 // Avoid possible arithmetic overflow during multiplication.
2558 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2559 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2560 notificationsPerBuffer, mFrameCount);
2561 } else {
2562 minFrameCount = mFrameCount * notificationsPerBuffer;
2563 }
2564 }
2565 } else {
2566 // For normal PCM streaming tracks, update minimum frame count.
2567 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2568 // cover audio hardware latency.
2569 // This is probably too conservative, but legacy application code may depend on it.
2570 // If you change this calculation, also review the start threshold which is related.
2571 uint32_t latencyMs = latency_l();
2572 if (latencyMs == 0) {
2573 ALOGE("Error when retrieving output stream latency");
2574 lStatus = UNKNOWN_ERROR;
2575 goto Exit;
2576 }
2577
2578 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2579 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2580
Eric Laurent81784c32012-11-19 14:55:58 -08002581 }
Eric Laurent21da6472017-11-09 16:29:26 -08002582 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002583 frameCount = minFrameCount;
2584 }
Eric Laurent81784c32012-11-19 14:55:58 -08002585 }
Eric Laurent21da6472017-11-09 16:29:26 -08002586
2587 // Make sure that application is notified with sufficient margin before underrun.
2588 // The client can divide the AudioTrack buffer into sub-buffers,
2589 // and expresses its desire to server as the notification frame count.
2590 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2591 size_t maxNotificationFrames;
2592 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2593 // notify every HAL buffer, regardless of the size of the track buffer
2594 maxNotificationFrames = mFrameCount;
2595 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002596 // Triple buffer the notification period for a triple buffered mixer period;
2597 // otherwise, double buffering for the notification period is fine.
2598 //
2599 // TODO: This should be moved to AudioTrack to modify the notification period
2600 // on AudioTrack::setBufferSizeInFrames() changes.
2601 const int nBuffering =
2602 (uint64_t{frameCount} * mSampleRate)
2603 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2604
Eric Laurent21da6472017-11-09 16:29:26 -08002605 maxNotificationFrames = frameCount / nBuffering;
2606 // If client requested a fast track but this was denied, then use the smaller maximum.
2607 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2608 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2609 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2610 maxNotificationFrames = maxNotificationFramesFastDenied;
2611 }
2612 }
2613 }
2614 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2615 if (notificationFrameCount == 0) {
2616 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2617 maxNotificationFrames, frameCount);
2618 } else {
2619 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2620 notificationFrameCount, maxNotificationFrames, frameCount);
2621 }
2622 notificationFrameCount = maxNotificationFrames;
2623 }
2624 }
2625
Glenn Kasten74935e42013-12-19 08:56:45 -08002626 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002627 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002628
Glenn Kastenc3df8382014-03-13 15:05:25 -07002629 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002630 case BIT_PERFECT:
2631 if (isBitPerfect) {
2632 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2633 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2634 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2635 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2636 mChannelMask);
2637 lStatus = BAD_VALUE;
2638 goto Exit;
2639 }
2640 }
2641 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002642
2643 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002644 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002645 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002646 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2647 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002648 sampleRate, format, channelMask, mOutput, mFormat);
2649 lStatus = BAD_VALUE;
2650 goto Exit;
2651 }
2652 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002653 break;
2654
2655 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002656 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002657 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2658 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 sampleRate, format, channelMask, mOutput, mFormat);
2660 lStatus = BAD_VALUE;
2661 goto Exit;
2662 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002663 break;
2664
2665 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002666 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002667 ALOGE("createTrack_l() Bad parameter: format %#x \""
2668 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 format, mOutput, mFormat);
2670 lStatus = BAD_VALUE;
2671 goto Exit;
2672 }
Andy Hungcd044842014-08-07 11:04:34 -07002673 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002674 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2675 lStatus = BAD_VALUE;
2676 goto Exit;
2677 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002678 break;
2679
Eric Laurent81784c32012-11-19 14:55:58 -08002680 }
2681
2682 lStatus = initCheck();
2683 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002684 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002685 goto Exit;
2686 }
2687
Andy Hungc5007f82023-08-29 14:26:09 -07002688 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002689 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002690
2691 // all tracks in same audio session must share the same routing strategy otherwise
2692 // conflicts will happen when tracks are moved from one output to another by audio policy
2693 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002694 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002695 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002696 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002697 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002698 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002699 if (sessionId == t->sessionId() && strategy != actual) {
2700 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2701 strategy, actual);
2702 lStatus = BAD_VALUE;
2703 goto Exit;
2704 }
2705 }
2706 }
2707
Deeraj Soman2b515232024-05-14 12:58:24 +05302708 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2709 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002710 // dynamic audio policy.
2711 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302712 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002713 audio_output_flags_t trackFlags = *flags;
2714 if (mType == DIRECT) {
2715 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302716 } else if (mType == OFFLOAD) {
2717 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2718 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002719 }
jiabin94ed47c2023-07-27 23:34:20 +00002720 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002721
Andy Hung8d31fd22023-06-26 19:20:57 -07002722 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002723 channelMask, frameCount,
2724 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002725 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002726 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02002727 speed, isSpatialized, isBitPerfect, volume);
Glenn Kasten03003332013-08-06 15:40:54 -07002728
Glenn Kasten03003332013-08-06 15:40:54 -07002729 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2730 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002731 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002732 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002733 goto Exit;
2734 }
2735 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002736 {
Andy Hung972bec12023-08-31 16:13:39 -07002737 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002738 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002739 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002740 }
2741 }
Eric Laurent81784c32012-11-19 14:55:58 -08002742
Andy Hung116bc262023-06-20 18:56:17 -07002743 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002744 if (chain != 0) {
2745 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2746 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002747 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002748 chain->incTrackCnt();
2749 }
2750
Eric Laurent05067782016-06-01 18:27:28 -07002751 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002752 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2753 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2754 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002755 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002756 }
2757 }
2758
2759 lStatus = NO_ERROR;
2760
2761Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002762 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002763 return track;
2764}
2765
Andy Hung1bc088a2018-02-09 15:57:31 -08002766template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002767ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002768{
Andy Hungc0691382018-09-12 18:01:57 -07002769 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002770 const ssize_t index = mTracks.remove(track);
2771 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002772 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002773 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002774 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002775 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002776 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002777 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002778 }
2779 return index;
2780}
2781
Andy Hungee58e4a2023-07-07 13:47:37 -07002782uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002783{
2784 return latency;
2785}
2786
Andy Hungee58e4a2023-07-07 13:47:37 -07002787uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002788{
Andy Hung972bec12023-08-31 16:13:39 -07002789 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002790 return latency_l();
2791}
Andy Hungee58e4a2023-07-07 13:47:37 -07002792uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002793NO_THREAD_SAFETY_ANALYSIS
2794// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002795{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002796 uint32_t latency;
2797 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2798 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002799 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002800 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002801}
2802
Andy Hungee58e4a2023-07-07 13:47:37 -07002803void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002804{
Andy Hung972bec12023-08-31 16:13:39 -07002805 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002806 // Don't apply master volume in SW if our HAL can do it for us.
2807 if (mOutput && mOutput->audioHwDev &&
2808 mOutput->audioHwDev->canSetMasterVolume()) {
2809 mMasterVolume = 1.0;
2810 } else {
2811 mMasterVolume = value;
2812 }
2813}
2814
Andy Hungee58e4a2023-07-07 13:47:37 -07002815void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002816{
2817 mMasterBalance.store(balance);
2818}
2819
Andy Hungee58e4a2023-07-07 13:47:37 -07002820void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002821{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002822 if (isDuplicating()) {
2823 return;
2824 }
Andy Hung972bec12023-08-31 16:13:39 -07002825 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002826 // Don't apply master mute in SW if our HAL can do it for us.
2827 if (mOutput && mOutput->audioHwDev &&
2828 mOutput->audioHwDev->canSetMasterMute()) {
2829 mMasterMute = false;
2830 } else {
2831 mMasterMute = muted;
2832 }
2833}
2834
Andy Hungee58e4a2023-07-07 13:47:37 -07002835void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002836{
Andy Hung972bec12023-08-31 16:13:39 -07002837 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002838 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002839 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002840}
2841
Andy Hungee58e4a2023-07-07 13:47:37 -07002842void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002843{
Andy Hung972bec12023-08-31 16:13:39 -07002844 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002845 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002846 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002847}
2848
Andy Hungee58e4a2023-07-07 13:47:37 -07002849float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002850{
Andy Hung972bec12023-08-31 16:13:39 -07002851 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002852 return mStreamTypes[stream].volume;
2853}
2854
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02002855sp<VolumePortInterface> PlaybackThread::getVolumePortInterface(audio_port_handle_t port) const
2856{
2857 audio_utils::lock_guard _l(mutex());
2858 if (port == AUDIO_PORT_HANDLE_NONE) {
2859 return nullptr;
2860 }
2861 for (size_t i = 0; i < mTracks.size(); i++) {
2862 sp<IAfTrack> track = mTracks[i].get();
2863 if (port == track->portId()) {
2864 return track;
2865 }
2866 }
2867 return nullptr;
2868}
2869
Andy Hungee58e4a2023-07-07 13:47:37 -07002870void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002871{
2872 mOutput->stream->setVolume(left, right);
2873}
2874
Andy Hungc5007f82023-08-29 14:26:09 -07002875// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002876status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002877{
2878 status_t status = ALREADY_EXISTS;
2879
Eric Laurent81784c32012-11-19 14:55:58 -08002880 if (mActiveTracks.indexOf(track) < 0) {
2881 // the track is newly added, make sure it fills up all its
2882 // buffers before playing. This is to ensure the client will
2883 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002884 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002885 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002886 // Because the track is not on the ActiveTracks,
2887 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002888 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002889 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002890 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002892 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002894 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002895 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002896 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 }
2898 return INVALID_OPERATION;
2899 }
2900 // abort if start is rejected by audio policy manager
2901 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002902 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2903 // current playback thread is reopened, which may happen when clients set preferred
2904 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2905 // immediately.
2906 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002907 }
2908#ifdef ADD_BATTERY_DATA
2909 // to track the speaker usage
2910 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2911#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002912 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002913 }
2914
Eric Laurent51716182016-02-29 18:00:56 -08002915 // set retry count for buffer fill
2916 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002917 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002918 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002919 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002920 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002921 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002922 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002923 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002924 track->retryCount() = kMaxTrackStartupRetries;
2925 track->fillingStatus() =
2926 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002927 }
2928
Andy Hung116bc262023-06-20 18:56:17 -07002929 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002930 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2931 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002932 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002933 // Unlock due to VibratorService will lock for this call and will
2934 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002935 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002936 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002937 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002938 std::optional<media::AudioVibratorInfo> vibratorInfo;
2939 {
2940 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2941 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002942 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002943 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002944 }
Andy Hungc5007f82023-08-29 14:26:09 -07002945 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002946 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002947 if (vibratorInfo) {
2948 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2949 }
2950
jiabin57303cc2018-12-18 15:45:57 -08002951 // Haptic playback should be enabled by vibrator service.
2952 if (track->getHapticPlaybackEnabled()) {
2953 // Disable haptic playback of all active track to ensure only
2954 // one track playing haptic if current track should play haptic.
2955 for (const auto &t : mActiveTracks) {
2956 t->setHapticPlaybackEnabled(false);
2957 }
jiabin245cdd92018-12-07 17:55:15 -08002958 }
jiabine70bc7f2020-06-30 22:07:55 -07002959
2960 // Set haptic intensity for effect
2961 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002962 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002963 }
jiabin245cdd92018-12-07 17:55:15 -08002964 }
2965
Andy Hung8d31fd22023-06-26 19:20:57 -07002966 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002967 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002968
2969 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2970 // all key changes are complete. It is possible that the threadLoop will begin
2971 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002972 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002973
Eric Laurentd0107bc2013-06-11 14:38:48 -07002974 if (chain != 0) {
2975 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2976 track->sessionId());
2977 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002978 }
2979
Andy Hungc2b11cb2020-04-22 09:04:01 -07002980 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002981 status = NO_ERROR;
2982 }
2983
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002984 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002985 return status;
2986}
2987
Andy Hungee58e4a2023-07-07 13:47:37 -07002988bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002989{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002990 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002991 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002992 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002993 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002994 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002995 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002996 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002997 if (track->isPausePending()) {
2998 track->pauseAck();
2999 }
Andy Hung8d31fd22023-06-26 19:20:57 -07003000 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08003001 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003002
3003 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08003004}
3005
Andy Hungee58e4a2023-07-07 13:47:37 -07003006void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003007{
3008 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08003009
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003010 String8 result;
3011 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003012 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08003013
Eric Laurent81784c32012-11-19 14:55:58 -08003014 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003015 {
Andy Hung972bec12023-08-31 16:13:39 -07003016 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003017 mAudioTrackCallbacks.erase(track);
3018 }
Eric Laurent81784c32012-11-19 14:55:58 -08003019 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003020 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003021 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003022 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3023 mFastTrackAvailMask |= 1 << index;
3024 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003025 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003026 }
Andy Hung116bc262023-06-20 18:56:17 -07003027 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003028 if (chain != 0) {
3029 chain->decTrackCnt();
3030 }
3031}
3032
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003033std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3034{
3035 std::set<int32_t> result;
3036 for (const auto& t : mTracks) {
3037 if (t->isExternalTrack()) {
3038 result.insert(t->portId());
3039 }
3040 }
3041 return result;
3042}
3043
3044std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3045{
3046 audio_utils::lock_guard _l(mutex());
3047 return getTrackPortIds_l();
3048}
3049
Andy Hungee58e4a2023-07-07 13:47:37 -07003050String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003051{
Andy Hung972bec12023-08-31 16:13:39 -07003052 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003053 String8 out_s8;
3054 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3055 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003056 }
Andy Hung920f6572022-10-06 12:09:49 -07003057 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003058}
3059
Andy Hungee58e4a2023-07-07 13:47:37 -07003060status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003061 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003062 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003063 return NO_INIT;
3064 }
3065 return mOutput->stream->selectPresentation(presentationId, programId);
3066}
3067
Andy Hungab65b182023-09-06 19:41:47 -07003068void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003069 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003070 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003071 sp<AudioIoDescriptor> desc;
3072 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003073 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003074 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003075 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003076 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003077 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3078 mSampleRate, mFormat, mChannelMask,
3079 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3080 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003081 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003082 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003083 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003084 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003085 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003086 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003087 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003088 break;
3089 }
Andy Hungab65b182023-09-06 19:41:47 -07003090 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003091}
3092
Andy Hungee58e4a2023-07-07 13:47:37 -07003093void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003095 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003096}
3097
Andy Hungee58e4a2023-07-07 13:47:37 -07003098void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003100 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101}
3102
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003103void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003104{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003105 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003106}
3107
Andy Hungee58e4a2023-07-07 13:47:37 -07003108void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003109 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003110{
Andy Hungee58e4a2023-07-07 13:47:37 -07003111 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003112 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003113 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003114 if (playbackThread == nullptr) {
3115 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3116 return;
3117 }
3118
jiabinf6eb4c32020-02-25 14:06:25 -08003119 audio_utils::metadata::Data metadata =
3120 audio_utils::metadata::dataFromByteString(metadataBs);
3121 if (metadata.empty()) {
3122 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3123 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3124 (int)metadataBs.size());
3125 return;
3126 }
3127
3128 audio_utils::metadata::ByteString metaDataStr =
3129 audio_utils::metadata::byteStringFromData(metadata);
3130 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003131 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003132 for (const auto& callbackPair : mAudioTrackCallbacks) {
3133 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003134 }
3135 }).detach();
3136}
3137
Andy Hungee58e4a2023-07-07 13:47:37 -07003138void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003139{
Andy Hung972bec12023-08-31 16:13:39 -07003140 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003141 // reject out of sequence requests
3142 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3143 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003144 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003145 }
3146}
3147
Andy Hungee58e4a2023-07-07 13:47:37 -07003148void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003149{
Andy Hung972bec12023-08-31 16:13:39 -07003150 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003151 // reject out of sequence requests
3152 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003153 // Register discontinuity when HW drain is completed because that can cause
3154 // the timestamp frame position to reset to 0 for direct and offload threads.
3155 // (Out of sequence requests are ignored, since the discontinuity would be handled
3156 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003157 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003158 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003159 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160 }
3161}
3162
Andy Hungee58e4a2023-07-07 13:47:37 -07003163void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003164NO_THREAD_SAFETY_ANALYSIS
3165// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003166{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003167 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003168 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3169 mSampleRate = audioConfig.sample_rate;
3170 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003171 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003172 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003173 }
Andy Hung81994d62023-07-20 21:44:14 -07003174 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003175 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3176 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003177 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003178
3179 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3180 mMixerChannelMask = mChannelMask;
3181 }
3182
Andy Hunge5412692014-05-16 11:25:07 -07003183 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003184 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003185
Eric Laurentf1f22e72021-07-13 14:04:14 +02003186 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3187
Phil Burkca5e6142015-07-14 09:42:29 -07003188 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003189 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003190 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003191 // Get format from the shim, which will be different than the HAL format
3192 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003193 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003194 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003195 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003196 }
Andy Hung81994d62023-07-20 21:44:14 -07003197 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003198 LOG_FATAL("HAL format %#x not supported for mixed output",
3199 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003200 }
Phil Burk062e67a2015-02-11 13:40:50 -08003201 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003202 result = mOutput->stream->getBufferSize(&mBufferSize);
3203 LOG_ALWAYS_FATAL_IF(result != OK,
3204 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003205 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003206 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003207 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003208 mFrameCount);
3209 }
3210
Eric Laurentd1f69b02014-12-15 14:33:13 -08003211 mHwSupportsPause = false;
3212 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003213 bool supportsPause = false, supportsResume = false;
3214 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3215 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003216 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003217 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003218 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003219 } else if (supportsResume) {
3220 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003221 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003222 }
3223 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003224 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3225 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3226 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003227
Andy Hungfbfc3952015-01-15 13:33:51 -08003228 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3229 // For best precision, we use float instead of the associated output
3230 // device format (typically PCM 16 bit).
3231
3232 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3233 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3234 mBufferSize = mFrameSize * mFrameCount;
3235
3236 // TODO: We currently use the associated output device channel mask and sample rate.
3237 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3238 // (if a valid mask) to avoid premature downmix.
3239 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3240 // instead of the output device sample rate to avoid loss of high frequency information.
3241 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3242 }
3243
Andy Hung09a50072014-02-27 14:30:47 -08003244 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003245 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003246 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003247 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3248 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003249 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3250 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003251
Eric Laurent81784c32012-11-19 14:55:58 -08003252 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3253 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3254 maxNormalFrameCount = maxNormalFrameCount & ~15;
3255 if (maxNormalFrameCount < minNormalFrameCount) {
3256 maxNormalFrameCount = minNormalFrameCount;
3257 }
3258 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3259 if (multiplier <= 1.0) {
3260 multiplier = 1.0;
3261 } else if (multiplier <= 2.0) {
3262 if (2 * mFrameCount <= maxNormalFrameCount) {
3263 multiplier = 2.0;
3264 } else {
3265 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3266 }
3267 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003268 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003269 }
3270 }
3271 mNormalFrameCount = multiplier * mFrameCount;
3272 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003273 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003274 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3275 }
Andy Hungab65b182023-09-06 19:41:47 -07003276 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3277 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003278
Andy Hung08fb1742015-05-31 23:22:10 -07003279 // Check if we want to throttle the processing to no more than 2x normal rate
3280 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003281 mThreadThrottleTimeMs = 0;
3282 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003283 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3284
Andy Hung010a1a12014-03-13 13:57:33 -07003285 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3286 // Originally this was int16_t[] array, need to remove legacy implications.
3287 free(mSinkBuffer);
3288 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003289
Andy Hung5b10a202014-03-13 13:59:29 -07003290 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3291 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3292 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003293 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003294
Andy Hung69aed5f2014-02-25 17:24:40 -08003295 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3296 // drives the output.
3297 free(mMixerBuffer);
3298 mMixerBuffer = NULL;
3299 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003300 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003301 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003302 * audio_bytes_per_sample(mMixerBufferFormat);
3303 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3304 }
Andy Hung98ef9782014-03-04 14:46:50 -08003305 free(mEffectBuffer);
3306 mEffectBuffer = NULL;
3307 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003308 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003309 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003310 * audio_bytes_per_sample(mEffectBufferFormat);
3311 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3312 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003313
Eric Laurentb62d0362021-10-26 17:40:18 +02003314 if (mType == SPATIALIZER) {
3315 free(mPostSpatializerBuffer);
3316 mPostSpatializerBuffer = nullptr;
3317 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3318 * audio_bytes_per_sample(mEffectBufferFormat);
3319 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3320 }
3321
Mikhail Naganov55773032020-10-01 15:08:13 -07003322 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3323 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003324 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3325 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003326 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003327
Eric Laurent81784c32012-11-19 14:55:58 -08003328 // force reconfiguration of effect chains and engines to take new buffer size and audio
3329 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003330 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003331 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3332 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003333 // create a copy of mEffectChains as calling moveEffectChain_ll()
3334 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003335 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003336 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003337 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003338 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003339 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003340
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003341 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003342 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003343 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003344 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003345 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3346 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3347 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3348 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3349 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3350 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3351 (int32_t)mHapticChannelMask)
3352 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3353 (int32_t)mHapticChannelCount)
3354 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003355 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003356 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3357 (int32_t)mFrameCount) // sic - added HAL
3358 ;
3359 uint32_t latencyMs;
3360 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3361 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3362 }
3363 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003364}
3365
Andy Hungee58e4a2023-07-07 13:47:37 -07003366ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003367{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003368 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003369 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003370 }
3371 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003372 static const bool stereo_spatialization_property =
3373 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3374 const bool stereo_spatialization_enabled =
3375 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3376 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003377 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3378 for (const sp<IAfTrack>& track : mActiveTracks) {
3379 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3380 allSessionsMetadata[track->sessionId()];
3381 auto backInserter = std::back_inserter(sessionMetadata);
3382 // No track is invalid as this is called after prepareTrack_l in the same
3383 // critical section
3384 track->copyMetadataTo(backInserter);
3385 }
3386 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3387 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3388 metadata.tracks.insert(metadata.tracks.end(),
3389 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3390 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3391 chain->sendMetadata_l(sessionTrackMetadata, {});
3392 }
3393 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3394 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3395 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3396 }
3397 }
3398 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3399 chain->sendMetadata_l(metadata.tracks, {});
3400 }
3401 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3402 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3403 }
3404 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3405 chain->sendMetadata_l(metadata.tracks, {});
3406 }
3407 } else {
3408 auto backInserter = std::back_inserter(metadata.tracks);
3409 for (const sp<IAfTrack>& track : mActiveTracks) {
3410 // No track is invalid as this is called after prepareTrack_l in the same
3411 // critical section
3412 track->copyMetadataTo(backInserter);
3413 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003414 }
Kevin Rocard12381092018-04-11 09:19:59 -07003415 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003416 MetadataUpdate change;
3417 change.playbackMetadataUpdate = metadata.tracks;
3418 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003419}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003420
Andy Hungee58e4a2023-07-07 13:47:37 -07003421void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003422 const StreamOutHalInterface::SourceMetadata& metadata)
3423{
3424 mOutput->stream->updateSourceMetadata(metadata);
3425};
3426
Andy Hungee58e4a2023-07-07 13:47:37 -07003427status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003428 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003429{
3430 if (halFrames == NULL || dspFrames == NULL) {
3431 return BAD_VALUE;
3432 }
Andy Hung972bec12023-08-31 16:13:39 -07003433 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003434 if (initCheck() != NO_ERROR) {
3435 return INVALID_OPERATION;
3436 }
Andy Hung818e7a32016-02-16 18:08:07 -08003437 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003438 *halFrames = framesWritten;
3439
3440 if (isSuspended()) {
3441 // return an estimation of rendered frames when the output is suspended
3442 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003443 *dspFrames = (uint32_t)
3444 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003445 return NO_ERROR;
3446 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003447 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003448 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003449 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003450 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003451 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003452 }
3453}
3454
Andy Hungee58e4a2023-07-07 13:47:37 -07003455product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003456{
3457 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3458 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3459 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003460 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003461 }
3462 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003463 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003464 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003465 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003466 }
3467 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003468 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003469}
3470
3471
Andy Hungee58e4a2023-07-07 13:47:37 -07003472AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003473{
Andy Hung972bec12023-08-31 16:13:39 -07003474 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003475 return mOutput;
3476}
3477
Andy Hungee58e4a2023-07-07 13:47:37 -07003478AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003479{
Andy Hung972bec12023-08-31 16:13:39 -07003480 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003481 AudioStreamOut *output = mOutput;
3482 mOutput = NULL;
3483 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3484 // must push a NULL and wait for ack
3485 mOutputSink.clear();
3486 mPipeSink.clear();
3487 mNormalSink.clear();
3488 return output;
3489}
3490
Andy Hungc5007f82023-08-29 14:26:09 -07003491// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003492sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003493{
3494 if (mOutput == NULL) {
3495 return NULL;
3496 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003497 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003498}
3499
Andy Hungee58e4a2023-07-07 13:47:37 -07003500uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003501{
3502 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3503}
3504
Andy Hungee58e4a2023-07-07 13:47:37 -07003505status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003506{
3507 if (!isValidSyncEvent(event)) {
3508 return BAD_VALUE;
3509 }
3510
Andy Hung972bec12023-08-31 16:13:39 -07003511 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003512
3513 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003514 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003515 if (event->triggerSession() == track->sessionId()) {
3516 (void) track->setSyncEvent(event);
3517 return NO_ERROR;
3518 }
3519 }
3520
3521 return NAME_NOT_FOUND;
3522}
3523
Andy Hungee58e4a2023-07-07 13:47:37 -07003524bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003525{
3526 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3527}
3528
Andy Hungee58e4a2023-07-07 13:47:37 -07003529void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003530 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003531{
Andy Hungfe726a62018-09-27 15:17:25 -07003532 // Miscellaneous track cleanup when removed from the active list,
3533 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003534#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003535 for (const auto& track : tracksToRemove) {
3536 if (track->isExternalTrack()) {
3537 // to track the speaker usage
3538 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003539 }
3540 }
Andy Hungfe726a62018-09-27 15:17:25 -07003541#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003542}
3543
Andy Hungee58e4a2023-07-07 13:47:37 -07003544void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003545{
3546 if (!mMasterMute) {
3547 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003548 if (mOutDeviceTypeAddrs.empty()) {
3549 ALOGD("ro.audio.silent is ignored since no output device is set");
3550 return;
3551 }
Andy Hungab65b182023-09-06 19:41:47 -07003552 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003553 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3554 return;
3555 }
Eric Laurent81784c32012-11-19 14:55:58 -08003556 if (property_get("ro.audio.silent", value, "0") > 0) {
3557 char *endptr;
3558 unsigned long ul = strtoul(value, &endptr, 0);
3559 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003560 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003561 // The setprop command will not allow a property to be changed after
3562 // the first time it is set, so we don't have to worry about un-muting.
3563 setMasterMute_l(true);
3564 }
3565 }
3566 }
3567}
3568
3569// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003570ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003571{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003572 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003573 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003575 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003576
3577 // If an NBAIO sink is present, use it to write the normal mixer's submix
3578 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003579
Andy Hung010a1a12014-03-13 13:57:33 -07003580 const size_t count = mBytesRemaining / mFrameSize;
3581
Simon Wilson2d590962012-11-29 15:18:50 -08003582 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003583 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003584 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003585 if (screenState != mScreenState) {
3586 mScreenState = screenState;
3587 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3588 if (pipe != NULL) {
3589 pipe->setAvgFrames((mScreenState & 1) ?
3590 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3591 }
3592 }
Andy Hung010a1a12014-03-13 13:57:33 -07003593 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003594 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003595
Eric Laurent81784c32012-11-19 14:55:58 -08003596 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003597 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003598
Andy Hung8946a282018-04-19 20:04:56 -07003599#ifdef TEE_SINK
3600 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3601#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003602 } else {
3603 bytesWritten = framesWritten;
3604 }
3605 // otherwise use the HAL / AudioStreamOut directly
3606 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003607 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003608
Eric Laurentbfb1b832013-01-07 09:53:42 -08003609 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003610 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3611 mWriteAckSequence += 2;
3612 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003613 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003614 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003616 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003617 // FIXME We should have an implementation of timestamps for direct output threads.
3618 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003619 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003620 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003621
Eric Laurentbfb1b832013-01-07 09:53:42 -08003622 if (mUseAsyncWrite &&
3623 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3624 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003625 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003627 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003628 }
Eric Laurent81784c32012-11-19 14:55:58 -08003629 }
3630
Eric Laurent81784c32012-11-19 14:55:58 -08003631 mNumWrites++;
3632 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003633 if (mStandby) {
3634 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003635 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003636 mStandby = false;
3637 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003638 return bytesWritten;
3639}
3640
Andy Hungc5007f82023-08-29 14:26:09 -07003641// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003642void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003643 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003644{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003645 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003646 if (outputSink != nullptr) {
3647 outputSink->startMelComputation(processor);
3648 }
Vlad Popab042ee62022-10-20 18:05:00 +02003649}
3650
Andy Hungc5007f82023-08-29 14:26:09 -07003651// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003652void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003653{
3654 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003655 if (outputSink != nullptr) {
3656 outputSink->stopMelComputation();
3657 }
Vlad Popab042ee62022-10-20 18:05:00 +02003658}
3659
Andy Hungee58e4a2023-07-07 13:47:37 -07003660void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003661{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003662 bool supportsDrain = false;
3663 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003664 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3665 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003666 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3667 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003668 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003669 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003670 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003671 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003672 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003673 }
3674}
3675
Andy Hungee58e4a2023-07-07 13:47:37 -07003676void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003677{
Eric Laurent275e8e92014-11-30 15:14:47 -08003678 {
Andy Hung972bec12023-08-31 16:13:39 -07003679 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003680 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003681 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003682 track->invalidate();
3683 }
Andy Hungdae27702016-10-31 14:01:16 -07003684 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3685 // After we exit there are no more track changes sent to BatteryNotifier
3686 // because that requires an active threadLoop.
3687 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3688 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003689 }
Eric Laurent81784c32012-11-19 14:55:58 -08003690}
3691
3692/*
3693The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003694 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003695 - mActiveSleepTimeUs from activeSleepTimeUs()
3696 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003697 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3698 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003699 - maxPeriod from frame count and sample rate (MIXER only)
3700
3701The parameters that affect these derived values are:
3702 - frame count
3703 - frame size
3704 - sample rate
3705 - device type: A2DP or not
3706 - device latency
3707 - format: PCM or not
3708 - active sleep time
3709 - idle sleep time
3710*/
3711
Andy Hungee58e4a2023-07-07 13:47:37 -07003712void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003713{
Andy Hung25c2dac2014-02-27 14:56:00 -08003714 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003715 mActiveSleepTimeUs = activeSleepTimeUs();
3716 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003717
Andy Hung8fe87eb2023-07-20 21:31:38 -07003718 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003719
Eric Laurent42537be2016-01-08 17:16:42 -08003720 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3721 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003722 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003723 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3724 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3725 }
3726 }
Eric Laurent81784c32012-11-19 14:55:58 -08003727}
3728
Andy Hungee58e4a2023-07-07 13:47:37 -07003729bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003730{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003731 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003732 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003733 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003734 size_t size = mTracks.size();
3735 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003736 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003737 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003738 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003739 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003740 }
3741 }
Eric Laurent13084622016-05-17 10:51:49 -07003742 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003743}
3744
Andy Hungee58e4a2023-07-07 13:47:37 -07003745void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003746{
Andy Hung972bec12023-08-31 16:13:39 -07003747 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003748 invalidateTracks_l(streamType);
3749}
3750
Andy Hungee58e4a2023-07-07 13:47:37 -07003751void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003752 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003753 invalidateTracks_l(portIds);
3754}
3755
Andy Hungee58e4a2023-07-07 13:47:37 -07003756bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003757 bool trackMatch = false;
3758 const size_t size = mTracks.size();
3759 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003760 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003761 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3762 t->invalidate();
3763 portIds.erase(t->portId());
3764 trackMatch = true;
3765 }
3766 if (portIds.empty()) {
3767 break;
3768 }
3769 }
3770 return trackMatch;
3771}
3772
jiabinf042b9b2021-05-07 23:46:28 +00003773// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003774IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003775 audio_port_handle_t trackPortId) {
3776 for (size_t i = 0; i < mTracks.size(); i++) {
3777 if (mTracks[i]->portId() == trackPortId) {
3778 return mTracks[i].get();
3779 }
3780 }
3781 return nullptr;
3782}
3783
Andy Hungee58e4a2023-07-07 13:47:37 -07003784status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003785{
Glenn Kastend848eb42016-03-08 13:42:11 -08003786 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003787 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003788 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003789
Andy Hungd3639922022-04-28 18:00:49 -07003790 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003791 if (!audio_is_global_session(session)) {
3792 // player sessions on a spatializer output will use a dedicated input buffer and
3793 // will either output multi channel to mEffectBuffer if the track is spatilaized
3794 // or stereo to mPostSpatializerBuffer if not spatialized.
3795 uint32_t channelMask;
3796 bool isSessionSpatialized =
3797 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3798 if (isSessionSpatialized) {
3799 channelMask = mMixerChannelMask;
3800 } else {
3801 channelMask = mChannelMask;
3802 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003803 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003804 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003805 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003806 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003807 &halInBuffer);
3808 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003809
Andy Hung583043b2023-07-17 17:05:00 -07003810 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003811 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3812 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3813 &halOutBuffer);
3814 if (result != OK) return result;
3815
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003816 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003817
Mikhail Naganov022b9952017-01-04 16:36:51 -08003818 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3819 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003820 } else {
3821 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3822 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3823 // mPostSpatializerBuffer as output buffer
3824 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003825 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003826 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3827 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003828 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003829 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3830 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003831
Eric Laurentb62d0362021-10-26 17:40:18 +02003832 if (session == AUDIO_SESSION_DEVICE) {
3833 halInBuffer = halOutBuffer;
3834 }
3835 }
3836 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003837 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003838 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3839 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3840 &halInBuffer);
3841 if (result != OK) return result;
3842 halOutBuffer = halInBuffer;
3843 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3844 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003845 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003846 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003847 // Only one effect chain can be present in direct output thread and it uses
3848 // the sink buffer as input
3849 if (mType != DIRECT) {
3850 size_t numSamples = mNormalFrameCount
3851 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3852 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003853 const status_t allocateStatus =
3854 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003855 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003856 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003857 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003858
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003859 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003860 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3861 buffer, session);
3862 }
3863 }
3864 }
3865
3866 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003867 // Attach all tracks with same session ID to this chain.
3868 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003869 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003870 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003871 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3872 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003873 track->setMainBuffer(buffer);
3874 chain->incTrackCnt();
3875 }
3876 }
3877
3878 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003879 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003880 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003881 ALOGV("addEffectChain_l() activating track %p on session %d",
3882 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003883 chain->incActiveTrackCnt();
3884 }
3885 }
3886 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003887
Eric Laurentaaa44472014-09-12 17:41:50 -07003888 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003889 chain->setInBuffer(halInBuffer);
3890 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003891 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3892 // chains list in order to be processed last as it contains output device effects.
3893 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3894 // processing effects specific to an output stream before effects applied to all streams
3895 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003896 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3897 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003898 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003899 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003900 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003901 // Effect chain for other sessions are inserted at beginning of effect
3902 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003903 // sessions is not important.
3904 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003905 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3906 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003907 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003908 size_t size = mEffectChains.size();
3909 size_t i = 0;
3910 for (i = 0; i < size; i++) {
3911 if (mEffectChains[i]->sessionId() < session) {
3912 break;
3913 }
3914 }
3915 mEffectChains.insertAt(chain, i);
3916 checkSuspendOnAddEffectChain_l(chain);
3917
3918 return NO_ERROR;
3919}
3920
Andy Hungee58e4a2023-07-07 13:47:37 -07003921size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003922{
Glenn Kastend848eb42016-03-08 13:42:11 -08003923 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003924
3925 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3926
3927 for (size_t i = 0; i < mEffectChains.size(); i++) {
3928 if (chain == mEffectChains[i]) {
3929 mEffectChains.removeAt(i);
3930 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003931 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003932 if (session == track->sessionId()) {
3933 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3934 chain.get(), session);
3935 chain->decActiveTrackCnt();
3936 }
3937 }
3938
3939 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003940 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003941 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003942 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003943 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003944 chain->decTrackCnt();
3945 }
3946 }
3947 break;
3948 }
3949 }
3950 return mEffectChains.size();
3951}
3952
Andy Hungee58e4a2023-07-07 13:47:37 -07003953status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003954 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003955{
Andy Hung972bec12023-08-31 16:13:39 -07003956 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003957 return attachAuxEffect_l(track, EffectId);
3958}
3959
Andy Hungee58e4a2023-07-07 13:47:37 -07003960status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003961 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003962{
3963 status_t status = NO_ERROR;
3964
3965 if (EffectId == 0) {
3966 track->setAuxBuffer(0, NULL);
3967 } else {
3968 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003969 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003970 if (effect != 0) {
3971 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3972 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3973 } else {
3974 status = INVALID_OPERATION;
3975 }
3976 } else {
3977 status = BAD_VALUE;
3978 }
3979 }
3980 return status;
3981}
3982
Andy Hungee58e4a2023-07-07 13:47:37 -07003983void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003984{
3985 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003986 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003987 if (track->auxEffectId() == effectId) {
3988 attachAuxEffect_l(track, 0);
3989 }
3990 }
3991}
3992
Andy Hungee58e4a2023-07-07 13:47:37 -07003993bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003994NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003995{
Andy Hung78d8d952023-05-30 18:10:23 -07003996 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003997
Andy Hung077d62e2023-10-03 10:49:34 -07003998 if (mType == SPATIALIZER) {
3999 const pid_t tid = getTid();
4000 if (tid == -1) { // odd: we are here, we must be a running thread.
4001 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
4002 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00004003 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4004 if (priorityBoost > 0) {
4005 stream()->setHalThreadPriority(priorityBoost);
4006 }
Andy Hung077d62e2023-10-03 10:49:34 -07004007 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004008 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4009 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4010 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4011 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4012 // only on ARC.
4013 const pid_t tid = getTid();
4014 if (tid == -1) {
4015 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4016 } else {
4017 const status_t status = requestPriority(getpid(),
4018 tid,
4019 kPriorityPlaybackThreadArc,
4020 false /* isForApp */,
4021 true /* asynchronous */);
4022 if (status != OK) {
4023 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4024 status);
4025 } else {
4026 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4027 }
4028 }
Andy Hung077d62e2023-10-03 10:49:34 -07004029 }
4030
Andy Hung8d31fd22023-06-26 19:20:57 -07004031 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004032
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004033 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004034 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004035
4036 // MIXER
4037 nsecs_t lastWarning = 0;
4038
4039 // DUPLICATING
4040 // FIXME could this be made local to while loop?
4041 writeFrames = 0;
4042
4043 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004044 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004045
Andy Hungd3639922022-04-28 18:00:49 -07004046 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004047 sleepTimeShift = 0;
4048 }
4049
4050 CpuStats cpuStats;
4051 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4052
4053 acquireWakeLock();
4054
Glenn Kasteneef598c2017-04-03 14:41:13 -07004055 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4056 // thread associated with this PlaybackThread.
4057 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4058 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004059 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4060 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004061 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004062 const char *logString = NULL;
4063
rago1bb90822017-05-02 18:31:48 -07004064 // Estimated time for next buffer to be written to hal. This is used only on
4065 // suspended mode (for now) to help schedule the wait time until next iteration.
4066 nsecs_t timeLoopNextNs = 0;
4067
Eric Laurent664539d2013-09-23 18:24:31 -07004068 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004069
Andy Hung2dbffc22018-08-08 18:50:41 -07004070 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004071
Eric Laurentb3f315a2021-07-13 15:09:05 +02004072 sendCheckOutputStageEffectsEvent();
4073
Andy Hung446f4df2019-02-21 12:26:41 -08004074 // loopCount is used for statistics and diagnostics.
4075 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004076 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004077 // Log merge requests are performed during AudioFlinger binder transactions, but
4078 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004079 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004080
Eric Laurent81784c32012-11-19 14:55:58 -08004081 cpuStats.sample(myName);
4082
Andy Hung116bc262023-06-20 18:56:17 -07004083 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004084 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004085 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004086 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004087
Andy Hung2dbffc22018-08-08 18:50:41 -07004088 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4089 //
Andy Hungc5007f82023-08-29 14:26:09 -07004090 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004091 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004092 // Here, we try for the AF lock, but do not block on it as the latency
4093 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004094 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004095 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004096 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004097 status_t status = INVALID_OPERATION;
4098 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004099 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004100 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004101 && swPatches.size() > 0) {
4102 status = swPatches[0].getLatencyMs_l(&latencyMs);
4103 downstreamPatchHandle = swPatches[0].getPatchHandle();
4104 }
4105 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004106 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004107 lastDownstreamPatchHandle = downstreamPatchHandle;
4108 }
4109 if (status == OK) {
4110 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004111 // latency of 5 seconds).
4112 const double minLatency = 0., maxLatency = 5000.;
4113 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004114 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004115 } else {
4116 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004117 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004118 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004119 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004120 }
Andy Hung583043b2023-07-17 17:05:00 -07004121 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004122 }
4123 } else {
4124 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4125 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004126 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004127 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4128 }
4129 }
4130
Eric Laurentb3f315a2021-07-13 15:09:05 +02004131 if (mCheckOutputStageEffects.exchange(false)) {
4132 checkOutputStageEffects();
4133 }
4134
Vlad Popa7e81cea2023-01-19 16:34:16 +01004135 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004136 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004137
Andy Hungc5007f82023-08-29 14:26:09 -07004138 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004139
Eric Laurent021cf962014-05-13 10:18:14 -07004140 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004141 if (mCheckOutputStageEffects.load()) {
4142 continue;
4143 }
Eric Laurent10351942014-05-08 18:49:52 -07004144
Andy Hungc5007f82023-08-29 14:26:09 -07004145 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004146 if (logString != NULL) {
4147 mNBLogWriter->logTimestamp();
4148 mNBLogWriter->log(logString);
4149 logString = NULL;
4150 }
4151
Dean Wheatley12473e92021-03-18 23:00:55 +11004152 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004153
Eric Laurent81784c32012-11-19 14:55:58 -08004154 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004155 if (mSignalPending) {
4156 // A signal was raised while we were unlocked
4157 mSignalPending = false;
4158 } else if (waitingAsyncCallback_l()) {
4159 if (exitPending()) {
4160 break;
4161 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004162 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004163 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004164 releaseWakeLock_l();
4165 released = true;
4166 }
Andy Hung10cbff12017-02-21 17:30:14 -08004167
4168 const int64_t waitNs = computeWaitTimeNs_l();
4169 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004170 std::cv_status cvstatus =
4171 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4172 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004173 mSignalPending = true; // if timeout recheck everything
4174 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004175 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004176 if (released) {
4177 acquireWakeLock_l();
4178 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004179 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4180 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004181
4182 continue;
4183 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004184 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004185 isSuspended()) {
4186 // put audio hardware into standby after short delay
4187 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004188
4189 threadLoop_standby();
4190
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004191 // This is where we go into standby
4192 if (!mStandby) {
4193 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004194 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004195 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004196 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004197 }
Andy Hungd0979812019-02-21 15:51:44 -08004198 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004199 }
4200
Eric Tan39ec8d62018-07-24 09:49:29 -07004201 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004202 // we're about to wait, flush the binder command buffer
4203 IPCThreadState::self()->flushCommands();
4204
4205 clearOutputTracks();
4206
4207 if (exitPending()) {
4208 break;
4209 }
4210
4211 releaseWakeLock_l();
4212 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004213 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004214 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004215 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004216 acquireWakeLock_l();
4217
4218 mMixerStatus = MIXER_IDLE;
4219 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4220 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004221 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004222 checkSilentMode_l();
4223
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004224 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4225 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004226 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004227 sleepTimeShift = 0;
4228 }
4229
4230 continue;
4231 }
4232 }
Eric Laurent81784c32012-11-19 14:55:58 -08004233 // mMixerStatusIgnoringFastTracks is also updated internally
4234 mMixerStatus = prepareTracks_l(&tracksToRemove);
4235
Andy Hungab65b182023-09-06 19:41:47 -07004236 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004237
Vlad Popa7e81cea2023-01-19 16:34:16 +01004238 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004239
Andy Hungf302e812024-01-26 11:55:15 -08004240 // Acquire a local copy of active tracks with lock (release w/o lock).
4241 //
4242 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4243 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4244 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4245 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4246
4247 setHalLatencyMode_l();
4248
4249 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4250 // so this is done before we lock our effect chains.
4251 for (const auto& track : mActiveTracks) {
4252 track->updateTeePatches_l();
4253 }
4254
4255 // signal actual start of output stream when the render position reported by
4256 // the kernel starts moving.
4257 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4258 && (mKernelPositionOnStandby
4259 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4260 mHalStarted = true;
4261 mWaitHalStartCV.notify_all();
4262 }
4263
Eric Laurent81784c32012-11-19 14:55:58 -08004264 // prevent any changes in effect chain list and in each effect chain
4265 // during mixing and effect process as the audio buffers could be deleted
4266 // or modified if an effect is created or deleted
4267 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004268
4269 // Determine which session to pick up haptic data.
4270 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004271 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004272 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004273 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004274 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004275 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004276 if (effectChain != nullptr
4277 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004278 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004279 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004280 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004281 break;
4282 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004283 if (activeHapticSessionId == AUDIO_SESSION_NONE
4284 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004285 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004286 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004287 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004288 }
4289 }
4290 }
Andy Hungc5007f82023-08-29 14:26:09 -07004291 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004292
Eric Laurentbfb1b832013-01-07 09:53:42 -08004293 if (mBytesRemaining == 0) {
4294 mCurrentWriteLength = 0;
4295 if (mMixerStatus == MIXER_TRACKS_READY) {
4296 // threadLoop_mix() sets mCurrentWriteLength
4297 threadLoop_mix();
4298 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4299 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004300 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004301 // must be written to HAL
4302 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004303 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004304 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004305
4306 // Tally underrun frames as we are inserting 0s here.
4307 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004308 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004309 && !track->isStopped()
4310 && !track->isPaused()
4311 && !track->isTerminated()) {
4312 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4313 __func__, track->id(), track->getTrackStateAsString(),
4314 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004315 track->audioTrackServerProxy()->tallyUnderrunFrames(
4316 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004317 }
4318 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004319 }
4320 }
Andy Hung98ef9782014-03-04 14:46:50 -08004321 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004322 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004323 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004324 // or mSinkBuffer (if there are no effects and there is no data already copied to
4325 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004326 //
4327 // This is done pre-effects computation; if effects change to
4328 // support higher precision, this needs to move.
4329 //
4330 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004331 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004332 uint32_t mixerChannelCount = mEffectBufferValid ?
4333 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004334 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004335 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4336 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4337
David Li88ee0902022-06-22 10:01:21 +08004338 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4339 // do these processes after effects are applied.
4340 if (!mEffectBufferValid) {
4341 // mono blend occurs for mixer threads only (not direct or offloaded)
4342 // and is handled here if we're going directly to the sink.
4343 if (requireMonoBlend()) {
4344 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4345 mNormalFrameCount, true /*limit*/);
4346 }
Andy Hung2ddee192015-12-18 17:34:44 -08004347
David Li88ee0902022-06-22 10:01:21 +08004348 if (!hasFastMixer()) {
4349 // Balance must take effect after mono conversion.
4350 // We do it here if there is no FastMixer.
4351 // mBalance detects zero balance within the class for speed
4352 // (not needed here).
4353 mBalance.setBalance(mMasterBalance.load());
4354 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4355 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004356 }
4357
Andy Hung98ef9782014-03-04 14:46:50 -08004358 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004359 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004360
4361 // If we're going directly to the sink and there are haptic channels,
4362 // we should adjust channels as the sample data is partially interleaved
4363 // in this case.
4364 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4365 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4366 mChannelCount + mHapticChannelCount,
4367 audio_bytes_per_sample(format),
4368 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4369 }
Andy Hung98ef9782014-03-04 14:46:50 -08004370 }
4371
Eric Laurentbfb1b832013-01-07 09:53:42 -08004372 mBytesRemaining = mCurrentWriteLength;
4373 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004374 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4375 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4376 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4377 mBytesWritten += mBytesRemaining;
4378 mFramesWritten += framesRemaining;
4379 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004380 mBytesRemaining = 0;
4381 }
Eric Laurent81784c32012-11-19 14:55:58 -08004382
Eric Laurentbfb1b832013-01-07 09:53:42 -08004383 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004384 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004385 for (size_t i = 0; i < effectChains.size(); i ++) {
4386 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004387 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004388 if (activeHapticSessionId != AUDIO_SESSION_NONE
4389 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004390 // Haptic data is active in this case, copy it directly from
4391 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004392 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4393 audio_channel_count_from_out_mask(mMixerChannelMask) :
4394 mChannelCount;
4395 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4396 hapticSessionChannelCount = mChannelCount;
4397 }
4398
jiabin47affe52019-04-04 18:02:07 -07004399 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004400 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004401 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004402 memcpy_by_audio_format(
4403 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004404 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004405 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004406 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004407 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004408 }
Eric Laurent81784c32012-11-19 14:55:58 -08004409 }
4410 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004411 // Process effect chains for offloaded thread even if no audio
4412 // was read from audio track: process only updates effect state
4413 // and thus does have to be synchronized with audio writes but may have
4414 // to be called while waiting for async write callback
4415 if (mType == OFFLOAD) {
4416 for (size_t i = 0; i < effectChains.size(); i ++) {
4417 effectChains[i]->process_l();
4418 }
4419 }
Eric Laurent81784c32012-11-19 14:55:58 -08004420
Andy Hung98ef9782014-03-04 14:46:50 -08004421 // Only if the Effects buffer is enabled and there is data in the
4422 // Effects buffer (buffer valid), we need to
4423 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004424 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004425 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004426 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004427 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004428 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004429 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004430 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004431 }
4432
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004433 if (!hasFastMixer()) {
4434 // Balance must take effect after mono conversion.
4435 // We do it here if there is no FastMixer.
4436 // mBalance detects zero balance within the class for speed (not needed here).
4437 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004438 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004439 }
4440
Eric Laurentb62d0362021-10-26 17:40:18 +02004441 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4442 // mPostSpatializerBuffer if the haptics track is spatialized.
4443 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4444 // For other thread types, the haptics channels are already in mEffectBuffer.
4445 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4446 const size_t srcBufferSize = mNormalFrameCount *
4447 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4448 mEffectBufferFormat);
4449 const size_t dstBufferSize = mNormalFrameCount
4450 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4451
4452 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4453 mEffectBufferFormat,
4454 (uint8_t*)mEffectBuffer + srcBufferSize,
4455 mEffectBufferFormat,
4456 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004457 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004458 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4459 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4460 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4461 // Clamp PCM float values more than this distance from 0 to insulate
4462 // a HAL which doesn't handle NaN correctly.
4463 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4464 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4465 static_cast<const float*>(effectBuffer),
4466 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4467 } else {
4468 memcpy_by_audio_format(mSinkBuffer, mFormat,
4469 effectBuffer, mEffectBufferFormat, framesToCopy);
4470 }
jiabin245cdd92018-12-07 17:55:15 -08004471 // The sample data is partially interleaved when haptic channels exist,
4472 // we need to adjust channels here.
4473 if (mHapticChannelCount > 0) {
4474 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4475 mChannelCount + mHapticChannelCount,
4476 audio_bytes_per_sample(mFormat),
4477 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4478 }
Andy Hung98ef9782014-03-04 14:46:50 -08004479 }
4480
Eric Laurent81784c32012-11-19 14:55:58 -08004481 // enable changes in effect chain
4482 unlockEffectChains(effectChains);
4483
Vlad Popafce10862023-02-03 10:37:07 +01004484 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004485 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004486 metadataUpdate.playbackMetadataUpdate);
4487 }
4488
Eric Laurentbfb1b832013-01-07 09:53:42 -08004489 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004490 // mSleepTimeUs == 0 means we must write to audio hardware
4491 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004492 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004493 // writePeriodNs is updated >= 0 when ret > 0.
4494 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004496 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004497 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004498 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004499 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004500 if (ret < 0) {
4501 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004502 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004503 mBytesWritten += ret;
4504 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004505 const int64_t frames = ret / mFrameSize;
4506 mFramesWritten += frames;
4507
4508 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4509 // process information relating to write time.
4510 if (audio_has_proportional_frames(mFormat)) {
4511 // we are in a continuous mixing cycle
4512 if (mMixerStatus == MIXER_TRACKS_READY &&
4513 loopCount == lastLoopCountWritten + 1) {
4514
4515 const double jitterMs =
4516 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4517 {frames, writePeriodNs},
4518 {0, 0} /* lastTimestamp */, mSampleRate);
4519 const double processMs =
4520 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4521
Andy Hung972bec12023-08-31 16:13:39 -07004522 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004523 mIoJitterMs.add(jitterMs);
4524 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004525
4526 if (mPipeSink.get() != nullptr) {
4527 // Using the Monopipe availableToWrite, we estimate the current
4528 // buffer size.
4529 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4530 const ssize_t
4531 availableToWrite = mPipeSink->availableToWrite();
4532 const size_t pipeFrames = monoPipe->maxFrames();
4533 const size_t
4534 remainingFrames = pipeFrames - max(availableToWrite, 0);
4535 mMonopipePipeDepthStats.add(remainingFrames);
4536 }
Andy Hung446f4df2019-02-21 12:26:41 -08004537 }
4538
4539 // write blocked detection
4540 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004541 if ((mType == MIXER || mType == SPATIALIZER)
4542 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004543 mNumDelayedWrites++;
4544 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4545 ATRACE_NAME("underrun");
4546 ALOGW("write blocked for %lld msecs, "
4547 "%d delayed writes, thread %d",
4548 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4549 mNumDelayedWrites, mId);
4550 lastWarning = lastIoEndNs;
4551 }
4552 }
4553 }
4554 // update timing info.
4555 mLastIoBeginNs = lastIoBeginNs;
4556 mLastIoEndNs = lastIoEndNs;
4557 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004558 }
4559 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4560 (mMixerStatus == MIXER_DRAIN_ALL)) {
4561 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004562 }
Andy Hungd3639922022-04-28 18:00:49 -07004563 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004564
4565 if (mThreadThrottle
4566 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004567 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004568 // Limit MixerThread data processing to no more than twice the
4569 // expected processing rate.
4570 //
4571 // This helps prevent underruns with NuPlayer and other applications
4572 // which may set up buffers that are close to the minimum size, or use
4573 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4574 //
4575 // The throttle smooths out sudden large data drains from the device,
4576 // e.g. when it comes out of standby, which often causes problems with
4577 // (1) mixer threads without a fast mixer (which has its own warm-up)
4578 // (2) minimum buffer sized tracks (even if the track is full,
4579 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004580 //
4581 // Total time spent in last processing cycle equals time spent in
4582 // 1. threadLoop_write, as well as time spent in
4583 // 2. threadLoop_mix (significant for heavy mixing, especially
4584 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004585
Andy Hung446f4df2019-02-21 12:26:41 -08004586 // it's OK if deltaMs is an overestimate.
4587
4588 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004589
Ivan Lozanoea04d392017-11-07 14:37:07 -08004590 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004591 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004592 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004593
Andy Hung08fb1742015-05-31 23:22:10 -07004594 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004595 // notify of throttle start on verbose log
4596 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4597 "mixer(%p) throttle begin:"
4598 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004599 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004600 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004601 // Throttle must be attributed to the previous mixer loop's write time
4602 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004603 // This also ensures proper timing statistics.
4604 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004605 } else {
4606 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4607 if (diff > 0) {
4608 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004609 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004610 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004611 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004612 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004613 outDeviceTypes_l(),
4614 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004615 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004616 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4617 }
Andy Hung08fb1742015-05-31 23:22:10 -07004618 }
4619 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004620 }
Eric Laurent81784c32012-11-19 14:55:58 -08004621
Eric Laurentbfb1b832013-01-07 09:53:42 -08004622 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004623 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004624 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004625 // suspended requires accurate metering of sleep time.
4626 if (isSuspended()) {
4627 // advance by expected sleepTime
4628 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4629 const nsecs_t nowNs = systemTime();
4630
4631 // compute expected next time vs current time.
4632 // (negative deltas are treated as delays).
4633 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4634 if (deltaNs < -kMaxNextBufferDelayNs) {
4635 // Delays longer than the max allowed trigger a reset.
4636 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4637 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4638 timeLoopNextNs = nowNs + deltaNs;
4639 } else if (deltaNs < 0) {
4640 // Delays within the max delay allowed: zero the delta/sleepTime
4641 // to help the system catch up in the next iteration(s)
4642 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4643 deltaNs = 0;
4644 }
4645 // update sleep time (which is >= 0)
4646 mSleepTimeUs = deltaNs / 1000;
4647 }
Eric Laurente93cc032016-05-05 10:15:10 -07004648 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004649 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004650 }
Glenn Kastene7754022014-10-31 12:11:26 -07004651 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004652 }
Eric Laurent81784c32012-11-19 14:55:58 -08004653 }
4654
4655 // Finally let go of removed track(s), without the lock held
4656 // since we can't guarantee the destructors won't acquire that
4657 // same lock. This will also mutate and push a new fast mixer state.
4658 threadLoop_removeTracks(tracksToRemove);
4659 tracksToRemove.clear();
4660
4661 // FIXME I don't understand the need for this here;
4662 // it was in the original code but maybe the
4663 // assignment in saveOutputTracks() makes this unnecessary?
4664 clearOutputTracks();
4665
4666 // Effect chains will be actually deleted here if they were removed from
4667 // mEffectChains list during mixing or effects processing
4668 effectChains.clear();
4669
4670 // FIXME Note that the above .clear() is no longer necessary since effectChains
4671 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004672
4673 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004674 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004675 mThreadloopExecutor.process(); // process any remaining deferred actions.
4676 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004677
Eric Laurentbfb1b832013-01-07 09:53:42 -08004678 threadLoop_exit();
4679
Eric Laurentcf817a22014-08-04 20:36:31 -07004680 if (!mStandby) {
4681 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004682 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004683 }
4684
4685 releaseWakeLock();
4686
4687 ALOGV("Thread %p type %d exiting", this, mType);
4688 return false;
4689}
4690
Andy Hungee58e4a2023-07-07 13:47:37 -07004691void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004692{
Dean Wheatley12473e92021-03-18 23:00:55 +11004693 if (mStandby) {
4694 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4695 return;
4696 } else if (mHwPaused) {
4697 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4698 return;
4699 }
4700
4701 // Gather the framesReleased counters for all active tracks,
4702 // and associate with the sink frames written out. We need
4703 // this to convert the sink timestamp to the track timestamp.
4704 bool kernelLocationUpdate = false;
4705 ExtendedTimestamp timestamp; // use private copy to fetch
4706
4707 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4708 // HAL may be draining some small duration buffered data for fade out.
4709 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4710 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4711 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4712 mSampleRate);
4713
Andy Hungab65b182023-09-06 19:41:47 -07004714 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004715 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4716 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4717 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4718 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4719 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4720 = correctedTimestamp.mFrames;
4721 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4722 = correctedTimestamp.mTimeNs;
4723 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4724 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4725 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4726
4727 // Note: Downstream latency only added if timestamp correction enabled.
4728 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4729 const int64_t newPosition =
4730 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4731 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4732 // prevent retrograde
4733 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4734 newPosition,
4735 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4736 - mSuspendedFrames));
4737 }
4738 }
4739
4740 // We always fetch the timestamp here because often the downstream
4741 // sink will block while writing.
4742
4743 // We keep track of the last valid kernel position in case we are in underrun
4744 // and the normal mixer period is the same as the fast mixer period, or there
4745 // is some error from the HAL.
4746 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4747 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4748 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4749 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4750 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4751
4752 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4753 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4754 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4755 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4756 }
4757
4758 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4759 kernelLocationUpdate = true;
4760 } else {
4761 ALOGVV("getTimestamp error - no valid kernel position");
4762 }
4763
4764 // copy over kernel info
4765 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4766 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4767 + mSuspendedFrames; // add frames discarded when suspended
4768 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4769 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4770 } else {
4771 mTimestampVerifier.error();
4772 }
4773
4774 // mFramesWritten for non-offloaded tracks are contiguous
4775 // even after standby() is called. This is useful for the track frame
4776 // to sink frame mapping.
4777 bool serverLocationUpdate = false;
4778 if (mFramesWritten != mLastFramesWritten) {
4779 serverLocationUpdate = true;
4780 mLastFramesWritten = mFramesWritten;
4781 }
4782 // Only update timestamps if there is a meaningful change.
4783 // Either the kernel timestamp must be valid or we have written something.
4784 if (kernelLocationUpdate || serverLocationUpdate) {
4785 if (serverLocationUpdate) {
4786 // use the time before we called the HAL write - it is a bit more accurate
4787 // to when the server last read data than the current time here.
4788 //
4789 // If we haven't written anything, mLastIoBeginNs will be -1
4790 // and we use systemTime().
4791 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4792 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004793 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004794 }
4795
Andy Hung8d31fd22023-06-26 19:20:57 -07004796 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004797 if (!t->isFastTrack()) {
4798 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004799 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004800 mFramesWritten,
4801 mSampleRate,
4802 mTimestamp);
4803 }
4804 }
4805 }
4806
4807 if (audio_has_proportional_frames(mFormat)) {
4808 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4809 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4810 mLatencyMs.add(latencyMs);
4811 }
4812 }
4813#if 0
4814 // logFormat example
4815 if (z % 100 == 0) {
4816 timespec ts;
4817 clock_gettime(CLOCK_MONOTONIC, &ts);
4818 LOGT("This is an integer %d, this is a float %f, this is my "
4819 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4820 LOGT("A deceptive null-terminated string %\0");
4821 }
4822 ++z;
4823#endif
4824}
4825
Andy Hungc5007f82023-08-29 14:26:09 -07004826// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004827void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004828NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004829{
Andy Hung6c498e92023-12-05 17:28:17 -08004830 if (tracksToRemove.empty()) return;
4831
4832 // Block all incoming TrackHandle requests until we are finished with the release.
4833 setThreadBusy_l(true);
4834
Andy Hungfe726a62018-09-27 15:17:25 -07004835 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004836 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004837 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004838 if (chain != 0) {
4839 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4840 __func__, track->id(), chain.get(), track->sessionId());
4841 chain->decActiveTrackCnt();
4842 }
Andy Hung6c498e92023-12-05 17:28:17 -08004843
Andy Hungfe726a62018-09-27 15:17:25 -07004844 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004845 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004846 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004847 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004848 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004849 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004850 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004851 }
Andy Hung6c498e92023-12-05 17:28:17 -08004852 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004853 }
jiabineb3bda02020-06-30 14:07:03 -07004854 if (mHapticChannelCount > 0 &&
4855 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004856 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004857 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004858 // Unlock due to VibratorService will lock for this call and will
4859 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004860 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004861 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004862
4863 // When the track is stop, set the haptic intensity as MUTE
4864 // for the HapticGenerator effect.
4865 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004866 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004867 }
jiabin245cdd92018-12-07 17:55:15 -08004868 }
Andy Hung6c498e92023-12-05 17:28:17 -08004869
4870 // Under lock, the track is removed from the active tracks list.
4871 //
4872 // Once the track is no longer active, the TrackHandle may directly
4873 // modify it as the threadLoop() is no longer responsible for its maintenance.
4874 // Do not modify the track from threadLoop after the mutex is unlocked
4875 // if it is not active.
4876 mActiveTracks.remove(track);
4877
4878 if (track->isTerminated()) {
4879 // remove from our tracks vector
4880 removeTrack_l(track);
4881 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004882 }
Andy Hung6c498e92023-12-05 17:28:17 -08004883
4884 // Allow incoming TrackHandle requests. We still hold the mutex,
4885 // so pending TrackHandle requests will occur after we unlock it.
4886 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004887}
Eric Laurent81784c32012-11-19 14:55:58 -08004888
Andy Hungee58e4a2023-07-07 13:47:37 -07004889status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004890{
4891 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004892 ExtendedTimestamp ets;
4893 status_t status = mNormalSink->getTimestamp(ets);
4894 if (status == NO_ERROR) {
4895 status = ets.getBestTimestamp(&timestamp);
4896 }
4897 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004898 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004899 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004900 collectTimestamps_l();
4901 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4902 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004903 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004904 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4905 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4906 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4907 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4908 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004909 }
4910 return INVALID_OPERATION;
4911}
Eric Laurent1c333e22014-05-20 10:48:17 -07004912
Eric Laurenteab90452019-06-24 15:17:46 -07004913// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4914// still applied by the mixer.
4915// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4916// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4917// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004918status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004919{
4920 status_t result = NO_ERROR;
4921 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4922 if (*volume != mLeftVolFloat) {
4923 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004924 // HAL can return INVALID_OPERATION if operation is not supported.
4925 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004926 "Error when setting output stream volume: %d", result);
4927 if (result == NO_ERROR) {
4928 mLeftVolFloat = *volume;
4929 }
4930 }
4931 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4932 // remove stream volume contribution from software volume.
4933 if (mLeftVolFloat == *volume) {
4934 *volume = 1.0f;
4935 }
4936 }
4937 return result;
4938}
4939
Andy Hungee58e4a2023-07-07 13:47:37 -07004940status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004941 audio_patch_handle_t *handle)
4942{
Andy Hungf60abce2016-08-26 11:37:54 -07004943 status_t status;
4944 if (property_get_bool("af.patch_park", false /* default_value */)) {
4945 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4946 // or if HAL does not properly lock against access.
4947 AutoPark<FastMixer> park(mFastMixer);
4948 status = PlaybackThread::createAudioPatch_l(patch, handle);
4949 } else {
4950 status = PlaybackThread::createAudioPatch_l(patch, handle);
4951 }
Eric Laurentb0463942022-12-20 16:31:10 +01004952
4953 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004954 return status;
4955}
4956
Andy Hungee58e4a2023-07-07 13:47:37 -07004957status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004958 audio_patch_handle_t *handle)
4959{
4960 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004961
4962 // store new device and send to effects
4963 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004964 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004965 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004966 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4967 && !mOutput->audioHwDev->supportsAudioPatches(),
4968 "Enumerated device type(%#x) must not be used "
4969 "as it does not support audio patches",
4970 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004971 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004972 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4973 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004974 }
4975
François Gaffie0c280aa2018-07-25 10:02:15 +02004976 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004977#ifdef ADD_BATTERY_DATA
4978 // when changing the audio output device, call addBatteryData to notify
4979 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004980 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004981 uint32_t params = 0;
4982 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004983 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004984 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 }
4986
Eric Laurent054d9d32015-04-24 08:48:48 -07004987 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004988 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004989 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4990 }
4991
4992 if (params != 0) {
4993 addBatteryData(params);
4994 }
4995 }
4996#endif
4997
4998 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004999 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07005000 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07005001
jiabinc52b1ff2019-10-31 17:20:42 -07005002 // mPatch.num_sinks is not set when the thread is created so that
5003 // the first patch creation triggers an ioConfigChanged callback
5004 bool configChanged = (mPatch.num_sinks == 0) ||
5005 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005006 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005007 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005008 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005009
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005010 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005011 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5012 status = hwDevice->createAudioPatch(patch->num_sources,
5013 patch->sources,
5014 patch->num_sinks,
5015 patch->sinks,
5016 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005017 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005018 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005019 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005020 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005021 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005022
5023 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005024 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005025 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005026 // also dispatch to active AudioTracks for MediaMetrics
5027 for (const auto &track : mActiveTracks) {
5028 track->logEndInterval();
5029 track->logBeginInterval(patchSinksAsString);
5030 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005031
Eric Laurente8726fe2015-06-26 09:39:24 -07005032 if (configChanged) {
5033 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5034 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005035 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005036 mActiveTracks.setHasChanged();
5037
Eric Laurent1c333e22014-05-20 10:48:17 -07005038 return status;
5039}
5040
Andy Hungee58e4a2023-07-07 13:47:37 -07005041status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005042{
Andy Hungf60abce2016-08-26 11:37:54 -07005043 status_t status;
5044 if (property_get_bool("af.patch_park", false /* default_value */)) {
5045 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5046 // or if HAL does not properly lock against access.
5047 AutoPark<FastMixer> park(mFastMixer);
5048 status = PlaybackThread::releaseAudioPatch_l(handle);
5049 } else {
5050 status = PlaybackThread::releaseAudioPatch_l(handle);
5051 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005052 return status;
5053}
5054
Andy Hungee58e4a2023-07-07 13:47:37 -07005055status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005056{
5057 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005058
jiabinc52b1ff2019-10-31 17:20:42 -07005059 mPatch = audio_patch{};
5060 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005061
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005062 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005063 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5064 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005065 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005066 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005067 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005068 // Force meteadata update after a route change
5069 mActiveTracks.setHasChanged();
5070
Eric Laurent1c333e22014-05-20 10:48:17 -07005071 return status;
5072}
5073
Andy Hungee58e4a2023-07-07 13:47:37 -07005074void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005075{
Andy Hung972bec12023-08-31 16:13:39 -07005076 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005077 mTracks.add(track);
5078}
5079
Andy Hungee58e4a2023-07-07 13:47:37 -07005080void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005081{
Andy Hung972bec12023-08-31 16:13:39 -07005082 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005083 destroyTrack_l(track);
5084}
5085
Andy Hungee58e4a2023-07-07 13:47:37 -07005086void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005087{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005088 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005089 config->role = AUDIO_PORT_ROLE_SOURCE;
5090 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5091 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005092 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5093 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5094 config->flags.output = mOutput->flags;
5095 }
Eric Laurent83b88082014-06-20 18:31:16 -07005096}
5097
Eric Laurent81784c32012-11-19 14:55:58 -08005098// ----------------------------------------------------------------------------
5099
Andy Hungee58e4a2023-07-07 13:47:37 -07005100/* static */
5101sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005102 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005103 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005104 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005105}
5106
Andy Hung583043b2023-07-17 17:05:00 -07005107MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005108 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005109 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005110 // mAudioMixer below
5111 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005112 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005113 mFastMixerFutex(0),
5114 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005115 // mOutputSink below
5116 // mPipeSink below
5117 // mNormalSink below
5118{
jiabinc52b1ff2019-10-31 17:20:42 -07005119 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005120 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005121 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005122 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5123 mNormalFrameCount);
5124 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5125
Andy Hungfbfc3952015-01-15 13:33:51 -08005126 if (type == DUPLICATING) {
5127 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5128 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5129 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005130 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5131 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005132 return;
5133 }
Eric Laurent81784c32012-11-19 14:55:58 -08005134 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005135 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005136 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005137 const NBAIO_Format offers[1] = {Format_from_SR_C(
5138 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005139#if !LOG_NDEBUG
5140 ssize_t index =
5141#else
5142 (void)
5143#endif
5144 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005145 ALOG_ASSERT(index == 0);
5146
5147 // initialize fast mixer depending on configuration
5148 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005149 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005150 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005151 } else {
5152 switch (kUseFastMixer) {
5153 case FastMixer_Never:
5154 initFastMixer = false;
5155 break;
5156 case FastMixer_Always:
5157 initFastMixer = true;
5158 break;
5159 case FastMixer_Static:
5160 case FastMixer_Dynamic:
5161 initFastMixer = mFrameCount < mNormalFrameCount;
5162 break;
5163 }
5164 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5165 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5166 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005167 }
5168 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005169 audio_format_t fastMixerFormat;
5170 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5171 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5172 } else {
5173 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5174 }
5175 if (mFormat != fastMixerFormat) {
5176 // change our Sink format to accept our intermediate precision
5177 mFormat = fastMixerFormat;
5178 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005179 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005180 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5181 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5182 }
Eric Laurent81784c32012-11-19 14:55:58 -08005183
5184 // create a MonoPipe to connect our submix to FastMixer
5185 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005186
Andy Hung1258c1a2014-05-23 21:22:17 -07005187 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005188 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005189 format.mFormat = fastMixerFormat;
5190 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5191
Eric Laurent81784c32012-11-19 14:55:58 -08005192 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5193 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5194 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5195 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005196 const NBAIO_Format offersFast[1] = {format};
5197 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005198#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005199 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005200#else
5201 (void)
5202#endif
Andy Hung920f6572022-10-06 12:09:49 -07005203 monoPipe->negotiate(offersFast, std::size(offersFast),
5204 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005205 ALOG_ASSERT(index == 0);
5206 monoPipe->setAvgFrames((mScreenState & 1) ?
5207 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5208 mPipeSink = monoPipe;
5209
Eric Laurent81784c32012-11-19 14:55:58 -08005210 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005211 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005212 FastMixerStateQueue *sq = mFastMixer->sq();
5213#ifdef STATE_QUEUE_DUMP
5214 sq->setObserverDump(&mStateQueueObserverDump);
5215 sq->setMutatorDump(&mStateQueueMutatorDump);
5216#endif
5217 FastMixerState *state = sq->begin();
5218 FastTrack *fastTrack = &state->mFastTracks[0];
5219 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5220 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5221 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005222 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5223 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5224 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005225 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005226 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005227 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005228 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005229 fastTrack->mGeneration++;
5230 state->mFastTracksGen++;
5231 state->mTrackMask = 1;
5232 // fast mixer will use the HAL output sink
5233 state->mOutputSink = mOutputSink.get();
5234 state->mOutputSinkGen++;
5235 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005236 // specify sink channel mask when haptic channel mask present as it can not
5237 // be calculated directly from channel count
5238 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005239 ? AUDIO_CHANNEL_NONE
5240 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005241 state->mCommand = FastMixerState::COLD_IDLE;
5242 // already done in constructor initialization list
5243 //mFastMixerFutex = 0;
5244 state->mColdFutexAddr = &mFastMixerFutex;
5245 state->mColdGen++;
5246 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005247 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005248 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005249 sq->end();
5250 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5251
Eric Tan0513b5d2018-09-17 10:32:48 -07005252 NBLog::thread_info_t info;
5253 info.id = mId;
5254 info.type = NBLog::FASTMIXER;
5255 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5256
Eric Laurent81784c32012-11-19 14:55:58 -08005257 // start the fast mixer
5258 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5259 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005260 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005261 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005262
5263#ifdef AUDIO_WATCHDOG
5264 // create and start the watchdog
5265 mAudioWatchdog = new AudioWatchdog();
5266 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5267 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5268 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005269 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005270#endif
Andy Hung8946a282018-04-19 20:04:56 -07005271 } else {
5272#ifdef TEE_SINK
5273 // Only use the MixerThread tee if there is no FastMixer.
5274 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5275 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5276#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005277 }
5278
5279 switch (kUseFastMixer) {
5280 case FastMixer_Never:
5281 case FastMixer_Dynamic:
5282 mNormalSink = mOutputSink;
5283 break;
5284 case FastMixer_Always:
5285 mNormalSink = mPipeSink;
5286 break;
5287 case FastMixer_Static:
5288 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5289 break;
5290 }
Andy Hung922617c2024-06-25 17:07:58 -07005291 // setMasterBalance needs to be called after the FastMixer
5292 // (if any) is set up, in order to deliver the balance settings to it.
5293 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005294}
5295
Andy Hungee58e4a2023-07-07 13:47:37 -07005296MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005297{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005298 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005299 FastMixerStateQueue *sq = mFastMixer->sq();
5300 FastMixerState *state = sq->begin();
5301 if (state->mCommand == FastMixerState::COLD_IDLE) {
5302 int32_t old = android_atomic_inc(&mFastMixerFutex);
5303 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005304 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005305 }
5306 }
5307 state->mCommand = FastMixerState::EXIT;
5308 sq->end();
5309 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5310 mFastMixer->join();
5311 // Though the fast mixer thread has exited, it's state queue is still valid.
5312 // We'll use that extract the final state which contains one remaining fast track
5313 // corresponding to our sub-mix.
5314 state = sq->begin();
5315 ALOG_ASSERT(state->mTrackMask == 1);
5316 FastTrack *fastTrack = &state->mFastTracks[0];
5317 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5318 delete fastTrack->mBufferProvider;
5319 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005320 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005321#ifdef AUDIO_WATCHDOG
5322 if (mAudioWatchdog != 0) {
5323 mAudioWatchdog->requestExit();
5324 mAudioWatchdog->requestExitAndWait();
5325 mAudioWatchdog.clear();
5326 }
5327#endif
5328 }
Andy Hung583043b2023-07-17 17:05:00 -07005329 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005330 delete mAudioMixer;
5331}
5332
Andy Hungee58e4a2023-07-07 13:47:37 -07005333void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005334 PlaybackThread::onFirstRef();
5335
Andy Hung972bec12023-08-31 16:13:39 -07005336 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005337 if (mOutput != nullptr && mOutput->stream != nullptr) {
5338 status_t status = mOutput->stream->setLatencyModeCallback(this);
5339 if (status != INVALID_OPERATION) {
5340 updateHalSupportedLatencyModes_l();
5341 }
5342 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5343 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5344 mBluetoothLatencyModesEnabled.store(
5345 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5346 }
5347}
Eric Laurent81784c32012-11-19 14:55:58 -08005348
Andy Hungee58e4a2023-07-07 13:47:37 -07005349uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005350{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005351 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005352 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5353 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5354 }
5355 return latency;
5356}
5357
Andy Hungee58e4a2023-07-07 13:47:37 -07005358ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005359{
5360 // FIXME we should only do one push per cycle; confirm this is true
5361 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005362 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005363 FastMixerStateQueue *sq = mFastMixer->sq();
5364 FastMixerState *state = sq->begin();
5365 if (state->mCommand != FastMixerState::MIX_WRITE &&
5366 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5367 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005368
5369 // FIXME workaround for first HAL write being CPU bound on some devices
5370 ATRACE_BEGIN("write");
5371 mOutput->write((char *)mSinkBuffer, 0);
5372 ATRACE_END();
5373
Eric Laurent81784c32012-11-19 14:55:58 -08005374 int32_t old = android_atomic_inc(&mFastMixerFutex);
5375 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005376 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005377 }
5378#ifdef AUDIO_WATCHDOG
5379 if (mAudioWatchdog != 0) {
5380 mAudioWatchdog->resume();
5381 }
5382#endif
5383 }
5384 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005385#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005386 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005387 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005388#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005389 sq->end();
5390 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5391 if (kUseFastMixer == FastMixer_Dynamic) {
5392 mNormalSink = mPipeSink;
5393 }
5394 } else {
5395 sq->end(false /*didModify*/);
5396 }
5397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005399}
5400
Andy Hungee58e4a2023-07-07 13:47:37 -07005401void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005402{
5403 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005404 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005405 FastMixerStateQueue *sq = mFastMixer->sq();
5406 FastMixerState *state = sq->begin();
5407 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005408 // Report any frames trapped in the Monopipe
5409 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5410 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5411 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5412 "monoPipeWritten:%lld monoPipeLeft:%lld",
5413 (long long)mFramesWritten, (long long)mSuspendedFrames,
5414 (long long)mPipeSink->framesWritten(), pipeFrames);
5415 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5416
Eric Laurent81784c32012-11-19 14:55:58 -08005417 state->mCommand = FastMixerState::COLD_IDLE;
5418 state->mColdFutexAddr = &mFastMixerFutex;
5419 state->mColdGen++;
5420 mFastMixerFutex = 0;
5421 sq->end();
5422 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5423 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5424 if (kUseFastMixer == FastMixer_Dynamic) {
5425 mNormalSink = mOutputSink;
5426 }
5427#ifdef AUDIO_WATCHDOG
5428 if (mAudioWatchdog != 0) {
5429 mAudioWatchdog->pause();
5430 }
5431#endif
5432 } else {
5433 sq->end(false /*didModify*/);
5434 }
5435 }
5436 PlaybackThread::threadLoop_standby();
5437}
5438
Andy Hungee58e4a2023-07-07 13:47:37 -07005439bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005440{
5441 return false;
5442}
5443
Andy Hungee58e4a2023-07-07 13:47:37 -07005444bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005445{
5446 return !mStandby;
5447}
5448
Andy Hungee58e4a2023-07-07 13:47:37 -07005449bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005450{
Andy Hung972bec12023-08-31 16:13:39 -07005451 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005452 return waitingAsyncCallback_l();
5453}
5454
Eric Laurent81784c32012-11-19 14:55:58 -08005455// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005456void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005457{
Andy Hung8d672e02023-09-15 18:19:28 -07005458 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5459 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005460 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005461 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005462 // discard any pending drain or write ack by incrementing sequence
5463 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5464 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005465 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005466 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5467 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005468 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005469 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005470 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005471}
5472
Andy Hungee58e4a2023-07-07 13:47:37 -07005473void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005474{
5475 ALOGV("signal playback thread");
5476 broadcast_l();
5477}
5478
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005479void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005480{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005481 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005482 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5483 invalidateTracks((audio_stream_type_t)i);
5484 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005485 if (isHardError) {
5486 mAfThreadCallback->onHardError(allTrackPortIds);
5487 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005488}
5489
Andy Hungee58e4a2023-07-07 13:47:37 -07005490void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005491{
Eric Laurent81784c32012-11-19 14:55:58 -08005492 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005493 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005494 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005495 // increase sleep time progressively when application underrun condition clears.
5496 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5497 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5498 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005499 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005500 sleepTimeShift--;
5501 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005502 mSleepTimeUs = 0;
5503 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005504 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005505
Eric Laurent81784c32012-11-19 14:55:58 -08005506}
5507
Andy Hungee58e4a2023-07-07 13:47:37 -07005508void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005509{
5510 // If no tracks are ready, sleep once for the duration of an output
5511 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005512 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005513 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005514 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5515 // Using the Monopipe availableToWrite, we estimate the
5516 // sleep time to retry for more data (before we underrun).
5517 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5518 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5519 const size_t pipeFrames = monoPipe->maxFrames();
5520 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5521 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5522 const size_t framesDelay = std::min(
5523 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5524 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5525 pipeFrames, framesLeft, framesDelay);
5526 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5527 } else {
5528 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5529 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5530 mSleepTimeUs = kMinThreadSleepTimeUs;
5531 }
5532 // reduce sleep time in case of consecutive application underruns to avoid
5533 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5534 // duration we would end up writing less data than needed by the audio HAL if
5535 // the condition persists.
5536 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5537 sleepTimeShift++;
5538 }
Eric Laurent81784c32012-11-19 14:55:58 -08005539 }
5540 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005541 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005542 }
5543 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005544 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5545 // before effects processing or output.
5546 if (mMixerBufferValid) {
5547 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005548 if (mType == SPATIALIZER) {
5549 memset(mSinkBuffer, 0, mSinkBufferSize);
5550 }
Andy Hung98ef9782014-03-04 14:46:50 -08005551 } else {
5552 memset(mSinkBuffer, 0, mSinkBufferSize);
5553 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005554 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005555 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5556 "anticipated start");
5557 }
5558 // TODO add standby time extension fct of effect tail
5559}
5560
Andy Hungc5007f82023-08-29 14:26:09 -07005561// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005562PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005563 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005564{
Andy Hungc0691382018-09-12 18:01:57 -07005565 // clean up deleted track ids in AudioMixer before allocating new tracks
5566 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5567 // for each trackId, destroy it in the AudioMixer
5568 if (mAudioMixer->exists(trackId)) {
5569 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005570 }
5571 });
Andy Hungc0691382018-09-12 18:01:57 -07005572 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005573
5574 mixer_state mixerStatus = MIXER_IDLE;
5575 // find out which tracks need to be processed
5576 size_t count = mActiveTracks.size();
5577 size_t mixedTracks = 0;
5578 size_t tracksWithEffect = 0;
5579 // counts only _active_ fast tracks
5580 size_t fastTracks = 0;
5581 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5582
5583 float masterVolume = mMasterVolume;
5584 bool masterMute = mMasterMute;
5585
5586 if (masterMute) {
5587 masterVolume = 0;
5588 }
5589 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005590 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005591 if (chain != 0) {
5592 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005593 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005594 masterVolume = (float)((v + (1 << 23)) >> 24);
5595 chain.clear();
5596 }
5597
5598 // prepare a new state to push
5599 FastMixerStateQueue *sq = NULL;
5600 FastMixerState *state = NULL;
5601 bool didModify = false;
5602 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005603 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005604 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005605 sq = mFastMixer->sq();
5606 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005607 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005608 }
5609
Andy Hung69aed5f2014-02-25 17:24:40 -08005610 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005611 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005612
Andy Hungbd3b2b02018-05-21 10:53:11 -07005613 // DeferredOperations handles statistics after setting mixerStatus.
5614 class DeferredOperations {
5615 public:
Andy Hungea840382020-05-05 21:50:17 -07005616 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5617 : mMixerStatus(mixerStatus)
5618 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005619
5620 // when leaving scope, tally frames properly.
5621 ~DeferredOperations() {
5622 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5623 // because that is when the underrun occurs.
5624 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005625 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005626 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005627 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005628 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005629 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005630 }
5631 }
Andy Hungea840382020-05-05 21:50:17 -07005632 // send the max underrun frames for this mixer period
5633 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005634 }
5635
5636 // tallyUnderrunFrames() is called to update the track counters
5637 // with the number of underrun frames for a particular mixer period.
5638 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005639 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005640 mUnderrunFrames.emplace_back(track, underrunFrames);
5641 }
5642
5643 private:
5644 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005645 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005646 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005647 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005648 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005649
jiabin245cdd92018-12-07 17:55:15 -08005650 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005651 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005652 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005653
5654 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005655 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005656
5657 // process fast tracks
5658 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005659 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5660 "%s(%d): FastTrack(%d) present without FastMixer",
5661 __func__, id(), track->id());
5662
jiabin245cdd92018-12-07 17:55:15 -08005663 if (track->getHapticPlaybackEnabled()) {
5664 noFastHapticTrack = false;
5665 }
Eric Laurent81784c32012-11-19 14:55:58 -08005666
5667 // It's theoretically possible (though unlikely) for a fast track to be created
5668 // and then removed within the same normal mix cycle. This is not a problem, as
5669 // the track never becomes active so it's fast mixer slot is never touched.
5670 // The converse, of removing an (active) track and then creating a new track
5671 // at the identical fast mixer slot within the same normal mix cycle,
5672 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005673 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005674 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005675 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5676 FastTrack *fastTrack = &state->mFastTracks[j];
5677
5678 // Determine whether the track is currently in underrun condition,
5679 // and whether it had a recent underrun.
5680 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5681 FastTrackUnderruns underruns = ftDump->mUnderruns;
5682 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005683 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005684 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005685 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005686 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005687 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005688 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005689 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005690 // don't count underruns that occur while stopping or pausing
5691 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005692 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005693 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5694 recentUnderruns > 0) {
5695 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005696 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005697 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005698 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005699 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005700
5701 // This is similar to the state machine for normal tracks,
5702 // with a few modifications for fast tracks.
5703 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005704 switch (track->state()) {
5705 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005706 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005707 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005708 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005709 }
5710 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005711 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005712 // ramp down is not yet implemented
5713 track->setPaused();
5714 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005715 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005716 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005717 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005718 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005719 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005720 if (recentFull > 0 || recentPartial > 0) {
5721 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005722 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005723 }
5724 if (recentUnderruns == 0) {
5725 // no recent underruns: stay active
5726 break;
5727 }
5728 // there has recently been an underrun of some kind
5729 if (track->sharedBuffer() == 0) {
5730 // were any of the recent underruns "empty" (no frames available)?
5731 if (recentEmpty == 0) {
5732 // no, then ignore the partial underruns as they are allowed indefinitely
5733 break;
5734 }
5735 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005736 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005737 break;
5738 }
5739 // indicate to client process that the track was disabled because of underrun;
5740 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005741 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005742 // remove from active list, but state remains ACTIVE [confusing but true]
5743 isActive = false;
5744 break;
5745 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005746 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005747 case IAfTrackBase::STOPPING_2:
5748 case IAfTrackBase::PAUSED:
5749 case IAfTrackBase::STOPPED:
5750 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005751 // Check for presentation complete if track is inactive
5752 // We have consumed all the buffers of this track.
5753 // This would be incomplete if we auto-paused on underrun
5754 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005755 uint32_t latency = 0;
5756 status_t result = mOutput->stream->getLatency(&latency);
5757 ALOGE_IF(result != OK,
5758 "Error when retrieving output stream latency: %d", result);
5759 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005760 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005761 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5762 // track stays in active list until presentation is complete
5763 break;
5764 }
5765 }
5766 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005767 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005768 }
5769 if (track->isStopped()) {
5770 // Can't reset directly, as fast mixer is still polling this track
5771 // track->reset();
5772 // So instead mark this track as needing to be reset after push with ack
5773 resetMask |= 1 << i;
5774 }
5775 isActive = false;
5776 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005777 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005778 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005779 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005780 }
5781
5782 if (isActive) {
5783 // was it previously inactive?
5784 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005785 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5786 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005787 fastTrack->mBufferProvider = eabp;
5788 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005789 fastTrack->mChannelMask = track->channelMask();
5790 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005791 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005792 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005793 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005794 fastTrack->mGeneration++;
5795 state->mTrackMask |= 1 << j;
5796 didModify = true;
5797 // no acknowledgement required for newly active tracks
5798 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005799 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005800 float volume;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02005801 if (!audioserver_flags::portid_volume_management()) {
5802 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5803 volume = 0.f;
5804 } else {
5805 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5806 }
Eric Laurenteab90452019-06-24 15:17:46 -07005807 } else {
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02005808 if (track->isPlaybackRestricted()) {
5809 volume = 0.f;
5810 } else {
5811 volume = masterVolume * track->getPortVolume();
5812 }
Eric Laurenteab90452019-06-24 15:17:46 -07005813 }
Eric Laurenteab90452019-06-24 15:17:46 -07005814 handleVoipVolume_l(&volume);
5815
Eric Laurent81784c32012-11-19 14:55:58 -08005816 // cache the combined master volume and stream type volume for fast mixer; this
5817 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005818 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005819 proxy->framesReleased()).first;
5820 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005821 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005822 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005823 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5824 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02005825 if (!audioserver_flags::portid_volume_management()) {
5826 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5827 /*muteState=*/{masterVolume == 0.f,
5828 mStreamTypes[track->streamType()].volume == 0.f,
5829 mStreamTypes[track->streamType()].mute,
5830 track->isPlaybackRestricted(),
5831 vlf == 0.f && vrf == 0.f,
5832 vh == 0.f});
5833 } else {
5834 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5835 /*muteState=*/{masterVolume == 0.f,
5836 track->getPortVolume() == 0.f,
5837 /* muteFromStreamMuted= */ false,
5838 track->isPlaybackRestricted(),
5839 vlf == 0.f && vrf == 0.f,
5840 vh == 0.f});
5841 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005842 vlf *= volume;
5843 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005844
jiabin220eea12024-05-17 17:55:20 +00005845 if (track->getInternalMute()) {
5846 vlf = 0.f;
5847 vrf = 0.f;
5848 }
5849
jiabin76d94692022-12-15 21:51:21 +00005850 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005851 ++fastTracks;
5852 } else {
5853 // was it previously active?
5854 if (state->mTrackMask & (1 << j)) {
5855 fastTrack->mBufferProvider = NULL;
5856 fastTrack->mGeneration++;
5857 state->mTrackMask &= ~(1 << j);
5858 didModify = true;
5859 // If any fast tracks were removed, we must wait for acknowledgement
5860 // because we're about to decrement the last sp<> on those tracks.
5861 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5862 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005863 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5864 // AudioTrack may start (which may not be with a start() but with a write()
5865 // after underrun) and immediately paused or released. In that case the
5866 // FastTrack state hasn't had time to update.
5867 // TODO Remove the ALOGW when this theory is confirmed.
5868 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005869 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005870 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005871 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005872 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005873 }
5874 tracksToRemove->add(track);
5875 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005876 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005877 }
jiabin245cdd92018-12-07 17:55:15 -08005878 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5879 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5880 didModify = true;
5881 }
Eric Laurent81784c32012-11-19 14:55:58 -08005882 continue;
5883 }
5884
5885 { // local variable scope to avoid goto warning
5886
5887 audio_track_cblk_t* cblk = track->cblk();
5888
5889 // The first time a track is added we wait
5890 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005891 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005892
5893 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005894 // use the trackId as the AudioMixer name.
5895 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005896 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005897 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005898 track->channelMask(),
5899 track->format(),
5900 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005901 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005902 ALOGW("%s(): AudioMixer cannot create track(%d)"
5903 " mask %#x, format %#x, sessionId %d",
5904 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005905 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005906 tracksToRemove->add(track);
5907 track->invalidate(); // consider it dead.
5908 continue;
5909 }
5910 }
5911
Eric Laurent81784c32012-11-19 14:55:58 -08005912 // make sure that we have enough frames to mix one full buffer.
5913 // enforce this condition only once to enable draining the buffer in case the client
5914 // app does not call stop() and relies on underrun to stop:
5915 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5916 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005917 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005918 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5919 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005920
5921 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005922 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005923 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5924 // add frames already consumed but not yet released by the resampler
5925 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005926 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005927
Eric Laurent81784c32012-11-19 14:55:58 -08005928 uint32_t minFrames = 1;
5929 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5930 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005931 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005932 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005933
5934 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005935 if (ATRACE_ENABLED()) {
5936 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005937 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005938 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005939 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005940 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005941 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005942 !track->isPaused() && !track->isTerminated())
5943 {
Andy Hungc0691382018-09-12 18:01:57 -07005944 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005945
5946 mixedTracks++;
5947
Shunkai Yaof4847652024-01-12 00:25:20 +00005948 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005949 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005950 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005951 if (track->mainBuffer() != mSinkBuffer &&
5952 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005953 if (mEffectBufferEnabled) {
5954 mEffectBufferValid = true; // Later can set directly.
5955 }
Eric Laurent81784c32012-11-19 14:55:58 -08005956 chain = getEffectChain_l(track->sessionId());
5957 // Delegate volume control to effect in track effect chain if needed
5958 if (chain != 0) {
5959 tracksWithEffect++;
5960 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005961 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005962 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005963 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005964 }
5965 }
5966
5967
5968 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005969 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005970 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005971 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5972 if (track->state() == IAfTrackBase::RESUMING) {
5973 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005974 // If a new track is paused immediately after start, do not ramp on resume.
5975 if (cblk->mServer != 0) {
5976 param = AudioMixer::RAMP_VOLUME;
5977 }
Eric Laurent81784c32012-11-19 14:55:58 -08005978 }
Andy Hungc0691382018-09-12 18:01:57 -07005979 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005980 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005981 // FIXME should not make a decision based on mServer
5982 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005983 // If the track is stopped before the first frame was mixed,
5984 // do not apply ramp
5985 param = AudioMixer::RAMP_VOLUME;
5986 }
5987
5988 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005989 uint32_t vl, vr; // in U8.24 integer format
5990 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005991 // read original volumes with volume control
Andy Hung333ab962019-05-28 20:23:35 -07005992 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005993 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005994 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005995 track->audioTrackServerProxy()->framesReleased()).first;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02005996 float v;
5997 if (!audioserver_flags::portid_volume_management()) {
5998 v = masterVolume * mStreamTypes[track->streamType()].volume;
5999 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6000 v = 0;
6001 }
6002 } else {
6003 v = masterVolume * track->getPortVolume();
6004 if (track->isPlaybackRestricted()) {
6005 v = 0;
6006 }
Eric Laurenteab90452019-06-24 15:17:46 -07006007 }
Eric Laurenteab90452019-06-24 15:17:46 -07006008 handleVoipVolume_l(&v);
6009
6010 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07006011 vl = vr = 0;
6012 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07006013 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08006014 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07006015 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07006016 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
6017 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08006018 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07006019 if (vlf > GAIN_FLOAT_UNITY) {
6020 ALOGV("Track left volume out of range: %.3g", vlf);
6021 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006022 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006023 if (vrf > GAIN_FLOAT_UNITY) {
6024 ALOGV("Track right volume out of range: %.3g", vrf);
6025 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006026 }
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006027 if (!audioserver_flags::portid_volume_management()) {
6028 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6029 /*muteState=*/{masterVolume == 0.f,
6030 mStreamTypes[track->streamType()].volume == 0.f,
6031 mStreamTypes[track->streamType()].mute,
6032 track->isPlaybackRestricted(),
6033 vlf == 0.f && vrf == 0.f,
6034 vh == 0.f});
6035 } else {
6036 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6037 /*muteState=*/{masterVolume == 0.f,
6038 track->getPortVolume() == 0.f,
6039 /* muteFromStreamMuted= */ false,
6040 track->isPlaybackRestricted(),
6041 vlf == 0.f && vrf == 0.f,
6042 vh == 0.f});
6043 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006044 // now apply the master volume and stream type volume and shaper volume
6045 vlf *= v * vh;
6046 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006047 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006048 // then derive vl and vr as U8.24 versions for the effect chain
6049 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6050 vl = (uint32_t) (scaleto8_24 * vlf);
6051 vr = (uint32_t) (scaleto8_24 * vrf);
6052 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006053 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006054 // send level comes from shared memory and so may be corrupt
6055 if (sendLevel > MAX_GAIN_INT) {
6056 ALOGV("Track send level out of range: %04X", sendLevel);
6057 sendLevel = MAX_GAIN_INT;
6058 }
Andy Hung6be49402014-05-30 10:42:03 -07006059 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6060 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006061 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006062
jiabin220eea12024-05-17 17:55:20 +00006063 if (track->getInternalMute()) {
6064 vrf = 0.f;
6065 vlf = 0.f;
6066 }
6067
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006068 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006069
Eric Laurent81784c32012-11-19 14:55:58 -08006070 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006071 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006072 // Do not ramp volume if volume is controlled by effect
6073 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006074 // Update remaining floating point volume levels
6075 vlf = (float)vl / (1 << 24);
6076 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006077 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006078 } else {
6079 // force no volume ramp when volume controller was just disabled or removed
6080 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006081 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006082 param = AudioMixer::VOLUME;
6083 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006084 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006085 }
6086
Eric Laurent81784c32012-11-19 14:55:58 -08006087 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006088 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006089 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006090
Andy Hungc0691382018-09-12 18:01:57 -07006091 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6092 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6093 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006094 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006095 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006096 AudioMixer::TRACK,
6097 AudioMixer::FORMAT, (void *)track->format());
6098 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006099 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006100 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006101 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006102
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006103 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006104 mAudioMixer->setParameter(
6105 trackId,
6106 AudioMixer::TRACK,
6107 AudioMixer::MIXER_CHANNEL_MASK,
6108 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6109 } else {
6110 mAudioMixer->setParameter(
6111 trackId,
6112 AudioMixer::TRACK,
6113 AudioMixer::MIXER_CHANNEL_MASK,
6114 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6115 }
6116
Glenn Kastene3aa6592012-12-04 12:22:46 -08006117 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006118 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006119 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006120 if (reqSampleRate == 0) {
6121 reqSampleRate = mSampleRate;
6122 } else if (reqSampleRate > maxSampleRate) {
6123 reqSampleRate = maxSampleRate;
6124 }
Eric Laurent81784c32012-11-19 14:55:58 -08006125 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006126 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006127 AudioMixer::RESAMPLE,
6128 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006129 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006130
Andy Hung8edb8dc2015-03-26 19:13:55 -07006131 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006132 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006133 AudioMixer::TIMESTRETCH,
6134 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006135 // cast away constness for this generic API.
6136 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006137
Andy Hung69aed5f2014-02-25 17:24:40 -08006138 /*
6139 * Select the appropriate output buffer for the track.
6140 *
Andy Hung98ef9782014-03-04 14:46:50 -08006141 * Tracks with effects go into their own effects chain buffer
6142 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006143 *
6144 * Other tracks can use mMixerBuffer for higher precision
6145 * channel accumulation. If this buffer is enabled
6146 * (mMixerBufferEnabled true), then selected tracks will accumulate
6147 * into it.
6148 *
6149 */
6150 if (mMixerBufferEnabled
6151 && (track->mainBuffer() == mSinkBuffer
6152 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006153 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006154 mAudioMixer->setParameter(
6155 trackId,
6156 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006157 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006158 mAudioMixer->setParameter(
6159 trackId,
6160 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006161 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006162 } else {
6163 mAudioMixer->setParameter(
6164 trackId,
6165 AudioMixer::TRACK,
6166 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6167 mAudioMixer->setParameter(
6168 trackId,
6169 AudioMixer::TRACK,
6170 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6171 // TODO: override track->mainBuffer()?
6172 mMixerBufferValid = true;
6173 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006174 } else {
6175 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006176 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006177 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006178 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006179 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006180 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006181 AudioMixer::TRACK,
6182 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6183 }
Eric Laurent81784c32012-11-19 14:55:58 -08006184 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006185 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006186 AudioMixer::TRACK,
6187 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006188 mAudioMixer->setParameter(
6189 trackId,
6190 AudioMixer::TRACK,
6191 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006192 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006193 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006194 trackId,
6195 AudioMixer::TRACK,
6196 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006197 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006198 mAudioMixer->setParameter(
6199 trackId,
6200 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006201 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006202
6203 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006204 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006205
6206 // If one track is ready, set the mixer ready if:
6207 // - the mixer was not ready during previous round OR
6208 // - no other track is not ready
6209 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6210 mixerStatus != MIXER_TRACKS_ENABLED) {
6211 mixerStatus = MIXER_TRACKS_READY;
6212 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006213
6214 // Enable the next few lines to instrument a test for underrun log handling.
6215 // TODO: Remove when we have a better way of testing the underrun log.
6216#if 0
6217 static int i;
6218 if ((++i & 0xf) == 0) {
6219 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6220 }
6221#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006222 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006223 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006224 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006225 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6226 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006227 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006228 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006229 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006230
Eric Laurent81784c32012-11-19 14:55:58 -08006231 // clear effect chain input buffer if an active track underruns to avoid sending
6232 // previous audio buffer again to effects
6233 chain = getEffectChain_l(track->sessionId());
6234 if (chain != 0) {
6235 chain->clearInputBuffer();
6236 }
6237
Andy Hungc0691382018-09-12 18:01:57 -07006238 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006239 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6240 track->isStopped() || track->isPaused()) {
6241 // We have consumed all the buffers of this track.
6242 // Remove it from the list of active tracks.
6243 // TODO: use actual buffer filling status instead of latency when available from
6244 // audio HAL
6245 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006246 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006247 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6248 if (track->isStopped()) {
6249 track->reset();
6250 }
6251 tracksToRemove->add(track);
6252 }
6253 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006254 // No buffers for this track. Give it a few chances to
6255 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006256 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006257 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6258 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006259 tracksToRemove->add(track);
6260 // indicate to client process that the track was disabled because of underrun;
6261 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006262 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006263 // If one track is not ready, mark the mixer also not ready if:
6264 // - the mixer was ready during previous round OR
6265 // - no other track is ready
6266 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6267 mixerStatus != MIXER_TRACKS_READY) {
6268 mixerStatus = MIXER_TRACKS_ENABLED;
6269 }
6270 }
Andy Hungc0691382018-09-12 18:01:57 -07006271 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006272 }
6273
6274 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006275
6276 }
6277
jiabin245cdd92018-12-07 17:55:15 -08006278 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6279 // When there is no fast track playing haptic and FastMixer exists,
6280 // enabling the first FastTrack, which provides mixed data from normal
6281 // tracks, to play haptic data.
6282 FastTrack *fastTrack = &state->mFastTracks[0];
6283 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6284 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6285 didModify = true;
6286 }
6287 }
6288
Eric Laurent81784c32012-11-19 14:55:58 -08006289 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006290 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006291 if (didModify) {
6292 state->mFastTracksGen++;
6293 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6294 if (kUseFastMixer == FastMixer_Dynamic &&
6295 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6296 state->mCommand = FastMixerState::COLD_IDLE;
6297 state->mColdFutexAddr = &mFastMixerFutex;
6298 state->mColdGen++;
6299 mFastMixerFutex = 0;
6300 if (kUseFastMixer == FastMixer_Dynamic) {
6301 mNormalSink = mOutputSink;
6302 }
6303 // If we go into cold idle, need to wait for acknowledgement
6304 // so that fast mixer stops doing I/O.
6305 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6306 pauseAudioWatchdog = true;
6307 }
Eric Laurent81784c32012-11-19 14:55:58 -08006308 }
6309 if (sq != NULL) {
6310 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006311 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6312 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6313 // when bringing the output sink into standby.)
6314 //
6315 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6316 //
6317 // This occurs with BT suspend when we idle the FastMixer with
6318 // active tracks, which may be added or removed.
6319 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006320 }
6321#ifdef AUDIO_WATCHDOG
6322 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6323 mAudioWatchdog->pause();
6324 }
6325#endif
6326
6327 // Now perform the deferred reset on fast tracks that have stopped
6328 while (resetMask != 0) {
6329 size_t i = __builtin_ctz(resetMask);
6330 ALOG_ASSERT(i < count);
6331 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006332 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006333 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6334 track->reset();
6335 }
6336
Andy Hung80d03d22018-04-10 10:32:11 -07006337 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6338 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6339 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6340 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6341 // See also the implementation of destroyTrack_l().
6342 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006343 const int trackId = track->id();
6344 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6345 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006346 }
6347 }
6348
Eric Laurent81784c32012-11-19 14:55:58 -08006349 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006350 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006351
Eric Laurentb3f315a2021-07-13 15:09:05 +02006352 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6353 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006354 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006355 }
6356
6357 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006358 // as long as there are effects we should clear the effects buffer, to avoid
6359 // passing a non-clean buffer to the effect chain
6360 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006361 if (mType == SPATIALIZER) {
6362 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6363 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006364 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006365 // sink or mix buffer must be cleared if all tracks are connected to an
6366 // effect chain as in this case the mixer will not write to the sink or mix buffer
6367 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006368 // always clear sink buffer for spatializer output as the output of the spatializer
6369 // effect will be accumulated into it
6370 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6371 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006372 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006373 if (mMixerBufferValid) {
6374 memset(mMixerBuffer, 0, mMixerBufferSize);
6375 // TODO: In testing, mSinkBuffer below need not be cleared because
6376 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6377 // after mixing.
6378 //
6379 // To enforce this guarantee:
6380 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6381 // (mixedTracks == 0 && fastTracks > 0))
6382 // must imply MIXER_TRACKS_READY.
6383 // Later, we may clear buffers regardless, and skip much of this logic.
6384 }
Andy Hung98ef9782014-03-04 14:46:50 -08006385 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006386 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006387 }
6388
6389 // if any fast tracks, then status is ready
6390 mMixerStatusIgnoringFastTracks = mixerStatus;
6391 if (fastTracks > 0) {
6392 mixerStatus = MIXER_TRACKS_READY;
6393 }
6394 return mixerStatus;
6395}
6396
Andy Hungc5007f82023-08-29 14:26:09 -07006397// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006398uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006399{
6400 uint32_t trackCount = 0;
6401 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006402 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006403 trackCount++;
6404 }
6405 }
6406 return trackCount;
6407}
6408
Andy Hungee58e4a2023-07-07 13:47:37 -07006409bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006410{
Brian Lindahl65e90012022-07-27 18:01:07 +02006411 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6412 // could falsely detect that the frame position has stalled due to underrun because we haven't
6413 // given the Audio HAL enough time to update.
6414 const nsecs_t nowNs = systemTime();
6415 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6416 return mLatchedValue;
6417 }
6418 mPreviousNs = nowNs;
6419 mLatchedValue = false;
6420 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006421 uint64_t position = 0;
6422 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006423 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006424 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006425 if (position != mPreviousPosition) {
6426 mPreviousPosition = position;
6427 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006428 }
6429 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006430 return mLatchedValue;
6431}
6432
Andy Hungee58e4a2023-07-07 13:47:37 -07006433void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006434{
6435 mLatchedValue = true;
6436 mPreviousPosition = 0;
6437 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006438}
6439
Andy Hungc5007f82023-08-29 14:26:09 -07006440// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006441bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006442 audio_channel_mask_t channelMask, audio_format_t format,
6443 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006444{
Andy Hung1bc088a2018-02-09 15:57:31 -08006445 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6446 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006447 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006448 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006449 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006450 ALOGW("%s: invalid format: %#x", __func__, format);
6451 return false;
6452 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006453 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006454 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6455 return false;
6456 }
6457 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006458}
6459
Andy Hungc5007f82023-08-29 14:26:09 -07006460// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006461bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006462 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006463{
Eric Laurent81784c32012-11-19 14:55:58 -08006464 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006465 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006466
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006467 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006468
Eric Laurent10351942014-05-08 18:49:52 -07006469 AudioParameter param = AudioParameter(keyValuePair);
6470 int value;
6471 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6472 reconfig = true;
6473 }
6474 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006475 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006476 status = BAD_VALUE;
6477 } else {
6478 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006479 reconfig = true;
6480 }
Eric Laurent10351942014-05-08 18:49:52 -07006481 }
6482 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006483 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006484 status = BAD_VALUE;
6485 } else {
6486 // no need to save value, since it's constant
6487 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006488 }
Eric Laurent10351942014-05-08 18:49:52 -07006489 }
6490 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6491 // do not accept frame count changes if tracks are open as the track buffer
6492 // size depends on frame count and correct behavior would not be guaranteed
6493 // if frame count is changed after track creation
6494 if (!mTracks.isEmpty()) {
6495 status = INVALID_OPERATION;
6496 } else {
6497 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006498 }
Eric Laurent10351942014-05-08 18:49:52 -07006499 }
6500 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006501 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006502 }
Eric Laurent81784c32012-11-19 14:55:58 -08006503
Eric Laurent10351942014-05-08 18:49:52 -07006504 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006505 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006506 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006507 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6508 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006509 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006510 mThreadMetrics.logEndInterval();
6511 mThreadSnapshot.onEnd();
6512 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006513 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006514 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006515 }
Eric Laurent10351942014-05-08 18:49:52 -07006516 if (status == NO_ERROR && reconfig) {
6517 readOutputParameters_l();
6518 delete mAudioMixer;
6519 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006520 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006521 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006522 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006523 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006524 track->channelMask(),
6525 track->format(),
6526 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006527 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006528 "%s(): AudioMixer cannot create track(%d)"
6529 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006530 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006531 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006532 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006533 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006534 }
Eric Laurent81784c32012-11-19 14:55:58 -08006535 }
6536
Dean Wheatley68918102021-03-19 22:09:19 +11006537 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006538}
6539
6540
Andy Hungee58e4a2023-07-07 13:47:37 -07006541void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006542{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006543 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006544 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006545 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006546 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006547 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6548 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6549 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006550 if (hasFastMixer()) {
6551 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6552
6553 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6554 // while we are dumping it. It may be inconsistent, but it won't mutate!
6555 // This is a large object so we place it on the heap.
6556 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006557 const std::unique_ptr<FastMixerDumpState> copy =
6558 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006559 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006560
6561#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006562 // Similar for state queue
6563 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6564 observerCopy.dump(fd);
6565 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6566 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006567#endif
6568
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006569#ifdef AUDIO_WATCHDOG
6570 if (mAudioWatchdog != 0) {
6571 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6572 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6573 wdCopy.dump(fd);
6574 }
6575#endif
6576
6577 } else {
6578 dprintf(fd, " No FastMixer\n");
6579 }
Eric Laurent90cea102023-05-15 15:08:27 +02006580
6581 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6582 mBluetoothLatencyModesEnabled ? "" : "not ");
6583 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6584 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6585 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006586}
6587
Andy Hungee58e4a2023-07-07 13:47:37 -07006588uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006589{
6590 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6591}
6592
Andy Hungee58e4a2023-07-07 13:47:37 -07006593uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006594{
6595 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6596}
6597
Andy Hungee58e4a2023-07-07 13:47:37 -07006598void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006599{
6600 PlaybackThread::cacheParameters_l();
6601
6602 // FIXME: Relaxed timing because of a certain device that can't meet latency
6603 // Should be reduced to 2x after the vendor fixes the driver issue
6604 // increase threshold again due to low power audio mode. The way this warning
6605 // threshold is calculated and its usefulness should be reconsidered anyway.
6606 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6607}
6608
Andy Hungee58e4a2023-07-07 13:47:37 -07006609void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006610 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006611}
6612
Andy Hungee58e4a2023-07-07 13:47:37 -07006613void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006614 // Only handle latency mode if:
6615 // - mBluetoothLatencyModesEnabled is true
6616 // - the HAL supports latency modes
6617 // - the selected device is Bluetooth LE or A2DP
6618 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6619 return;
6620 }
6621 if (mOutDeviceTypeAddrs.size() != 1
6622 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6623 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6624 return;
6625 }
6626
6627 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6628 if (mSupportedLatencyModes.size() == 1) {
6629 // If the HAL only support one latency mode currently, confirm the choice
6630 latencyMode = mSupportedLatencyModes[0];
6631 } else if (mSupportedLatencyModes.size() > 1) {
6632 // Request low latency if:
6633 // - At least one active track is either:
6634 // - a fast track with gaming usage or
6635 // - a track with acessibility usage
6636 for (const auto& track : mActiveTracks) {
6637 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6638 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6639 latencyMode = AUDIO_LATENCY_MODE_LOW;
6640 break;
6641 }
6642 }
6643 }
6644
6645 if (latencyMode != mSetLatencyMode) {
6646 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6647 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6648 __func__, mId, toString(latencyMode).c_str(), status);
6649 if (status == NO_ERROR) {
6650 mSetLatencyMode = latencyMode;
6651 }
6652 }
6653}
6654
Andy Hungee58e4a2023-07-07 13:47:37 -07006655void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006656
6657 if (mOutput == nullptr || mOutput->stream == nullptr) {
6658 return;
6659 }
6660 std::vector<audio_latency_mode_t> latencyModes;
6661 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6662 if (status != NO_ERROR) {
6663 latencyModes.clear();
6664 }
6665 if (latencyModes != mSupportedLatencyModes) {
6666 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6667 __func__, mId, status, toString(latencyModes).c_str());
6668 mSupportedLatencyModes.swap(latencyModes);
6669 sendHalLatencyModesChangedEvent_l();
6670 }
6671}
6672
Andy Hungee58e4a2023-07-07 13:47:37 -07006673status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006674 std::vector<audio_latency_mode_t>* modes) {
6675 if (modes == nullptr) {
6676 return BAD_VALUE;
6677 }
Andy Hung972bec12023-08-31 16:13:39 -07006678 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006679 *modes = mSupportedLatencyModes;
6680 return NO_ERROR;
6681}
6682
Andy Hungee58e4a2023-07-07 13:47:37 -07006683void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006684 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006685 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006686 if (modes != mSupportedLatencyModes) {
6687 ALOGD("%s: thread(%d) supported latency modes: %s",
6688 __func__, mId, toString(modes).c_str());
6689 mSupportedLatencyModes.swap(modes);
6690 sendHalLatencyModesChangedEvent_l();
6691 }
6692}
6693
Andy Hungee58e4a2023-07-07 13:47:37 -07006694status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006695 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6696 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6697 return INVALID_OPERATION;
6698 }
6699 mBluetoothLatencyModesEnabled.store(enabled);
6700 return NO_ERROR;
6701}
6702
Eric Laurent81784c32012-11-19 14:55:58 -08006703// ----------------------------------------------------------------------------
6704
Andy Hungee58e4a2023-07-07 13:47:37 -07006705/* static */
6706sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006707 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006708 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6709 const audio_offload_info_t& offloadInfo) {
6710 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006711 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006712}
6713
Andy Hung583043b2023-07-17 17:05:00 -07006714DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006715 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6716 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006717 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006718 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006719{
Andy Hung583043b2023-07-17 17:05:00 -07006720 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006721}
6722
Andy Hungee58e4a2023-07-07 13:47:37 -07006723DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006724{
6725}
6726
Andy Hungee58e4a2023-07-07 13:47:37 -07006727void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006728{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006729 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006730 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6731 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6732}
6733
Andy Hungee58e4a2023-07-07 13:47:37 -07006734void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006735{
Andy Hung972bec12023-08-31 16:13:39 -07006736 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006737 if (mMasterBalance != balance) {
6738 mMasterBalance.store(balance);
6739 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6740 broadcast_l();
6741 }
6742}
6743
Andy Hungee58e4a2023-07-07 13:47:37 -07006744void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006745{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006746 float left, right;
6747
Andy Hung333ab962019-05-28 20:23:35 -07006748 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006749 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006750
Andy Hung398ffa22022-12-13 19:19:53 -08006751 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6752 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6753
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006754 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6755 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006756
6757 const int64_t volumeShaperFrames =
6758 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6759 const auto [shaperVolume, shaperActive] =
6760 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006761 mVolumeShaperActive = shaperActive;
6762
Vlad Popae2f5aef2022-07-25 16:00:20 +02006763 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6764 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6765 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6766
6767 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6768
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006769 if (!audioserver_flags::portid_volume_management()) {
6770 if (mMasterMute || mStreamTypes[track->streamType()].mute ||
6771 track->isPlaybackRestricted()) {
6772 left = right = 0;
6773 } else {
6774 float typeVolume = mStreamTypes[track->streamType()].volume;
6775 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006776
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006777 if (left > GAIN_FLOAT_UNITY) {
6778 left = GAIN_FLOAT_UNITY;
6779 }
6780 if (right > GAIN_FLOAT_UNITY) {
6781 right = GAIN_FLOAT_UNITY;
6782 }
6783 left *= v;
6784 right *= v;
6785 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006786 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006787 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6788 right *= mMasterBalanceRight;
6789 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006790 }
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006791 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6792 /*muteState=*/{mMasterMute,
6793 mStreamTypes[track->streamType()].volume == 0.f,
6794 mStreamTypes[track->streamType()].mute,
6795 track->isPlaybackRestricted(),
6796 clientVolumeMute,
6797 shaperVolume == 0.f});
6798 } else {
6799 if (mMasterMute || track->isPlaybackRestricted()) {
6800 left = right = 0;
6801 } else {
6802 float typeVolume = track->getPortVolume();
6803 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006804
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006805 if (left > GAIN_FLOAT_UNITY) {
6806 left = GAIN_FLOAT_UNITY;
6807 }
6808 if (right > GAIN_FLOAT_UNITY) {
6809 right = GAIN_FLOAT_UNITY;
6810 }
6811 left *= v;
6812 right *= v;
6813 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6814 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6815 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6816 right *= mMasterBalanceRight;
6817 }
6818 }
6819 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6820 /*muteState=*/{mMasterMute,
6821 track->getPortVolume() == 0.f,
6822 /* muteFromStreamMuted= */ false,
6823 track->isPlaybackRestricted(),
6824 clientVolumeMute,
6825 shaperVolume == 0.f});
6826 }
Vlad Popae8d99472022-06-30 16:02:48 +02006827
Eric Laurentbfb1b832013-01-07 09:53:42 -08006828 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006829 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006830 if (left != mLeftVolFloat || right != mRightVolFloat) {
6831 mLeftVolFloat = left;
6832 mRightVolFloat = right;
6833
Eric Laurentbfb1b832013-01-07 09:53:42 -08006834 // Delegate volume control to effect in track effect chain if needed
6835 // only one effect chain can be present on DirectOutputThread, so if
6836 // there is one, the track is connected to it
6837 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006838 // if effect chain exists, volume is handled by it.
6839 // Convert volumes from float to 8.24
6840 uint32_t vl = (uint32_t)(left * (1 << 24));
6841 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006842 // Direct/Offload effect chains set output volume in setVolume().
6843 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006844 } else {
6845 // otherwise we directly set the volume.
6846 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006847 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006848 }
6849 }
6850}
6851
Andy Hungee58e4a2023-07-07 13:47:37 -07006852void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006853{
Andy Hung8d31fd22023-06-26 19:20:57 -07006854 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6855 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006856
Eric Laurent0f0631e2015-07-06 18:01:25 -07006857 if (previousTrack != 0 && latestTrack != 0) {
6858 if (mType == DIRECT) {
6859 if (previousTrack.get() != latestTrack.get()) {
6860 mFlushPending = true;
6861 }
6862 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006863 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6864 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006865 mFlushPending = true;
6866 }
6867 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006868 } else if (previousTrack == 0) {
6869 // there could be an old track added back during track transition for direct
6870 // output, so always issues flush to flush data of the previous track if it
6871 // was already destroyed with HAL paused, then flush can resume the playback
6872 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006873 }
6874 PlaybackThread::onAddNewTrack_l();
6875}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006876
Andy Hungee58e4a2023-07-07 13:47:37 -07006877PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006878 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006879)
6880{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006881 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006882 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006883 bool doHwPause = false;
6884 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006885
6886 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006887 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006888 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006889 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006890 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006891 continue;
6892 }
6893
Andy Hung8d31fd22023-06-26 19:20:57 -07006894 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006895#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006896 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006897#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006898 // Only consider last track started for volume and mixer state control.
6899 // In theory an older track could underrun and restart after the new one starts
6900 // but as we only care about the transition phase between two tracks on a
6901 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006902 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006903 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006904
Kuowei Li23666472021-01-20 10:23:25 +08006905 if (track->isPausePending()) {
6906 track->pauseAck();
6907 // It is possible a track might have been flushed or stopped.
6908 // Other operations such as flush pending might occur on the next prepare.
6909 if (track->isPausing()) {
6910 track->setPaused();
6911 }
6912 // Always perform pause, as an immediate flush will change
6913 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006914 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006915 doHwPause = true;
6916 mHwPaused = true;
6917 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006918 } else if (track->isFlushPending()) {
6919 track->flushAck();
6920 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006921 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006922 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006923 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006924 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006925 if (last) {
6926 mLeftVolFloat = mRightVolFloat = -1.0;
6927 if (mHwPaused) {
6928 doHwResume = true;
6929 mHwPaused = false;
6930 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006931 }
6932 }
6933
Eric Laurent81784c32012-11-19 14:55:58 -08006934 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006935 // for all its buffers to be filled before processing it.
6936 // Allow draining the buffer in case the client
6937 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006938 // hence the test on (track->retryCount() > 1).
6939 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006940 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6941 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006942 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006943
6944 // target retry count that we will use is based on the time we wait for retries.
6945 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6946 // the retry threshold is when we accept any size for PCM data. This is slightly
6947 // smaller than the retry count so we can push small bits of data without a glitch.
6948 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006949 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006950 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006951 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006952 minFrames = mNormalFrameCount;
6953 } else {
6954 minFrames = 1;
6955 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006956
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006957 const size_t framesReady = track->framesReady();
6958 const int trackId = track->id();
6959 if (ATRACE_ENABLED()) {
6960 std::string traceName("nRdy");
6961 traceName += std::to_string(trackId);
6962 ATRACE_INT(traceName.c_str(), framesReady);
6963 }
6964 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006965 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006966 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006967 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006968
Andy Hung8d31fd22023-06-26 19:20:57 -07006969 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6970 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006971 if (last) {
6972 // make sure processVolume_l() will apply new volume even if 0
6973 mLeftVolFloat = mRightVolFloat = -1.0;
6974 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006975 if (!mHwSupportsPause) {
6976 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006977 }
6978 }
6979
6980 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006981 processVolume_l(track, last);
6982 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006983 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006984 if (previousTrack != 0) {
6985 if (track != previousTrack.get()) {
6986 // Flush any data still being written from last track
6987 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006988 // Invalidate previous track to force a seek when resuming.
6989 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006990 }
6991 }
6992 mPreviousTrack = track;
6993
Eric Laurentd595b7c2013-04-03 17:27:56 -07006994 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006995 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006996 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006997 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006998 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006999 doHwResume = true;
7000 mHwPaused = false;
7001 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007002 }
Eric Laurent81784c32012-11-19 14:55:58 -08007003 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07007004 // clear effect chain input buffer if the last active track started underruns
7005 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07007006 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08007007 mEffectChains[0]->clearInputBuffer();
7008 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007009 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007010 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07007011 if (last && mHwPaused) {
7012 doHwResume = true;
7013 mHwPaused = false;
7014 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007015 }
7016 if ((track->sharedBuffer() != 0) || track->isStopped() ||
7017 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007018 // We have consumed all the buffers of this track.
7019 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04007020 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07007021 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04007022 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08007023 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04007024 if (presComplete) {
7025 mOutput->presentationComplete();
7026 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007027 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007028 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07007029 }
Eric Laurent81784c32012-11-19 14:55:58 -08007030 if (track->isStopped()) {
7031 track->reset();
7032 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007033 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08007034 }
7035 } else {
7036 // No buffers for this track. Give it a few chances to
7037 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07007038 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02007039 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007040 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007041 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007042 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007043 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08007044 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007045 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7046 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08007047 tracksToRemove->add(track);
7048 // indicate to client process that the track was disabled because of
7049 // underrun; it will then automatically call start() when data is available
7050 track->disable();
7051 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
7052 // unlike mixerthread, HAL can be paused for direct output
7053 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
7054 "minFrames = %u, mFormat = %#x",
7055 framesReady, minFrames, mFormat);
7056 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
7057 doHwPause = true;
7058 mHwPaused = true;
7059 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007060 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08007061 } else if (last) {
7062 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007063 }
7064 }
7065 }
7066 }
7067
Eric Laurentd1f69b02014-12-15 14:33:13 -08007068 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007069 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007070 for (size_t i = 0; i < mTracks.size(); i++) {
7071 if (mTracks[i]->isFlushPending()) {
7072 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007073 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007074 }
7075 }
7076 }
7077
7078 // make sure the pause/flush/resume sequence is executed in the right order.
7079 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7080 // before flush and then resume HW. This can happen in case of pause/flush/resume
7081 // if resume is received before pause is executed.
7082 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007083 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007084 status_t result = mOutput->stream->pause();
7085 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007086 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007087 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007088 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007089 flushHw_l();
7090 }
7091 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007092 status_t result = mOutput->stream->resume();
7093 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007094 }
Eric Laurent81784c32012-11-19 14:55:58 -08007095 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007096 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007097
7098 return mixerStatus;
7099}
7100
Andy Hungee58e4a2023-07-07 13:47:37 -07007101void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007102{
Eric Laurent81784c32012-11-19 14:55:58 -08007103 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007104 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007105 // output audio to hardware
7106 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007107 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007108 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007109 status_t status = mActiveTrack->getNextBuffer(&buffer);
7110 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007111 // no need to pad with 0 for compressed audio
7112 if (audio_has_proportional_frames(mFormat)) {
7113 memset(curBuf, 0, frameCount * mFrameSize);
7114 }
Eric Laurent81784c32012-11-19 14:55:58 -08007115 break;
7116 }
7117 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7118 frameCount -= buffer.frameCount;
7119 curBuf += buffer.frameCount * mFrameSize;
7120 mActiveTrack->releaseBuffer(&buffer);
7121 }
Andy Hung2098f272014-02-27 14:00:06 -08007122 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007123 mSleepTimeUs = 0;
7124 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007125 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007126}
7127
Andy Hungee58e4a2023-07-07 13:47:37 -07007128void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007129{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007130 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007131 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007132 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007133 return;
7134 }
Andy Hung85ba3332021-04-27 17:40:26 -07007135 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7136 mSleepTimeUs = mActiveSleepTimeUs;
7137 } else {
7138 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007139 }
Andy Hung85ba3332021-04-27 17:40:26 -07007140 // Note: In S or later, we do not write zeroes for
7141 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007142}
7143
Andy Hungee58e4a2023-07-07 13:47:37 -07007144void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007145{
7146 {
Andy Hung972bec12023-08-31 16:13:39 -07007147 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007148 for (size_t i = 0; i < mTracks.size(); i++) {
7149 if (mTracks[i]->isFlushPending()) {
7150 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007151 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007152 }
7153 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007154 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007155 flushHw_l();
7156 }
7157 }
7158 PlaybackThread::threadLoop_exit();
7159}
7160
7161// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007162bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007163{
7164 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007165 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007166 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007167
Eric Laurent022a5132024-04-12 17:02:51 +00007168 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007169 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007170 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007171 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007172 const auto& mainTrack = mTracks[mTracks.size() - 1];
7173
7174 trackPaused = mainTrack->isPaused();
7175 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7176 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007177 }
7178
Eric Laurent022a5132024-04-12 17:02:51 +00007179 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007180}
7181
Andy Hungc5007f82023-08-29 14:26:09 -07007182// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007183bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007184 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007185{
7186 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007187 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007188
Eric Laurent10351942014-05-08 18:49:52 -07007189 AudioParameter param = AudioParameter(keyValuePair);
7190 int value;
7191 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007192 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007193 }
Eric Laurent10351942014-05-08 18:49:52 -07007194 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7195 // do not accept frame count changes if tracks are open as the track buffer
7196 // size depends on frame count and correct behavior would not be garantied
7197 // if frame count is changed after track creation
7198 if (!mTracks.isEmpty()) {
7199 status = INVALID_OPERATION;
7200 } else {
7201 reconfig = true;
7202 }
7203 }
7204 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007205 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007206 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007207 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007208 if (!mStandby) {
7209 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007210 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007211 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007212 }
Eric Laurent10351942014-05-08 18:49:52 -07007213 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007214 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007215 }
7216 if (status == NO_ERROR && reconfig) {
7217 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007218 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007219 }
7220 }
7221
Dean Wheatley68918102021-03-19 22:09:19 +11007222 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007223}
7224
Andy Hungee58e4a2023-07-07 13:47:37 -07007225uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007226{
7227 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007228 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007229 time = PlaybackThread::activeSleepTimeUs();
7230 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007231 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007232 }
7233 return time;
7234}
7235
Andy Hungee58e4a2023-07-07 13:47:37 -07007236uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007237{
7238 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007239 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007240 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7241 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007242 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007243 }
7244 return time;
7245}
7246
Andy Hungee58e4a2023-07-07 13:47:37 -07007247uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007248{
7249 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007250 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007251 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7252 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007253 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007254 }
7255 return time;
7256}
7257
Andy Hungee58e4a2023-07-07 13:47:37 -07007258void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007259{
7260 PlaybackThread::cacheParameters_l();
7261
7262 // use shorter standby delay as on normal output to release
7263 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007264 // no delay on outputs with HW A/V sync
7265 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007266 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007267 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007268 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007269 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007270 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007271 }
Eric Laurent81784c32012-11-19 14:55:58 -08007272}
7273
Andy Hungee58e4a2023-07-07 13:47:37 -07007274void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007275{
ziyangch8f194f12021-12-01 13:48:04 -08007276 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007277 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007278 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007279 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007280 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007281 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007282 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007283}
7284
Andy Hungee58e4a2023-07-07 13:47:37 -07007285int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007286 // If a VolumeShaper is active, we must wake up periodically to update volume.
7287 const int64_t NS_PER_MS = 1000000;
7288 return mVolumeShaperActive ?
7289 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7290}
7291
Eric Laurent81784c32012-11-19 14:55:58 -08007292// ----------------------------------------------------------------------------
7293
Andy Hungee58e4a2023-07-07 13:47:37 -07007294AsyncCallbackThread::AsyncCallbackThread(
7295 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007296 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007297 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007298 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007299 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007300 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007301{
7302}
7303
Andy Hungee58e4a2023-07-07 13:47:37 -07007304void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007305{
7306 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7307}
7308
Andy Hungee58e4a2023-07-07 13:47:37 -07007309bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007310{
7311 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007312 uint32_t writeAckSequence;
7313 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007314 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007315
7316 {
Andy Hungc5007f82023-08-29 14:26:09 -07007317 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007318 while (!((mWriteAckSequence & 1) ||
7319 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007320 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007321 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007322 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007323 }
7324
Eric Laurentbfb1b832013-01-07 09:53:42 -08007325 if (exitPending()) {
7326 break;
7327 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007328 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7329 mWriteAckSequence, mDrainSequence);
7330 writeAckSequence = mWriteAckSequence;
7331 mWriteAckSequence &= ~1;
7332 drainSequence = mDrainSequence;
7333 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007334 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007335 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007336 }
7337 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007338 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007339 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007340 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007341 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007342 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007343 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007344 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007345 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007346 if (asyncError != ASYNC_ERROR_NONE) {
7347 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007348 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007349 }
7350 }
7351 }
7352 return false;
7353}
7354
Andy Hungee58e4a2023-07-07 13:47:37 -07007355void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007356{
7357 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007358 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007359 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007360 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007361}
7362
Andy Hungee58e4a2023-07-07 13:47:37 -07007363void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007364{
Andy Hung972bec12023-08-31 16:13:39 -07007365 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007366 // bit 0 is cleared
7367 mWriteAckSequence = sequence << 1;
7368}
7369
Andy Hungee58e4a2023-07-07 13:47:37 -07007370void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007371{
Andy Hung972bec12023-08-31 16:13:39 -07007372 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007373 // ignore unexpected callbacks
7374 if (mWriteAckSequence & 2) {
7375 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007376 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007377 }
7378}
7379
Andy Hungee58e4a2023-07-07 13:47:37 -07007380void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381{
Andy Hung972bec12023-08-31 16:13:39 -07007382 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007383 // bit 0 is cleared
7384 mDrainSequence = sequence << 1;
7385}
7386
Andy Hungee58e4a2023-07-07 13:47:37 -07007387void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007388{
Andy Hung972bec12023-08-31 16:13:39 -07007389 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007390 // ignore unexpected callbacks
7391 if (mDrainSequence & 2) {
7392 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007393 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007394 }
7395}
7396
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007397void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007398{
Andy Hung972bec12023-08-31 16:13:39 -07007399 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007400 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007401 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007402}
7403
Eric Laurentbfb1b832013-01-07 09:53:42 -08007404
7405// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007406
7407/* static */
7408sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007409 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007410 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7411 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007412 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007413}
7414
Andy Hung583043b2023-07-17 17:05:00 -07007415OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007416 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7417 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007418 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007419 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007420{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007421 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007422 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007423 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007424}
7425
Andy Hungee58e4a2023-07-07 13:47:37 -07007426void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007427{
7428 if (mFlushPending || mHwPaused) {
7429 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007430 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007431 flushHw_l();
7432 } else {
7433 mMixerStatus = MIXER_DRAIN_ALL;
7434 threadLoop_drain();
7435 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007436 if (mUseAsyncWrite) {
7437 ALOG_ASSERT(mCallbackThread != 0);
7438 mCallbackThread->exit();
7439 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007440 PlaybackThread::threadLoop_exit();
7441}
7442
Andy Hungee58e4a2023-07-07 13:47:37 -07007443PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007444 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007445)
7446{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007447 size_t count = mActiveTracks.size();
7448
7449 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007450 bool doHwPause = false;
7451 bool doHwResume = false;
7452
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007453 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007454
Eric Laurentbfb1b832013-01-07 09:53:42 -08007455 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007456 for (const sp<IAfTrack>& t : mActiveTracks) {
7457 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007458#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007459 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007460#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007461 // Only consider last track started for volume and mixer state control.
7462 // In theory an older track could underrun and restart after the new one starts
7463 // but as we only care about the transition phase between two tracks on a
7464 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007465 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007466 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007467
Haynes Mathew George7844f672014-01-15 12:32:55 -08007468 if (track->isInvalid()) {
7469 ALOGW("An invalidated track shouldn't be in active list");
7470 tracksToRemove->add(track);
7471 continue;
7472 }
7473
Andy Hung8d31fd22023-06-26 19:20:57 -07007474 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007475 ALOGW("An idle track shouldn't be in active list");
7476 continue;
7477 }
7478
Kuowei Li23666472021-01-20 10:23:25 +08007479 if (track->isPausePending()) {
7480 track->pauseAck();
7481 // It is possible a track might have been flushed or stopped.
7482 // Other operations such as flush pending might occur on the next prepare.
7483 if (track->isPausing()) {
7484 track->setPaused();
7485 }
7486 // Always perform pause if last, as an immediate flush will change
7487 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007488 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007489 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007490 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007491 mHwPaused = true;
7492 }
7493 // If we were part way through writing the mixbuffer to
7494 // the HAL we must save this until we resume
7495 // BUG - this will be wrong if a different track is made active,
7496 // in that case we want to discard the pending data in the
7497 // mixbuffer and tell the client to present it again when the
7498 // track is resumed
7499 mPausedWriteLength = mCurrentWriteLength;
7500 mPausedBytesRemaining = mBytesRemaining;
7501 mBytesRemaining = 0; // stop writing
7502 }
7503 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007504 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007505 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007506 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007507 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007508 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007509 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007510 track->flushAck();
7511 if (last) {
7512 mFlushPending = true;
7513 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007514 } else if (track->isResumePending()){
7515 track->resumeAck();
7516 if (last) {
7517 if (mPausedBytesRemaining) {
7518 // Need to continue write that was interrupted
7519 mCurrentWriteLength = mPausedWriteLength;
7520 mBytesRemaining = mPausedBytesRemaining;
7521 mPausedBytesRemaining = 0;
7522 }
7523 if (mHwPaused) {
7524 doHwResume = true;
7525 mHwPaused = false;
7526 // threadLoop_mix() will handle the case that we need to
7527 // resume an interrupted write
7528 }
7529 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007530 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007531
Eric Laurent3df841a2016-07-15 15:15:40 -07007532 mLeftVolFloat = mRightVolFloat = -1.0;
7533
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007534 // Do not handle new data in this iteration even if track->framesReady()
7535 mixerStatus = MIXER_TRACKS_ENABLED;
7536 }
7537 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007538 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007539 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007540 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7541 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007542 if (last) {
7543 // make sure processVolume_l() will apply new volume even if 0
7544 mLeftVolFloat = mRightVolFloat = -1.0;
7545 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007546 }
7547
7548 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007549 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007550 if (previousTrack != 0) {
7551 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007552 // Flush any data still being written from last track
7553 mBytesRemaining = 0;
7554 if (mPausedBytesRemaining) {
7555 // Last track was paused so we also need to flush saved
7556 // mixbuffer state and invalidate track so that it will
7557 // re-submit that unwritten data when it is next resumed
7558 mPausedBytesRemaining = 0;
7559 // Invalidate is a bit drastic - would be more efficient
7560 // to have a flag to tell client that some of the
7561 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007562 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007563 }
7564 // flush data already sent to the DSP if changing audio session as audio
7565 // comes from a different source. Also invalidate previous track to force a
7566 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007567 if (previousTrack->sessionId() != track->sessionId()) {
7568 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007569 }
7570 }
7571 }
7572 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007573 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007574 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007575 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007576 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007577 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007578 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007579 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007580 mixerStatus = MIXER_TRACKS_READY;
7581 }
7582 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007583 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007584 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007585 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007586 // Hardware buffer can hold a large amount of audio so we must
7587 // wait for all current track's data to drain before we say
7588 // that the track is stopped.
7589 if (mBytesRemaining == 0) {
7590 // Only start draining when all data in mixbuffer
7591 // has been written
7592 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007593 track->setState(IAfTrackBase::STOPPING_2);
7594 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007595 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7596 if (last && !mStandby) {
7597 // do not modify drain sequence if we are already draining. This happens
7598 // when resuming from pause after drain.
7599 if ((mDrainSequence & 1) == 0) {
7600 mSleepTimeUs = 0;
7601 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7602 mixerStatus = MIXER_DRAIN_TRACK;
7603 mDrainSequence += 2;
7604 }
7605 if (mHwPaused) {
7606 // It is possible to move from PAUSED to STOPPING_1 without
7607 // a resume so we must ensure hardware is running
7608 doHwResume = true;
7609 mHwPaused = false;
7610 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007611 }
7612 }
Eric Laurente93cc032016-05-05 10:15:10 -07007613 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007614 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007615 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007616 }
7617 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007618 // Drain has completed or we are in standby, signal presentation complete
7619 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007620 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007621 mOutput->presentationComplete();
7622 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007623 track->reset();
7624 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007625 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007626 if (!mUseAsyncWrite) {
7627 // If we don't get explicit drain notification we must
7628 // register discontinuity regardless of whether this is
7629 // the previous (!last) or the upcoming (last) track
7630 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007631 mTimestampVerifier.discontinuity(
7632 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007633 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007634 }
7635 } else {
7636 // No buffers for this track. Give it a few chances to
7637 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007638 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007639 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007640 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007641 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007642 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007643 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007644 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7645 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007646 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007647 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007648 // it will then automatically call start() when data is available
7649 track->disable();
7650 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007651 } else if (last){
7652 mixerStatus = MIXER_TRACKS_ENABLED;
7653 }
7654 }
7655 }
7656 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007657 if (track->isReady()) { // check ready to prevent premature start.
7658 processVolume_l(track, last);
7659 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007660 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007661
Eric Laurentea0fade2013-10-04 16:23:48 -07007662 // make sure the pause/flush/resume sequence is executed in the right order.
7663 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7664 // before flush and then resume HW. This can happen in case of pause/flush/resume
7665 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007666 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007667 status_t result = mOutput->stream->pause();
7668 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007669 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007670 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007671 if (mFlushPending) {
7672 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007673 }
Eric Laurentfd477972013-10-25 18:10:40 -07007674 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007675 status_t result = mOutput->stream->resume();
7676 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007677 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007678
Eric Laurentbfb1b832013-01-07 09:53:42 -08007679 // remove all the tracks that need to be...
7680 removeTracks_l(*tracksToRemove);
7681
7682 return mixerStatus;
7683}
7684
Eric Laurentbfb1b832013-01-07 09:53:42 -08007685// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007686bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007687{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007688 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7689 mWriteAckSequence, mDrainSequence);
7690 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007691 return true;
7692 }
7693 return false;
7694}
7695
Andy Hungee58e4a2023-07-07 13:47:37 -07007696bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007697{
Andy Hung972bec12023-08-31 16:13:39 -07007698 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007699 return waitingAsyncCallback_l();
7700}
7701
Andy Hungee58e4a2023-07-07 13:47:37 -07007702void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007703{
Eric Laurente659ef42014-09-29 13:06:46 -07007704 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007705 // Flush anything still waiting in the mixbuffer
7706 mCurrentWriteLength = 0;
7707 mBytesRemaining = 0;
7708 mPausedWriteLength = 0;
7709 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007710 // reset bytes written count to reflect that DSP buffers are empty after flush.
7711 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007712
Eric Laurentbfb1b832013-01-07 09:53:42 -08007713 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007714 // discard any pending drain or write ack by incrementing sequence
7715 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7716 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007717 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007718 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7719 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007720 }
7721}
7722
Andy Hungee58e4a2023-07-07 13:47:37 -07007723void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007724{
Andy Hung972bec12023-08-31 16:13:39 -07007725 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007726 if (PlaybackThread::invalidateTracks_l(streamType)) {
7727 mFlushPending = true;
7728 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007729}
7730
Andy Hungee58e4a2023-07-07 13:47:37 -07007731void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007732 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007733 if (PlaybackThread::invalidateTracks_l(portIds)) {
7734 mFlushPending = true;
7735 }
7736}
7737
Eric Laurentbfb1b832013-01-07 09:53:42 -08007738// ----------------------------------------------------------------------------
7739
Andy Hungee58e4a2023-07-07 13:47:37 -07007740/* static */
7741sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007742 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007743 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007744 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007745}
7746
Andy Hung583043b2023-07-17 17:05:00 -07007747DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007748 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007749 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007750 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007751 mWaitTimeMs(UINT_MAX)
7752{
7753 addOutputTrack(mainThread);
7754}
7755
Andy Hungee58e4a2023-07-07 13:47:37 -07007756DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007757{
7758 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7759 mOutputTracks[i]->destroy();
7760 }
7761}
7762
Andy Hungee58e4a2023-07-07 13:47:37 -07007763void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007764{
7765 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007766 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007767 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007768 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007769 if (mMixerBufferValid) {
7770 memset(mMixerBuffer, 0, mMixerBufferSize);
7771 } else {
7772 memset(mSinkBuffer, 0, mSinkBufferSize);
7773 }
Eric Laurent81784c32012-11-19 14:55:58 -08007774 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007775 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007776 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007777 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007778 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007779}
7780
Andy Hungee58e4a2023-07-07 13:47:37 -07007781void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007782{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007783 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007784 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007785 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007786 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007787 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007788 }
7789 } else if (mBytesWritten != 0) {
7790 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7791 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007792 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007793 } else {
7794 // flush remaining overflow buffers in output tracks
7795 writeFrames = 0;
7796 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007797 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007798 }
7799}
7800
Andy Hungee58e4a2023-07-07 13:47:37 -07007801ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007802{
7803 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007804 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7805
7806 // Consider the first OutputTrack for timestamp and frame counting.
7807
7808 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7809 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7810 // we always claim success.
7811 if (i == 0) {
7812 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7813 ALOGD_IF(correction != 0 && writeFrames != 0,
7814 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7815 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7816 mFramesWritten -= correction;
7817 }
7818
7819 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007820 }
Andy Hungcf10d742020-04-28 15:38:24 -07007821 if (mStandby) {
7822 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007823 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007824 mStandby = false;
7825 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007826 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007827}
7828
Andy Hungee58e4a2023-07-07 13:47:37 -07007829void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007830{
7831 // DuplicatingThread implements standby by stopping all tracks
7832 for (size_t i = 0; i < outputTracks.size(); i++) {
7833 outputTracks[i]->stop();
7834 }
7835}
7836
Andy Hung8a5abfd2023-12-07 19:35:12 -08007837void DuplicatingThread::threadLoop_exit()
7838{
7839 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7840 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7841 // Do so here in the threadLoop_exit().
7842
7843 SortedVector <sp<IAfOutputTrack>> localTracks;
7844 {
7845 audio_utils::lock_guard l(mutex());
7846 localTracks = std::move(mOutputTracks);
7847 mOutputTracks.clear();
7848 }
7849 localTracks.clear();
7850 outputTracks.clear();
7851 PlaybackThread::threadLoop_exit();
7852}
7853
Andy Hungee58e4a2023-07-07 13:47:37 -07007854void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007855{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007856 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007857
7858 std::stringstream ss;
7859 const size_t numTracks = mOutputTracks.size();
7860 ss << " " << numTracks << " OutputTracks";
7861 if (numTracks > 0) {
7862 ss << ":";
7863 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007864 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007865 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007866 if (thread.get() != nullptr) {
7867 ss << thread.get() << ", " << thread->id();
7868 } else {
7869 ss << "null";
7870 }
7871 ss << ")";
7872 }
7873 }
7874 ss << "\n";
7875 std::string result = ss.str();
7876 write(fd, result.c_str(), result.size());
7877}
7878
Andy Hungee58e4a2023-07-07 13:47:37 -07007879void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007880{
7881 outputTracks = mOutputTracks;
7882}
7883
Andy Hungee58e4a2023-07-07 13:47:37 -07007884void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007885{
7886 outputTracks.clear();
7887}
7888
Andy Hungee58e4a2023-07-07 13:47:37 -07007889void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007890{
Andy Hung972bec12023-08-31 16:13:39 -07007891 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007892 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7893 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7894 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7895 const size_t frameCount =
7896 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7897 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7898 // from different OutputTracks and their associated MixerThreads (e.g. one may
7899 // nearly empty and the other may be dropping data).
7900
Svet Ganov33761132021-05-13 22:51:08 +00007901 // TODO b/182392769: use attribution source util, move to server edge
7902 AttributionSourceState attributionSource = AttributionSourceState();
7903 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007904 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007905 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007906 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007907 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007908 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007909 this,
7910 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007911 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007912 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007913 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007914 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007915 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7916 if (status != NO_ERROR) {
7917 ALOGE("addOutputTrack() initCheck failed %d", status);
7918 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007919 }
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02007920 if (!audioserver_flags::portid_volume_management()) {
7921 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7922 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007923 mOutputTracks.add(outputTrack);
7924 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7925 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007926}
7927
Andy Hungee58e4a2023-07-07 13:47:37 -07007928void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007929{
Andy Hung972bec12023-08-31 16:13:39 -07007930 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007931 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7932 if (mOutputTracks[i]->thread() == thread) {
7933 mOutputTracks[i]->destroy();
7934 mOutputTracks.removeAt(i);
7935 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007936 // NO_THREAD_SAFETY_ANALYSIS
7937 // Lambda workaround: as thread != this
7938 // we can safely call the remote thread getOutput.
7939 const bool equalOutput =
7940 [&](){ return thread->getOutput() == mOutput; }();
7941 if (equalOutput) {
7942 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007943 }
Eric Laurent81784c32012-11-19 14:55:58 -08007944 return;
7945 }
7946 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007947 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007948}
7949
Andy Hungc5007f82023-08-29 14:26:09 -07007950// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007951void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007952{
7953 mWaitTimeMs = UINT_MAX;
7954 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007955 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007956 if (strong != 0) {
7957 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7958 if (waitTimeMs < mWaitTimeMs) {
7959 mWaitTimeMs = waitTimeMs;
7960 }
7961 }
7962 }
7963}
7964
Andy Hungee58e4a2023-07-07 13:47:37 -07007965bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007966{
7967 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007968 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007969 if (thread == 0) {
7970 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7971 outputTracks[i].get());
7972 return false;
7973 }
Andy Hung87c693c2023-07-06 20:56:16 -07007974 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007975 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007976 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007977 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7978 thread.get());
7979 return false;
7980 }
7981 }
7982 return true;
7983}
7984
Andy Hungee58e4a2023-07-07 13:47:37 -07007985void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007986 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007987{
Kevin Rocard12381092018-04-11 09:19:59 -07007988 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7989 outputTrack->setMetadatas(metadata.tracks);
7990 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007991}
7992
Andy Hungee58e4a2023-07-07 13:47:37 -07007993uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007994{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007995 // return half the wait time in microseconds.
7996 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007997}
7998
Andy Hungee58e4a2023-07-07 13:47:37 -07007999void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008000{
8001 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
8002 updateWaitTime_l();
8003
8004 MixerThread::cacheParameters_l();
8005}
8006
Eric Laurentb3f315a2021-07-13 15:09:05 +02008007// ----------------------------------------------------------------------------
8008
Andy Hungee58e4a2023-07-07 13:47:37 -07008009/* static */
8010sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07008011 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07008012 AudioStreamOut* output,
8013 audio_io_handle_t id,
8014 bool systemReady,
8015 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07008016 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07008017}
8018
Andy Hung583043b2023-07-17 17:05:00 -07008019SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02008020 AudioStreamOut* output,
8021 audio_io_handle_t id,
8022 bool systemReady,
8023 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07008024 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02008025{
8026}
8027
Andy Hungee58e4a2023-07-07 13:47:37 -07008028void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02008029 // if mSupportedLatencyModes is empty, the HAL stream does not support
8030 // latency mode control and we can exit.
8031 if (mSupportedLatencyModes.empty()) {
8032 return;
8033 }
Eric Laurent4c85e372024-02-23 16:50:06 +00008034 // Do not update the HAL latency mode if no track is active
8035 if (mActiveTracks.isEmpty()) {
8036 return;
8037 }
8038
Eric Laurent68a40a82022-05-03 18:15:04 +02008039 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
8040 if (mSupportedLatencyModes.size() == 1) {
8041 // If the HAL only support one latency mode currently, confirm the choice
8042 latencyMode = mSupportedLatencyModes[0];
8043 } else if (mSupportedLatencyModes.size() > 1) {
8044 // Request low latency if:
8045 // - The low latency mode is requested by the spatializer controller
8046 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
8047 // AND
8048 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02008049 for (const auto& track : mActiveTracks) {
8050 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01008051 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02008052 break;
8053 }
8054 }
Eric Laurent68a40a82022-05-03 18:15:04 +02008055 }
8056
8057 if (latencyMode != mSetLatencyMode) {
8058 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08008059 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
8060 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02008061 if (status == NO_ERROR) {
8062 mSetLatencyMode = latencyMode;
8063 }
8064 }
8065}
8066
Andy Hungee58e4a2023-07-07 13:47:37 -07008067status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008068 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008069 return BAD_VALUE;
8070 }
Andy Hung972bec12023-08-31 16:13:39 -07008071 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008072 mRequestedLatencyMode = mode;
8073 return NO_ERROR;
8074}
8075
Andy Hungee58e4a2023-07-07 13:47:37 -07008076void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008077NO_THREAD_SAFETY_ANALYSIS
8078// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008079{
8080 bool hasVirtualizer = false;
8081 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008082 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008083 {
Andy Hung972bec12023-08-31 16:13:39 -07008084 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008085 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008086 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008087 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008088 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8089 }
8090
8091 finalDownMixer = mFinalDownMixer;
8092 mFinalDownMixer.clear();
8093 }
8094
8095 if (hasVirtualizer) {
8096 if (finalDownMixer != nullptr) {
8097 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008098 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008099 }
8100 finalDownMixer.clear();
8101 } else if (!hasDownMixer) {
8102 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008103 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008104 EFFECT_UIID_DOWNMIX, &descriptors);
8105 if (status != NO_ERROR) {
8106 return;
8107 }
8108 ALOG_ASSERT(!descriptors.empty(),
8109 "%s getDescriptors() returned no error but empty list", __func__);
8110
8111 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8112 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008113 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008114
8115 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8116 ALOGW("%s error creating downmixer %d", __func__, status);
8117 finalDownMixer.clear();
8118 } else {
8119 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008120 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008121 }
8122 }
8123
8124 {
Andy Hung972bec12023-08-31 16:13:39 -07008125 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008126 mFinalDownMixer = finalDownMixer;
8127 }
8128}
8129
Andy Hunge2514462023-12-06 14:59:24 -08008130void SpatializerThread::threadLoop_exit()
8131{
8132 // The Spatializer EffectHandle must be released on the PlaybackThread
8133 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8134 mFinalDownMixer.clear();
8135
8136 PlaybackThread::threadLoop_exit();
8137}
8138
Eric Laurent81784c32012-11-19 14:55:58 -08008139// ----------------------------------------------------------------------------
8140// Record
8141// ----------------------------------------------------------------------------
8142
Andy Hung583043b2023-07-17 17:05:00 -07008143sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008144 AudioStreamIn* input,
8145 audio_io_handle_t id,
8146 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008147 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008148}
8149
Andy Hung583043b2023-07-17 17:05:00 -07008150RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008151 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008152 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008153 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008154 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008155 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008156 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008157 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008158 mActiveTracks(&this->mLocalLog),
8159 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008160 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008161 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008162 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8163 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008164 // mFastCapture below
8165 , mFastCaptureFutex(0)
8166 // mInputSource
8167 // mPipeSink
8168 // mPipeSource
8169 , mPipeFramesP2(0)
8170 // mPipeMemory
8171 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008172 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008173 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008174{
Glenn Kastend7dca052015-03-05 16:05:54 -08008175 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008176 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008177
George Burgess IVa8f90c12020-05-14 11:27:19 -07008178 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008179 mIsMsdDevice = strcmp(
8180 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8181 }
8182
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008183 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008184
Andy Hungc8fddf32018-08-08 18:32:37 -07008185 // TODO: We may also match on address as well as device type for
8186 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008187 // TODO: This property should be ensure that only contains one single device type.
8188 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8189 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008190 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8191 : AUDIO_DEVICE_NONE));
8192
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008193 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008194 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008195 size_t numCounterOffers = 0;
8196 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008197#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008198 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008199#else
8200 (void)
8201#endif
8202 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008203 ALOG_ASSERT(index == 0);
8204
8205 // initialize fast capture depending on configuration
8206 bool initFastCapture;
8207 switch (kUseFastCapture) {
8208 case FastCapture_Never:
8209 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008210 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008211 break;
8212 case FastCapture_Always:
8213 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008214 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008215 break;
8216 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008217 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008218 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008219 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008220 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8221 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8222 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008223 break;
8224 // case FastCapture_Dynamic:
8225 }
8226
8227 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008228 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008229 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008230 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8231 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008232 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008233 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008234 const sp<MemoryDealer> roHeap(readOnlyHeap());
8235 sp<IMemory> pipeMemory;
8236 if ((roHeap == 0) ||
8237 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008238 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008239 ALOGE("not enough memory for pipe buffer size=%zu; "
8240 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8241 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8242 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008243 goto failed;
8244 }
8245 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8246 memset(pipeBuffer, 0, pipeSize);
8247 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008248 const NBAIO_Format offersFast[1] = {format};
8249 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008250 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008251 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008252 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008253 mPipeSink = pipe;
8254 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008255 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008256 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008257 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008258 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008259 mPipeSource = pipeReader;
8260 mPipeFramesP2 = pipeFramesP2;
8261 mPipeMemory = pipeMemory;
8262
8263 // create fast capture
8264 mFastCapture = new FastCapture();
8265 FastCaptureStateQueue *sq = mFastCapture->sq();
8266#ifdef STATE_QUEUE_DUMP
8267 // FIXME
8268#endif
8269 FastCaptureState *state = sq->begin();
8270 state->mCblk = NULL;
8271 state->mInputSource = mInputSource.get();
8272 state->mInputSourceGen++;
8273 state->mPipeSink = pipe;
8274 state->mPipeSinkGen++;
8275 state->mFrameCount = mFrameCount;
8276 state->mCommand = FastCaptureState::COLD_IDLE;
8277 // already done in constructor initialization list
8278 //mFastCaptureFutex = 0;
8279 state->mColdFutexAddr = &mFastCaptureFutex;
8280 state->mColdGen++;
8281 state->mDumpState = &mFastCaptureDumpState;
8282#ifdef TEE_SINK
8283 // FIXME
8284#endif
Andy Hung583043b2023-07-17 17:05:00 -07008285 mFastCaptureNBLogWriter =
8286 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008287 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8288 sq->end();
8289 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8290
8291 // start the fast capture
8292 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8293 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008294 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008295 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008296#ifdef AUDIO_WATCHDOG
8297 // FIXME
8298#endif
8299
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008300 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008301 }
Andy Hung8946a282018-04-19 20:04:56 -07008302#ifdef TEE_SINK
8303 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8304 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8305#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008306failed: ;
8307
8308 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008309}
8310
Andy Hungee58e4a2023-07-07 13:47:37 -07008311RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008312{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008313 if (mFastCapture != 0) {
8314 FastCaptureStateQueue *sq = mFastCapture->sq();
8315 FastCaptureState *state = sq->begin();
8316 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8317 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8318 if (old == -1) {
8319 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8320 }
8321 }
8322 state->mCommand = FastCaptureState::EXIT;
8323 sq->end();
8324 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8325 mFastCapture->join();
8326 mFastCapture.clear();
8327 }
Andy Hung583043b2023-07-17 17:05:00 -07008328 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8329 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008330 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008331}
8332
Andy Hungee58e4a2023-07-07 13:47:37 -07008333void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008334{
Glenn Kastend7dca052015-03-05 16:05:54 -08008335 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008336}
8337
Andy Hungee58e4a2023-07-07 13:47:37 -07008338void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008339{
8340 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008341 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008342 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008343 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008344 track->invalidate();
8345 }
8346 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008347 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008348}
8349
Andy Hungee58e4a2023-07-07 13:47:37 -07008350bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008351{
Eric Laurent81784c32012-11-19 14:55:58 -08008352 nsecs_t lastWarning = 0;
8353
8354 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008355
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008356reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008357 {
Andy Hung972bec12023-08-31 16:13:39 -07008358 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008359 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008360 }
8361
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008362 // used to request a deferred sleep, to be executed later while mutex is unlocked
8363 uint32_t sleepUs = 0;
8364
Andy Hung95c94a22023-10-20 16:41:18 -07008365 // timestamp correction enable is determined under lock, used in processing step.
8366 bool timestampCorrectionEnabled = false;
8367
Andy Hung446f4df2019-02-21 12:26:41 -08008368 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8369
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008370 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008371 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008372 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8373 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008374 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008375 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008376
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008377 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008378 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008379
Glenn Kasten735f45f2014-08-18 15:51:59 -07008380 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008381 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008382
Glenn Kasten735f45f2014-08-18 15:51:59 -07008383 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008384 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008385
Eric Laurent33403f02020-05-29 18:35:06 -07008386 bool silenceFastCapture = false;
8387
Andy Hungc5007f82023-08-29 14:26:09 -07008388 { // scope for mutex()
8389 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008390
Eric Laurent021cf962014-05-13 10:18:14 -07008391 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008392
Eric Laurent000a4192014-01-29 15:17:32 -08008393 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008394 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008395 if (exitPending()) {
8396 break;
8397 }
8398
Eric Laurent5c25d562016-07-13 17:17:45 -07008399 // sleep with mutex unlocked
8400 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008401 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008402 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008403 ATRACE_END();
8404 sleepUs = 0;
8405 continue;
8406 }
8407
Glenn Kasten2b806402013-11-20 16:37:38 -08008408 // if no active track(s), then standby and release wakelock
8409 size_t size = mActiveTracks.size();
8410 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008411 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008412 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008413 releaseWakeLock_l();
8414 ALOGV("RecordThread: loop stopping");
8415 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008416 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008417 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008418 goto reacquire_wakelock;
8419 }
8420
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008421 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008422 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008423 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008424 if (activeTrack) { // ensure track release is outside lock.
8425 oldActiveTracks.emplace_back(std::move(activeTrack));
8426 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008427 activeTrack = mActiveTracks[i];
8428 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008429 if (activeTrack->isFastTrack()) {
8430 ALOG_ASSERT(fastTrackToRemove == 0);
8431 fastTrackToRemove = activeTrack;
8432 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008433 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008434 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008435 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008436 continue;
8437 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008438
Andy Hung8d31fd22023-06-26 19:20:57 -07008439 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008440 switch (activeTrackState) {
8441
Andy Hung8d31fd22023-06-26 19:20:57 -07008442 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008443 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008444 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008445 if (activeTrack->isFastTrack()) {
8446 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8447 // Keep a ref on fast track to wait for FastCapture thread to get updated
8448 // state before potential track removal
8449 fastTrackToRemove = activeTrack;
8450 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008451 doBroadcast = true;
8452 size--;
8453 continue;
8454
Andy Hung8d31fd22023-06-26 19:20:57 -07008455 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008456 sleepUs = 10000;
8457 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008458 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008459 continue;
8460
Andy Hung8d31fd22023-06-26 19:20:57 -07008461 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008462 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008463 if (mStandby) {
8464 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008465 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008466 mStandby = false;
8467 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008468 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008469 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008470 break;
8471
Andy Hung8d31fd22023-06-26 19:20:57 -07008472 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008473 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008474 break;
8475
Andy Hung8d31fd22023-06-26 19:20:57 -07008476 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8477 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8478 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008479 default:
Andy Hungce685402018-10-05 17:23:27 -07008480 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8481 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008482 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008483
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008484 if (activeTrack->isFastTrack()) {
8485 ALOG_ASSERT(!mFastTrackAvail);
8486 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008487 // if the active fast track is silenced either:
8488 // 1) silence the whole capture from fast capture buffer if this is
8489 // the only active track
8490 // 2) invalidate this track: this will cause the client to reconnect and possibly
8491 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008492 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008493 if (activeTrack->isSilenced()) {
8494 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008495 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008496 } else {
8497 silenceFastCapture = true;
8498 }
8499 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008500 // Invalidate fast tracks if access to audio history is required as this is not
8501 // possible with fast tracks. Once the fast track has been invalidated, no new
8502 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8503 if (mMaxSharedAudioHistoryMs != 0) {
8504 invalidate = true;
8505 }
8506 if (invalidate) {
8507 activeTrack->invalidate();
8508 ALOG_ASSERT(fastTrackToRemove == 0);
8509 fastTrackToRemove = activeTrack;
8510 removeTrack_l(activeTrack);
8511 mActiveTracks.remove(activeTrack);
8512 size--;
8513 continue;
8514 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008515 fastTrack = activeTrack;
8516 }
Eric Laurent33403f02020-05-29 18:35:06 -07008517
8518 activeTracks.add(activeTrack);
8519 i++;
8520
Glenn Kasten9e982352013-08-14 14:39:50 -07008521 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008522
Andy Hungab65b182023-09-06 19:41:47 -07008523 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008524
Kevin Rocard069c2712018-03-29 19:09:14 -07008525 updateMetadata_l();
8526
Eric Laurent5c25d562016-07-13 17:17:45 -07008527 if (allStopped) {
8528 standbyIfNotAlreadyInStandby();
8529 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008530 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008531 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008532 }
8533
8534 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008535 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008536 if (sleepUs == 0) {
8537 sleepUs = kRecordThreadSleepUs;
8538 }
8539 continue;
8540 }
8541 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008542
Andy Hung95c94a22023-10-20 16:41:18 -07008543 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008544 lockEffectChains_l(effectChains);
8545 }
8546
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008547 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008548
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008549 size_t size = effectChains.size();
8550 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008551 // thread mutex is not locked, but effect chain is locked
8552 effectChains[i]->process_l();
8553 }
8554
Glenn Kasten735f45f2014-08-18 15:51:59 -07008555 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008556 if (mFastCapture != 0) {
8557 FastCaptureStateQueue *sq = mFastCapture->sq();
8558 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008559 bool didModify = false;
8560 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008561 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8562 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8563 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8564 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8565 if (old == -1) {
8566 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8567 }
8568 }
8569 state->mCommand = FastCaptureState::READ_WRITE;
8570#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008571 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008572 FastThreadDumpState::kSamplingNforLowRamDevice :
8573 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008574#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008575 didModify = true;
8576 }
8577 audio_track_cblk_t *cblkOld = state->mCblk;
8578 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8579 if (cblkNew != cblkOld) {
8580 state->mCblk = cblkNew;
8581 // block until acked if removing a fast track
8582 if (cblkOld != NULL) {
8583 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8584 }
8585 didModify = true;
8586 }
jiabin01c8f562018-07-19 17:47:28 -07008587 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8588 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8589 if (state->mFastPatchRecordBufferProvider != abp) {
8590 state->mFastPatchRecordBufferProvider = abp;
8591 state->mFastPatchRecordFormat = fastTrack == 0 ?
8592 AUDIO_FORMAT_INVALID : fastTrack->format();
8593 didModify = true;
8594 }
Eric Laurent33403f02020-05-29 18:35:06 -07008595 if (state->mSilenceCapture != silenceFastCapture) {
8596 state->mSilenceCapture = silenceFastCapture;
8597 didModify = true;
8598 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008599 sq->end(didModify);
8600 if (didModify) {
8601 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008602#if 0
8603 if (kUseFastCapture == FastCapture_Dynamic) {
8604 mNormalSource = mPipeSource;
8605 }
8606#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008607 }
8608 }
8609
Glenn Kasten735f45f2014-08-18 15:51:59 -07008610 // now run the fast track destructor with thread mutex unlocked
8611 fastTrackToRemove.clear();
8612
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008613 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8614 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8615 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8616 // If destination is non-contiguous, first read past the nominal end of buffer, then
8617 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008618
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008619 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008620 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008621 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008622
8623 // If an NBAIO source is present, use it to read the normal capture's data
8624 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008625 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008626
8627 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8628 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8629 // we immediately retry the read() to get data and prevent another overflow.
8630 for (int retries = 0; retries <= 2; ++retries) {
8631 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8632 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8633 framesToRead);
8634 if (framesRead != OVERRUN) break;
8635 }
8636
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008637 const ssize_t availableToRead = mPipeSource->availableToRead();
8638 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008639 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008640 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008641 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8642 "more frames to read than fifo size, %zd > %zu",
8643 availableToRead, mPipeFramesP2);
8644 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8645 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8646 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8647 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008648 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8649 }
8650 if (framesRead < 0) {
8651 status_t status = (status_t) framesRead;
8652 switch (status) {
8653 case OVERRUN:
8654 ALOGW("overrun on read from pipe");
8655 framesRead = 0;
8656 break;
8657 case NEGOTIATE:
8658 ALOGE("re-negotiation is needed");
8659 framesRead = -1; // Will cause an attempt to recover.
8660 break;
8661 default:
8662 ALOGE("unknown error %d on read from pipe", status);
8663 break;
8664 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008665 }
8666 // otherwise use the HAL / AudioStreamIn directly
8667 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008668 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008669 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008670 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008671 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008672 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008673 if (result < 0) {
8674 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008675 } else {
8676 framesRead = bytesRead / mFrameSize;
8677 }
8678 }
8679
Andy Hung446f4df2019-02-21 12:26:41 -08008680 const int64_t lastIoEndNs = systemTime(); // end IO timing
8681
Andy Hung3f0c9022016-01-15 17:49:46 -08008682 // Update server timestamp with server stats
8683 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008684 if (framesRead >= 0) {
8685 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8686 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8687 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008688
8689 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008690 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008691 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008692 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008693 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8694 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8695 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008696 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008697 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8698
8699 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008700 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008701 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008702 id(), (long long)time, (long long)position);
8703 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8704 position = correctedTimestamp.mFrames;
8705 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008706 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008707 id(), (long long)time, (long long)position);
8708 }
8709
Andy Hung3f0c9022016-01-15 17:49:46 -08008710 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8711 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8712 // Note: In general record buffers should tend to be empty in
8713 // a properly running pipeline.
8714 //
8715 // Also, it is not advantageous to call get_presentation_position during the read
8716 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008717 } else {
8718 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008719 }
8720 }
Andy Hunge6c37112019-02-26 17:38:10 -08008721
8722 // From the timestamp, input read latency is negative output write latency.
8723 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008724 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008725 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8726 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8727 mLatencyMs.add(latencyMs);
8728 }
8729
Andy Hung3f0c9022016-01-15 17:49:46 -08008730 // Use this to track timestamp information
8731 // ALOGD("%s", mTimestamp.toString().c_str());
8732
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008733 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008734 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008735 // Force input into standby so that it tries to recover at next read attempt
8736 inputStandBy();
8737 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008738 }
8739 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008740 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008741 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008742 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008743 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008744
Andy Hung8946a282018-04-19 20:04:56 -07008745#ifdef TEE_SINK
8746 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8747#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008748 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008749 {
8750 size_t part1 = mRsmpInFramesP2 - rear;
8751 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008752 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008753 (framesRead - part1) * mFrameSize);
8754 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008755 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008756 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008757
8758 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008759
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008760 // loop over each active track
8761 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008762 if (activeTrack) { // ensure track release is outside lock.
8763 oldActiveTracks.emplace_back(std::move(activeTrack));
8764 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008765 activeTrack = activeTracks[i];
8766
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008767 // skip fast tracks, as those are handled directly by FastCapture
8768 if (activeTrack->isFastTrack()) {
8769 continue;
8770 }
8771
Andy Hung73c02e42015-03-29 01:13:58 -07008772 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008773 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8774
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008775 enum {
8776 OVERRUN_UNKNOWN,
8777 OVERRUN_TRUE,
8778 OVERRUN_FALSE
8779 } overrun = OVERRUN_UNKNOWN;
8780
8781 // loop over getNextBuffer to handle circular sink
8782 for (;;) {
8783
Andy Hung8d31fd22023-06-26 19:20:57 -07008784 activeTrack->sinkBuffer().frameCount = ~0;
8785 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8786 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008787 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8788
Andy Hung73c02e42015-03-29 01:13:58 -07008789 // check available frames and handle overrun conditions
8790 // if the record track isn't draining fast enough.
8791 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008792 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008793 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008794 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008795 overrun = OVERRUN_TRUE;
8796 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008797 if (framesOut == 0 || framesIn == 0) {
8798 break;
8799 }
8800
Andy Hung6770c6f2015-04-07 13:43:36 -07008801 // Don't allow framesOut to be larger than what is possible with resampling
8802 // from framesIn.
8803 // This isn't strictly necessary but helps limit buffer resizing in
8804 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008805 if (audio_is_linear_pcm(activeTrack->format())) {
8806 framesOut = min(framesOut,
8807 destinationFramesPossible(
8808 framesIn, mSampleRate, activeTrack->sampleRate()));
8809 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008810
8811 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008812 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008813 // straight from RecordThread buffer to RecordTrack buffer.
8814 AudioBufferProvider::Buffer buffer;
8815 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008816 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008817 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008818 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008819 ALOGV_IF(buffer.frameCount != framesOut,
8820 "%s() read less than expected (%zu vs %zu)",
8821 __func__, buffer.frameCount, framesOut);
8822 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008823 memcpy(activeTrack->sinkBuffer().raw,
8824 buffer.raw, buffer.frameCount * mFrameSize);
8825 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008826 } else {
8827 framesOut = 0;
8828 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008829 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008830 }
8831 } else {
8832 // process frames from the RecordThread buffer provider to the RecordTrack
8833 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008834 framesOut = activeTrack->recordBufferConverter()->convert(
8835 activeTrack->sinkBuffer().raw,
8836 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008837 framesOut);
8838 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008839
8840 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8841 overrun = OVERRUN_FALSE;
8842 }
8843
Andy Hung93bb5732023-05-04 21:16:34 -07008844 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8845 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008846 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008847 if (framesToDrop == 0) {
8848 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008849 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008850 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008851 // Sanitize before releasing if the track has no access to the source data
8852 // An idle UID receives silence from non virtual devices until active
8853 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008854 memset(activeTrack->sinkBuffer().raw,
8855 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008856 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008857 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008858 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008859 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008860 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008861 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008862 }
8863 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008864
8865 switch (overrun) {
8866 case OVERRUN_TRUE:
8867 // client isn't retrieving buffers fast enough
8868 if (!activeTrack->setOverflow()) {
8869 nsecs_t now = systemTime();
8870 // FIXME should lastWarning per track?
8871 if ((now - lastWarning) > kWarningThrottleNs) {
8872 ALOGW("RecordThread: buffer overflow");
8873 lastWarning = now;
8874 }
8875 }
8876 break;
8877 case OVERRUN_FALSE:
8878 activeTrack->clearOverflow();
8879 break;
8880 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008881 break;
8882 }
8883
Andy Hung3f0c9022016-01-15 17:49:46 -08008884 // update frame information and push timestamp out
8885 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008886 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008887 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8888 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008889 }
8890
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008891unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008892 // enable changes in effect chain
8893 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008894 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008895 if (audio_has_proportional_frames(mFormat)
8896 && loopCount == lastLoopCountRead + 1) {
8897 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8898 const double jitterMs =
8899 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8900 {framesRead, readPeriodNs},
8901 {0, 0} /* lastTimestamp */, mSampleRate);
8902 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8903
Andy Hung972bec12023-08-31 16:13:39 -07008904 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008905 mIoJitterMs.add(jitterMs);
8906 mProcessTimeMs.add(processMs);
8907 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008908 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008909 // update timing info.
8910 mLastIoBeginNs = lastIoBeginNs;
8911 mLastIoEndNs = lastIoEndNs;
8912 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008913 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008914 mThreadloopExecutor.process(); // process any remaining deferred actions.
8915 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008916
Glenn Kasten93e471f2013-08-19 08:40:07 -07008917 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008918
8919 {
Andy Hung972bec12023-08-31 16:13:39 -07008920 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008921 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008922 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008923 track->invalidate();
8924 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008925 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008926 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008927 }
8928
8929 releaseWakeLock();
8930
8931 ALOGV("RecordThread %p exiting", this);
8932 return false;
8933}
8934
Andy Hungee58e4a2023-07-07 13:47:37 -07008935void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008936{
8937 if (!mStandby) {
8938 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008939 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008940 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008941 mStandby = true;
8942 }
8943}
8944
Andy Hungee58e4a2023-07-07 13:47:37 -07008945void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008946{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008947 // Idle the fast capture if it's currently running
8948 if (mFastCapture != 0) {
8949 FastCaptureStateQueue *sq = mFastCapture->sq();
8950 FastCaptureState *state = sq->begin();
8951 if (!(state->mCommand & FastCaptureState::IDLE)) {
8952 state->mCommand = FastCaptureState::COLD_IDLE;
8953 state->mColdFutexAddr = &mFastCaptureFutex;
8954 state->mColdGen++;
8955 mFastCaptureFutex = 0;
8956 sq->end();
8957 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8958 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8959#if 0
8960 if (kUseFastCapture == FastCapture_Dynamic) {
8961 // FIXME
8962 }
8963#endif
8964#ifdef AUDIO_WATCHDOG
8965 // FIXME
8966#endif
8967 } else {
8968 sq->end(false /*didModify*/);
8969 }
8970 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008971 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008972 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008973
8974 // If going into standby, flush the pipe source.
8975 if (mPipeSource.get() != nullptr) {
8976 const ssize_t flushed = mPipeSource->flush();
8977 if (flushed > 0) {
8978 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8979 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8980 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8981 }
8982 }
Eric Laurent81784c32012-11-19 14:55:58 -08008983}
8984
Andy Hungc5007f82023-08-29 14:26:09 -07008985// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008986sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008987 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008988 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008989 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008990 audio_format_t format,
8991 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008992 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008993 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008994 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008995 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008996 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008997 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008998 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008999 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02009000 audio_port_handle_t portId,
9001 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08009002{
Glenn Kasten74935e42013-12-19 08:56:45 -08009003 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009004 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07009005 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08009006 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07009007 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009008 audio_input_flags_t requestedFlags = *flags;
9009 uint32_t sampleRate;
9010
9011 lStatus = initCheck();
9012 if (lStatus != NO_ERROR) {
9013 ALOGE("createRecordTrack_l() audio driver not initialized");
9014 goto Exit;
9015 }
9016
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009017 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
9018 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
9019 lStatus = BAD_VALUE;
9020 goto Exit;
9021 }
9022
Eric Laurentec376dc2021-04-08 20:41:22 +02009023 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01009024 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009025 lStatus = PERMISSION_DENIED;
9026 goto Exit;
9027 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009028 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07009029 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009030 lStatus = BAD_VALUE;
9031 goto Exit;
9032 }
9033 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08009034 if (*pSampleRate == 0) {
9035 *pSampleRate = mSampleRate;
9036 }
9037 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07009038
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009039 // special case for FAST flag considered OK if fast capture is present and access to
9040 // audio history is not required
9041 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07009042 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
9043 }
9044
Eric Laurentf14db3c2017-12-08 14:20:36 -08009045 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07009046 if ((*flags & inputFlags) != *flags) {
9047 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
9048 " input flags (%08x)",
9049 *flags, inputFlags);
9050 *flags = (audio_input_flags_t)(*flags & inputFlags);
9051 }
Eric Laurent81784c32012-11-19 14:55:58 -08009052
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009053 // client expresses a preference for FAST and no access to audio history,
9054 // but we get the final say
9055 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009056 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009057 // we formerly checked for a callback handler (non-0 tid),
9058 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00009059 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009060 //
Phil Burk7ed66a12019-04-18 13:20:30 -07009061 // Frame count is not specified (0), or is less than or equal the pipe depth.
9062 // It is OK to provide a higher capacity than requested.
9063 // We will force it to mPipeFramesP2 below.
9064 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009065 // PCM data
9066 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009067 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009068 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009069 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009070 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009071 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009072 hasFastCapture() &&
9073 // there are sufficient fast track slots available
9074 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009075 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009076 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009077 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009078 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009079 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009080 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009081 audio_input_flags_t old = *flags;
9082 chain->checkInputFlagCompatibility(flags);
9083 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009084 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9085 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009086 }
9087 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009088 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009089 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9090 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009091 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009092 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9093 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009094 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009095 this, frameCount, mFrameCount, mPipeFramesP2,
9096 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009097 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009098 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009099 }
9100 }
9101
Eric Laurentf14db3c2017-12-08 14:20:36 -08009102 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9103 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9104 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9105 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9106 lStatus = BAD_TYPE;
9107 goto Exit;
9108 }
9109
Glenn Kasten74105912014-07-03 12:28:53 -07009110 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009111 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009112 // fast track: frame count is exactly the pipe depth
9113 frameCount = mPipeFramesP2;
9114 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009115 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009116 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009117 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9118 // or 20 ms if there is a fast capture
9119 // TODO This could be a roundupRatio inline, and const
9120 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9121 * sampleRate + mSampleRate - 1) / mSampleRate;
9122 // minimum number of notification periods is at least kMinNotifications,
9123 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9124 static const size_t kMinNotifications = 3;
9125 static const uint32_t kMinMs = 30;
9126 // TODO This could be a roundupRatio inline
9127 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9128 // TODO This could be a roundupRatio inline
9129 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9130 maxNotificationFrames;
9131 const size_t minFrameCount = maxNotificationFrames *
9132 max(kMinNotifications, minNotificationsByMs);
9133 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009134 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9135 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009136 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009137 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009138 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009139 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009140
Andy Hungc5007f82023-08-29 14:26:09 -07009141 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009142 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009143 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009144 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009145 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009146 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009147 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009148 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009149 }
Eric Laurent81784c32012-11-19 14:55:58 -08009150
Andy Hung8d31fd22023-06-26 19:20:57 -07009151 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009152 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009153 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009154 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009155 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009156
Glenn Kasten03003332013-08-06 15:40:54 -07009157 lStatus = track->initCheck();
9158 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009159 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009160 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009161 goto Exit;
9162 }
9163 mTracks.add(track);
9164
Eric Laurent05067782016-06-01 18:27:28 -07009165 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009166 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9167 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9168 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009169 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009170 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009171
9172 if (maxSharedAudioHistoryMs != 0) {
9173 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9174 }
Eric Laurent81784c32012-11-19 14:55:58 -08009175 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009176
Eric Laurent81784c32012-11-19 14:55:58 -08009177 lStatus = NO_ERROR;
9178
9179Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009180 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009181 return track;
9182}
9183
Andy Hungee58e4a2023-07-07 13:47:37 -07009184status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009185 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009186 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009187{
9188 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9189 sp<ThreadBase> strongMe = this;
9190 status_t status = NO_ERROR;
9191
9192 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009193 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009194 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009195 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009196 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009197 event, triggerSession,
9198 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009199 }
9200
9201 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009202 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009203 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009204 if (recordTrack->isInvalid()) {
9205 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009206 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9207 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009208 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009209 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009210 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009211 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9212 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009213 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009214 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009215 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009216 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009217 }
9218 return status;
9219 }
9220
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009221 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9222 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9223 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009224 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009225 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009226 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009227 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009228 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009229 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009230 if (recordTrack->isInvalid()) {
9231 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009232 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9233 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009234 // STARTING_2 forces destroy to call stopInput.
9235 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009236 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9237 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009238 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009239 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009240 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009241 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009242 // Someone else has changed state, let them take over,
9243 // leave mState in the new state.
9244 recordTrack->clearSyncStartEvent();
9245 return INVALID_OPERATION;
9246 }
9247 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009248 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009249 ALOGW("%s(%d): startInput failed, status %d",
9250 __func__, recordTrack->id(), status);
9251 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9252 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009253 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009254 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009255 return status;
9256 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009257 sendIoConfigEvent_l(
9258 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009259 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009260
9261 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9262
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009263 // Catch up with current buffer indices if thread is already running.
9264 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9265 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9266 // see previously buffered data before it called start(), but with greater risk of overrun.
9267
Andy Hung8d31fd22023-06-26 19:20:57 -07009268 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009269 if (!recordTrack->isDirect()) {
9270 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009271 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009272 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009273 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009274 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009275 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009276 return status;
9277 }
Eric Laurent81784c32012-11-19 14:55:58 -08009278}
9279
Andy Hungee58e4a2023-07-07 13:47:37 -07009280void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009281{
Andy Hungee58e4a2023-07-07 13:47:37 -07009282 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009283
9284 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009285 sp<IAfTrackBase> ptr =
9286 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9287 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009288 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009289 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009290 }
Eric Laurent81784c32012-11-19 14:55:58 -08009291 }
9292}
9293
Andy Hungee58e4a2023-07-07 13:47:37 -07009294bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009295 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009296 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009297 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009298 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009299 return false;
9300 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009301 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009302 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009303
Andy Hungabfab202019-03-07 19:45:54 -08009304 // NOTE: Waiting here is important to keep stop synchronous.
9305 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009306 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009307 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009308 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009309 }
Andy Hungce685402018-10-05 17:23:27 -07009310
Andy Hung8d31fd22023-06-26 19:20:57 -07009311 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009312 ALOGV("Record stopped OK");
9313 return true;
9314 }
Andy Hungce685402018-10-05 17:23:27 -07009315
9316 // don't handle anything - we've been invalidated or restarted and in a different state
9317 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009318 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009319 return false;
9320}
9321
Andy Hungee58e4a2023-07-07 13:47:37 -07009322bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009323{
9324 return false;
9325}
9326
Andy Hungee58e4a2023-07-07 13:47:37 -07009327status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009328{
9329#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9330 if (!isValidSyncEvent(event)) {
9331 return BAD_VALUE;
9332 }
9333
Glenn Kastend848eb42016-03-08 13:42:11 -08009334 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009335 status_t ret = NAME_NOT_FOUND;
9336
Andy Hung972bec12023-08-31 16:13:39 -07009337 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009338
9339 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009340 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009341 if (eventSession == track->sessionId()) {
9342 (void) track->setSyncEvent(event);
9343 ret = NO_ERROR;
9344 }
9345 }
9346 return ret;
9347#else
9348 return BAD_VALUE;
9349#endif
9350}
9351
Andy Hungee58e4a2023-07-07 13:47:37 -07009352status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009353 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009354{
9355 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009356 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009357 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009358 return NO_INIT;
9359 }
jiabin9ff780e2018-03-19 18:19:52 -07009360 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9361 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009362}
9363
Andy Hungee58e4a2023-07-07 13:47:37 -07009364status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009365 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009366{
Paul McLean12340082019-03-19 09:35:05 -06009367 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009368 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009369 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009370 return NO_INIT;
9371 }
Paul McLean12340082019-03-19 09:35:05 -06009372 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009373}
9374
Andy Hungee58e4a2023-07-07 13:47:37 -07009375status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009376{
Paul McLean12340082019-03-19 09:35:05 -06009377 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009378 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009379 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009380 return NO_INIT;
9381 }
Paul McLean12340082019-03-19 09:35:05 -06009382 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009383}
9384
Andy Hungee58e4a2023-07-07 13:47:37 -07009385status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009386 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9387 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009388 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009389 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9390}
9391
Andy Hungee58e4a2023-07-07 13:47:37 -07009392status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009393 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9394 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009395
Eric Laurentec376dc2021-04-08 20:41:22 +02009396 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9397 return BAD_VALUE;
9398 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009399
9400 if (sharedAudioStartMs < 0
9401 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009402 return BAD_VALUE;
9403 }
9404
Eric Laurent2407ce32021-04-26 14:56:03 +02009405 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9406 // As we cannot detect more than one wraparound, only accept values up current write position
9407 // after one wraparound
9408 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9409 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009410 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009411 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9412 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009413 // Bring the start frame position within the input buffer to match the documented
9414 // "best effort" behavior of the API.
9415 if (sharedOffset < 0) {
9416 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009417 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009418 sharedAudioStartFrames =
9419 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009420 }
9421
Eric Laurentec376dc2021-04-08 20:41:22 +02009422 mSharedAudioPackageName = sharedAudioPackageName;
9423 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009424 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009425 } else {
9426 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009427 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009428 }
9429 return NO_ERROR;
9430}
9431
Andy Hungee58e4a2023-07-07 13:47:37 -07009432void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009433 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9434 mSharedAudioStartFrames = -1;
9435 mSharedAudioPackageName = "";
9436}
9437
Andy Hungee58e4a2023-07-07 13:47:37 -07009438ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009439{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009440 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009441 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009442 }
9443 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009444 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009445 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009446 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009447 }
9448 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009449 MetadataUpdate change;
9450 change.recordMetadataUpdate = metadata.tracks;
9451 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009452}
9453
Andy Hungc5007f82023-08-29 14:26:09 -07009454// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009455void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009456{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009457 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009458 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009459
Eric Laurent81784c32012-11-19 14:55:58 -08009460 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009461 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009462 removeTrack_l(track);
9463 }
9464}
9465
Andy Hungee58e4a2023-07-07 13:47:37 -07009466void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009467{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009468 String8 result;
9469 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009470 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009471
Eric Laurent81784c32012-11-19 14:55:58 -08009472 mTracks.remove(track);
9473 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009474 if (track->isFastTrack()) {
9475 ALOG_ASSERT(!mFastTrackAvail);
9476 mFastTrackAvail = true;
9477 }
Eric Laurent81784c32012-11-19 14:55:58 -08009478}
9479
Andy Hungee58e4a2023-07-07 13:47:37 -07009480void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009481{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009482 AudioStreamIn *input = mInput;
9483 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9484 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009485 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009486 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009487 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009488 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009489 }
Andy Hungbfa64962017-06-12 14:43:19 -07009490
9491 if (input != nullptr) {
9492 dprintf(fd, " Hal stream dump:\n");
9493 (void)input->stream->dump(fd);
9494 }
9495
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009496 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009497 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009498
Glenn Kasten2f90c512015-12-02 11:40:09 -08009499 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9500 // while we are dumping it. It may be inconsistent, but it won't mutate!
9501 // This is a large object so we place it on the heap.
9502 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009503 const std::unique_ptr<FastCaptureDumpState> copy =
9504 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009505 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009506}
9507
Andy Hungee58e4a2023-07-07 13:47:37 -07009508void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009509{
Eric Laurent81784c32012-11-19 14:55:58 -08009510 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009511 size_t numtracks = mTracks.size();
9512 size_t numactive = mActiveTracks.size();
9513 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009514 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009515 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009516 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009517 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009518 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009519 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009520 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009521 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009522 if (track != 0) {
9523 bool active = mActiveTracks.indexOf(track) >= 0;
9524 if (active) {
9525 numactiveseen++;
9526 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009527 result.append(prefix);
9528 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009529 }
Eric Laurent81784c32012-11-19 14:55:58 -08009530 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009531 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009532 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009533 }
9534
Marco Nelissenb2208842014-02-07 14:00:50 -08009535 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009536 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009537 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009538 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009539 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009540 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009541 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009542 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009543 result.append(prefix);
9544 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009545 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009546 }
Eric Laurent81784c32012-11-19 14:55:58 -08009547
9548 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009549 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009550}
9551
Andy Hungee58e4a2023-07-07 13:47:37 -07009552void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009553{
Andy Hung972bec12023-08-31 16:13:39 -07009554 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009555 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009556 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009557 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009558 track->setSilenced(silenced);
9559 }
9560 }
9561}
Andy Hung73c02e42015-03-29 01:13:58 -07009562
Andy Hung8d31fd22023-06-26 19:20:57 -07009563void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009564{
Andy Hung87c693c2023-07-06 20:56:16 -07009565 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009566 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009567 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009568 const int32_t rear = recordThread->mRsmpInRear;
9569 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009570 if (mRecordTrack->startFrames() >= 0) {
9571 int32_t startFrames = mRecordTrack->startFrames();
9572 // Accept a recent wraparound of mRsmpInRear
9573 if (startFrames <= rear) {
9574 deltaFrames = rear - startFrames;
9575 } else {
9576 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009577 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009578 // start frame cannot be further in the past than start of resampling buffer
9579 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9580 deltaFrames = recordThread->mRsmpInFrames;
9581 }
9582 }
9583 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009584}
9585
Andy Hung8d31fd22023-06-26 19:20:57 -07009586void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009587 size_t *framesAvailable, bool *hasOverrun)
9588{
Andy Hung87c693c2023-07-06 20:56:16 -07009589 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009590 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009591 const int32_t rear = recordThread->mRsmpInRear;
9592 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009593 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009594
9595 size_t framesIn;
9596 bool overrun = false;
9597 if (filled < 0) {
9598 // should not happen, but treat like a massive overrun and re-sync
9599 framesIn = 0;
9600 mRsmpInFront = rear;
9601 overrun = true;
9602 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9603 framesIn = (size_t) filled;
9604 } else {
9605 // client is not keeping up with server, but give it latest data
9606 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009607 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9608 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009609 overrun = true;
9610 }
9611 if (framesAvailable != NULL) {
9612 *framesAvailable = framesIn;
9613 }
9614 if (hasOverrun != NULL) {
9615 *hasOverrun = overrun;
9616 }
9617}
9618
Eric Laurent81784c32012-11-19 14:55:58 -08009619// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009620status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009621 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009622{
Andy Hung87c693c2023-07-06 20:56:16 -07009623 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009624 if (threadBase == 0) {
9625 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009626 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009627 return NOT_ENOUGH_DATA;
9628 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009629 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009630 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009631 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009632 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009633 // FIXME should not be P2 (don't want to increase latency)
9634 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009635 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009636 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009637
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009638 front &= recordThread->mRsmpInFramesP2 - 1;
9639 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009640 if (part1 > (size_t) filled) {
9641 part1 = filled;
9642 }
9643 size_t ask = buffer->frameCount;
9644 ALOG_ASSERT(ask > 0);
9645 if (part1 > ask) {
9646 part1 = ask;
9647 }
9648 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009649 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009650 buffer->raw = NULL;
9651 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009652 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009653 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009654 }
9655
Andy Hung57446612015-04-19 23:56:46 -07009656 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009657 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009658 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009659 return NO_ERROR;
9660}
9661
9662// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009663void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009664 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009665{
Hongwei Wang95e37682019-04-12 11:13:36 -07009666 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009667 if (stepCount == 0) {
9668 return;
9669 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009670 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009671 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009672 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009673 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009674 buffer->frameCount = 0;
9675}
9676
Andy Hungee58e4a2023-07-07 13:47:37 -07009677void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009678{
Andy Hung972bec12023-08-31 16:13:39 -07009679 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009680 checkBtNrec_l();
9681}
9682
Andy Hungee58e4a2023-07-07 13:47:37 -07009683void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009684{
9685 // disable AEC and NS if the device is a BT SCO headset supporting those
9686 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009687 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009688 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009689 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9690 for (size_t i = 0; i < mEffectChains.size(); i++) {
9691 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9692 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9693 }
9694 }
9695}
9696
Andy Hung97a893e2015-03-29 01:03:07 -07009697
Andy Hungee58e4a2023-07-07 13:47:37 -07009698bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009699 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009700{
9701 bool reconfig = false;
9702
Eric Laurent10351942014-05-08 18:49:52 -07009703 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009704
Eric Laurent10351942014-05-08 18:49:52 -07009705 audio_format_t reqFormat = mFormat;
9706 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009707 // 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 +08009708 [[maybe_unused]] audio_channel_mask_t channelMask =
9709 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009710
9711 AudioParameter param = AudioParameter(keyValuePair);
9712 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009713
9714 // scope for AutoPark extends to end of method
9715 AutoPark<FastCapture> park(mFastCapture);
9716
Eric Laurent10351942014-05-08 18:49:52 -07009717 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9718 // channel count change can be requested. Do we mandate the first client defines the
9719 // HAL sampling rate and channel count or do we allow changes on the fly?
9720 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9721 samplingRate = value;
9722 reconfig = true;
9723 }
9724 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009725 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009726 status = BAD_VALUE;
9727 } else {
9728 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009729 reconfig = true;
9730 }
Eric Laurent10351942014-05-08 18:49:52 -07009731 }
9732 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9733 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009734 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009735 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009736 status = BAD_VALUE;
9737 } else {
9738 channelMask = mask;
9739 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009740 }
Eric Laurent10351942014-05-08 18:49:52 -07009741 }
9742 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9743 // do not accept frame count changes if tracks are open as the track buffer
9744 // size depends on frame count and correct behavior would not be guaranteed
9745 // if frame count is changed after track creation
9746 if (mActiveTracks.size() > 0) {
9747 status = INVALID_OPERATION;
9748 } else {
9749 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009750 }
Eric Laurent10351942014-05-08 18:49:52 -07009751 }
9752 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009753 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009754 }
9755 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9756 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009757 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009758 }
Glenn Kastene198c362013-08-13 09:13:36 -07009759
Eric Laurent10351942014-05-08 18:49:52 -07009760 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009761 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009762 if (status == INVALID_OPERATION) {
9763 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009764 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009765 }
9766 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009767 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009768 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9769 if (mInput->stream->getAudioProperties(&config) == OK &&
9770 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9771 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009772 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009773 status = NO_ERROR;
9774 }
Eric Laurent81784c32012-11-19 14:55:58 -08009775 }
Eric Laurent10351942014-05-08 18:49:52 -07009776 if (status == NO_ERROR) {
9777 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009778 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009779 }
9780 }
Eric Laurent81784c32012-11-19 14:55:58 -08009781 }
Eric Laurent10351942014-05-08 18:49:52 -07009782
Eric Laurent81784c32012-11-19 14:55:58 -08009783 return reconfig;
9784}
9785
Andy Hungee58e4a2023-07-07 13:47:37 -07009786String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009787{
Andy Hung972bec12023-08-31 16:13:39 -07009788 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009789 if (initCheck() == NO_ERROR) {
9790 String8 out_s8;
9791 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9792 return out_s8;
9793 }
Eric Laurent81784c32012-11-19 14:55:58 -08009794 }
Andy Hung920f6572022-10-06 12:09:49 -07009795 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009796}
9797
Andy Hungab65b182023-09-06 19:41:47 -07009798void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009799 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009800 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009801 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009802 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009803 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009804 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009805 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9806 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009807 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009808 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009809 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009810 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009811 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009812 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009813 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009814 break;
9815 }
Andy Hungab65b182023-09-06 19:41:47 -07009816 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009817}
9818
Andy Hungee58e4a2023-07-07 13:47:37 -07009819void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009820{
Dean Wheatley6c009512023-10-23 09:34:14 +11009821 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9822 mSampleRate = audioConfig.sample_rate;
9823 mChannelMask = audioConfig.channel_mask;
9824 if (!audio_is_input_channel(mChannelMask)) {
9825 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9826 }
9827
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009828 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009829
9830 // Get actual HAL format.
9831 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9832 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9833 // Get format from the shim, which will be different than the HAL format
9834 // if recording compressed audio from IEC61937 wrapped sources.
9835 mFormat = audioConfig.format;
9836 if (!audio_is_valid_format(mFormat)) {
9837 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9838 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009839 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009840 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9841 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009842 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009843 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009844 ALOGI("HAL format %#x is not linear pcm", mFormat);
9845 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009846 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009847 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9848 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009849 result = mInput->stream->getBufferSize(&mBufferSize);
9850 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009851 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009852 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9853 "mBufferSize=%zu, mFrameCount=%zu",
9854 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009855
Eric Laurentec376dc2021-04-08 20:41:22 +02009856 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9857 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009858 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009859
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009860 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9861 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009862
9863 audio_input_flags_t flags = mInput->flags;
9864 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9865 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009866 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009867 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9868 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9869 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9870 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9871 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9872 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009873}
9874
Andy Hungee58e4a2023-07-07 13:47:37 -07009875uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009876{
Andy Hung972bec12023-08-31 16:13:39 -07009877 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009878 uint32_t result;
9879 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9880 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009881 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009882 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009883}
9884
Andy Hungee58e4a2023-07-07 13:47:37 -07009885KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009886{
Glenn Kastend848eb42016-03-08 13:42:11 -08009887 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009888 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009889 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009890 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009891 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009892 if (ids.indexOfKey(sessionId) < 0) {
9893 ids.add(sessionId, true);
9894 }
9895 }
9896 return ids;
9897}
9898
Andy Hungee58e4a2023-07-07 13:47:37 -07009899AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009900{
Andy Hung972bec12023-08-31 16:13:39 -07009901 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009902 AudioStreamIn *input = mInput;
9903 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009904 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009905 return input;
9906}
9907
Andy Hungc5007f82023-08-29 14:26:09 -07009908// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009909sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009910{
9911 if (mInput == NULL) {
9912 return NULL;
9913 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009914 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009915}
9916
Andy Hungee58e4a2023-07-07 13:47:37 -07009917status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009918{
Eric Laurent81784c32012-11-19 14:55:58 -08009919 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009920 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009921 chain->setInBuffer(NULL);
9922 chain->setOutBuffer(NULL);
9923
9924 checkSuspendOnAddEffectChain_l(chain);
9925
Eric Laurent1b928682014-10-02 19:41:47 -07009926 // make sure enabled pre processing effects state is communicated to the HAL as we
9927 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009928 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009929
Eric Laurent81784c32012-11-19 14:55:58 -08009930 mEffectChains.add(chain);
9931
9932 return NO_ERROR;
9933}
9934
Andy Hungee58e4a2023-07-07 13:47:37 -07009935size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009936{
9937 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009938
9939 for (size_t i = 0; i < mEffectChains.size(); i++) {
9940 if (chain == mEffectChains[i]) {
9941 mEffectChains.removeAt(i);
9942 break;
9943 }
Eric Laurent81784c32012-11-19 14:55:58 -08009944 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009945 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009946}
9947
Andy Hungee58e4a2023-07-07 13:47:37 -07009948status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009949 audio_patch_handle_t *handle)
9950{
9951 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009952
9953 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009954 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009955 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009956 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009957 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009958 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009959 }
9960
Eric Laurentd8365c52017-07-16 15:27:05 -07009961 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009962
9963 // store new source and send to effects
9964 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9965 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009966 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009967 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009968 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009969 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009970
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009971 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009972 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9973 status = hwDevice->createAudioPatch(patch->num_sources,
9974 patch->sources,
9975 patch->num_sinks,
9976 patch->sinks,
9977 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009978 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009979 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9980 patch->sinks[0].ext.mix.usecase.source,
9981 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009982 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009983 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009984
jiabinc52b1ff2019-10-31 17:20:42 -07009985 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009986 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009987 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009988 }
Eric Laurent296fb132015-05-01 11:38:42 -07009989
Andy Hungc2b11cb2020-04-22 09:04:01 -07009990 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009991 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009992 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009993 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009994 // also dispatch to active AudioRecords
9995 for (const auto &track : mActiveTracks) {
9996 track->logEndInterval();
9997 track->logBeginInterval(pathSourcesAsString);
9998 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009999 // Force meteadata update after a route change
10000 mActiveTracks.setHasChanged();
10001
Eric Laurent1c333e22014-05-20 10:48:17 -070010002 return status;
10003}
10004
Andy Hungee58e4a2023-07-07 13:47:37 -070010005status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -070010006{
10007 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010008
jiabinc52b1ff2019-10-31 17:20:42 -070010009 mPatch = audio_patch{};
10010 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -070010011
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010012 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010013 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10014 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010015 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010016 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -070010017 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010018 // Force meteadata update after a route change
10019 mActiveTracks.setHasChanged();
10020
Eric Laurent1c333e22014-05-20 10:48:17 -070010021 return status;
10022}
10023
Andy Hungee58e4a2023-07-07 13:47:37 -070010024void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -070010025{
Andy Hung972bec12023-08-31 16:13:39 -070010026 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -070010027 mOutDevices = outDevices;
10028 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
10029 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010030 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -070010031 }
10032}
10033
Andy Hungee58e4a2023-07-07 13:47:37 -070010034int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +020010035{
10036 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010037 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +020010038 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010039 int32_t oldestFront = mRsmpInRear;
10040 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +020010041 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010042 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +020010043 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +020010044 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +020010045 if (filled > maxFilled) {
10046 oldestFront = front;
10047 maxFilled = filled;
10048 }
Eric Laurentec376dc2021-04-08 20:41:22 +020010049 }
Andy Hung920f6572022-10-06 12:09:49 -070010050 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010051 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
10052 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010053 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +020010054}
10055
Andy Hungee58e4a2023-07-07 13:47:37 -070010056void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +020010057{
10058 if (offset == 0) {
10059 return;
10060 }
10061 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010062 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +020010063 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -070010064 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010065 }
10066}
10067
Andy Hungee58e4a2023-07-07 13:47:37 -070010068void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010069{
10070 // This is the formula for calculating the temporary buffer size.
10071 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10072 // 1 full output buffer, regardless of the alignment of the available input.
10073 // The value is somewhat arbitrary, and could probably be even larger.
10074 // A larger value should allow more old data to be read after a track calls start(),
10075 // without increasing latency.
10076 //
10077 // Note this is independent of the maximum downsampling ratio permitted for capture.
10078 size_t minRsmpInFrames = mFrameCount * 7;
10079
10080 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10081 // capture history available to another client using the same session ID:
10082 // dimension the resampler input buffer accordingly.
10083
10084 // Get oldest client read position: getOldestFront_l() must be called before altering
10085 // mRsmpInRear, or mRsmpInFrames
10086 int32_t previousFront = getOldestFront_l();
10087 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10088 int32_t previousRear = mRsmpInRear;
10089 mRsmpInRear = 0;
10090
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010091 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010092 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010093 "resizeInputBuffer_l() called with invalid max shared history %d",
10094 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010095 if (maxSharedAudioHistoryMs != 0) {
10096 // resizeInputBuffer_l should never be called with a non zero shared history if the
10097 // buffer was not already allocated
10098 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10099 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10100 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10101 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010102 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010103 return;
10104 }
10105 mRsmpInFrames = rsmpInFrames;
10106 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010107 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010108 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10109 // initialized
10110 if (mRsmpInFrames < minRsmpInFrames) {
10111 mRsmpInFrames = minRsmpInFrames;
10112 }
10113 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10114
10115 // TODO optimize audio capture buffer sizes ...
10116 // Here we calculate the size of the sliding buffer used as a source
10117 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10118 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10119 // be better to have it derived from the pipe depth in the long term.
10120 // The current value is higher than necessary. However it should not add to latency.
10121
10122 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10123 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10124
10125 void *rsmpInBuffer;
10126 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10127 // if posix_memalign fails, will segv here.
10128 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10129
10130 // Copy audio history if any from old buffer before freeing it
10131 if (previousRear != 0) {
10132 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10133 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10134
10135 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10136 previousFront &= previousRsmpInFramesP2 - 1;
10137 size_t part1 = previousRsmpInFramesP2 - previousFront;
10138 if (part1 > (size_t) unread) {
10139 part1 = unread;
10140 }
10141 if (part1 != 0) {
10142 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10143 part1 * mFrameSize);
10144 mRsmpInRear = part1;
10145 part1 = unread - part1;
10146 if (part1 != 0) {
10147 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10148 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10149 mRsmpInRear += part1;
10150 }
10151 }
10152 // Update front for all clients according to new rear
10153 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10154 } else {
10155 mRsmpInRear = 0;
10156 }
10157 free(mRsmpInBuffer);
10158 mRsmpInBuffer = rsmpInBuffer;
10159}
10160
Andy Hungee58e4a2023-07-07 13:47:37 -070010161void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010162{
Andy Hung972bec12023-08-31 16:13:39 -070010163 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010164 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010165 if (record->getSource()) {
10166 mSource = record->getSource();
10167 }
Eric Laurent83b88082014-06-20 18:31:16 -070010168}
10169
Andy Hungee58e4a2023-07-07 13:47:37 -070010170void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010171{
Andy Hung972bec12023-08-31 16:13:39 -070010172 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010173 if (mSource == record->getSource()) {
10174 mSource = mInput;
10175 }
Eric Laurent83b88082014-06-20 18:31:16 -070010176 destroyTrack_l(record);
10177}
10178
Andy Hungee58e4a2023-07-07 13:47:37 -070010179void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010180{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010181 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010182 config->role = AUDIO_PORT_ROLE_SINK;
10183 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10184 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010185 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10186 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10187 config->flags.input = mInput->flags;
10188 }
Eric Laurent83b88082014-06-20 18:31:16 -070010189}
Eric Laurent1c333e22014-05-20 10:48:17 -070010190
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191// ----------------------------------------------------------------------------
10192// Mmap
10193// ----------------------------------------------------------------------------
10194
Andy Hung7aa7d102023-07-07 15:58:48 -070010195// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10196// MmapPlaybackThread or MmapCaptureThread instance.
10197class MmapThreadHandle : public MmapStreamInterface {
10198public:
10199 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10200 ~MmapThreadHandle() override;
10201
10202 // MmapStreamInterface virtuals
10203 status_t createMmapBuffer(int32_t minSizeFrames,
10204 struct audio_mmap_buffer_info* info) final;
10205 status_t getMmapPosition(struct audio_mmap_position* position) final;
10206 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10207 status_t start(const AudioClient& client,
10208 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10209 status_t stop(audio_port_handle_t handle) final;
10210 status_t standby() final;
10211 status_t reportData(const void* buffer, size_t frameCount) final;
10212private:
10213 const sp<IAfMmapThread> mThread;
10214};
10215
10216/* static */
10217sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10218 const sp<IAfMmapThread>& mmapThread) {
10219 return sp<MmapThreadHandle>::make(mmapThread);
10220}
10221
10222MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010223 : mThread(thread)
10224{
Phil Burk9fabbf82017-08-03 12:02:00 -070010225 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010226}
10227
Andy Hung7aa7d102023-07-07 15:58:48 -070010228// MmapStreamInterface could be directly implemented by MmapThread excepting this
10229// special handling on adapter dtor.
10230MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231{
Phil Burk9fabbf82017-08-03 12:02:00 -070010232 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010233}
10234
Andy Hung7aa7d102023-07-07 15:58:48 -070010235status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010236 struct audio_mmap_buffer_info *info)
10237{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010238 return mThread->createMmapBuffer(minSizeFrames, info);
10239}
10240
Andy Hung7aa7d102023-07-07 15:58:48 -070010241status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243 return mThread->getMmapPosition(position);
10244}
10245
Andy Hung7aa7d102023-07-07 15:58:48 -070010246status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010247 int64_t *timeNanos) {
10248 return mThread->getExternalPosition(position, timeNanos);
10249}
10250
Andy Hung7aa7d102023-07-07 15:58:48 -070010251status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010252 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010253{
jiabind1f1cb62020-03-24 11:57:57 -070010254 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010255}
10256
Andy Hung7aa7d102023-07-07 15:58:48 -070010257status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010259 return mThread->stop(handle);
10260}
10261
Andy Hung7aa7d102023-07-07 15:58:48 -070010262status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010263{
Eric Laurent18b57012017-02-13 16:23:52 -080010264 return mThread->standby();
10265}
10266
Andy Hung7aa7d102023-07-07 15:58:48 -070010267status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10268{
jiabinfc791ee2023-02-15 19:43:40 +000010269 return mThread->reportData(buffer, frameCount);
10270}
10271
Eric Laurent6acd1d42017-01-04 14:23:29 -080010272
Andy Hungee58e4a2023-07-07 13:47:37 -070010273MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010274 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010275 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010276 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010277 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010278 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010279 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010280 mActiveTracks(&this->mLocalLog),
10281 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10282 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010283{
Eric Laurent18b57012017-02-13 16:23:52 -080010284 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285 readHalParameters_l();
10286}
10287
Andy Hungee58e4a2023-07-07 13:47:37 -070010288void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289{
10290 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10291}
10292
Andy Hungee58e4a2023-07-07 13:47:37 -070010293void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294{
Andy Hung8d31fd22023-06-26 19:20:57 -070010295 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010296 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010297 {
Andy Hung972bec12023-08-31 16:13:39 -070010298 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010299 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010300 activeTracks.add(t);
10301 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010302 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010303 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010304 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305 stop(t->portId());
10306 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010307 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010308 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010309 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010310 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010311 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312 }
10313}
10314
10315
Andy Hung8d672e02023-09-15 18:19:28 -070010316void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010317 audio_stream_type_t streamType __unused,
10318 audio_session_t sessionId,
10319 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010320 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010321 audio_port_handle_t portId)
10322{
10323 mAttr = *attr;
10324 mSessionId = sessionId;
10325 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010326 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327 mPortId = portId;
10328}
10329
Andy Hungee58e4a2023-07-07 13:47:37 -070010330status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010331 struct audio_mmap_buffer_info *info)
10332{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010333 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010334 if (mHalStream == 0) {
10335 return NO_INIT;
10336 }
Eric Laurent18b57012017-02-13 16:23:52 -080010337 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338 return mHalStream->createMmapBuffer(minSizeFrames, info);
10339}
10340
Andy Hungee58e4a2023-07-07 13:47:37 -070010341status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010343 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010344 if (mHalStream == 0) {
10345 return NO_INIT;
10346 }
10347 return mHalStream->getMmapPosition(position);
10348}
10349
Andy Hungee58e4a2023-07-07 13:47:37 -070010350status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010351{
Eric Laurentdda206a2022-07-08 17:28:35 +020010352 // The HAL must receive track metadata before starting the stream
10353 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010354 status_t ret = mHalStream->start();
10355 if (ret != NO_ERROR) {
10356 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10357 return ret;
10358 }
Andy Hungcf10d742020-04-28 15:38:24 -070010359 if (mStandby) {
10360 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010361 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010362 mStandby = false;
10363 }
Eric Laurent331679c2018-04-16 17:03:16 -070010364 return NO_ERROR;
10365}
10366
Andy Hungee58e4a2023-07-07 13:47:37 -070010367status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010368 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369 audio_port_handle_t *handle)
10370{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010371 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010372 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010373 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374 if (mHalStream == 0) {
10375 return NO_INIT;
10376 }
10377
10378 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010379
Eric Laurentdda206a2022-07-08 17:28:35 +020010380 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010381 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010382 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010383 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010384 }
10385
10386 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10387
10388 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010389 AttributionSourceState adjAttributionSource;
10390 if (!com::android::media::audio::audioserver_permissions()) {
10391 adjAttributionSource = afutils::checkAttributionSourcePackage(
10392 client.attributionSource);
10393 } else {
10394 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10395 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10396 client.attributionSource,
10397 mAfThreadCallback->getPermissionProvider()
10398 );
10399 if (!validatedRes.has_value()) {
10400 ALOGE("MMAP client package validation fail: %s",
10401 validatedRes.error().toString8().c_str());
10402 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10403 }
10404 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10405 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010406
Andy Hung3f49ebb2023-09-19 14:48:41 -070010407 const auto localSessionId = mSessionId;
10408 auto localAttr = mAttr;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020010409 float volume = 0.0f;
Eric Laurenta54f1282017-07-01 19:39:32 -070010410 if (isOutput()) {
10411 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10412 config.sample_rate = mSampleRate;
10413 config.channel_mask = mChannelMask;
10414 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010415 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010416 audio_output_flags_t flags =
10417 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010418 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010419 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010420 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010421 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010422 mutex().unlock();
10423 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10424 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010425 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010426 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010427 &config,
10428 flags,
10429 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010430 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010431 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010432 &isSpatialized,
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020010433 &isBitPerfect,
10434 &volume);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010435 mutex().lock();
10436 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010437 ALOGD_IF(!secondaryOutputs.empty(),
10438 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010440 audio_config_base_t config;
10441 config.sample_rate = mSampleRate;
10442 config.channel_mask = mChannelMask;
10443 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010444 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010445 mutex().unlock();
10446 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010447 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010448 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010449 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010450 &config,
10451 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10452 &deviceId,
10453 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010454 mutex().lock();
10455 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010456 }
10457 // APM should not chose a different input or output stream for the same set of attributes
10458 // and audo configuration
10459 if (ret != NO_ERROR || io != mId) {
10460 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10461 __FUNCTION__, ret, io, mId);
10462 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010463 }
10464
10465 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010466 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010467 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010468 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469 } else {
jiabin09609032022-06-15 19:26:01 +000010470 {
10471 // Add the track record before starting input so that the silent status for the
10472 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010473 setClientSilencedState_l(portId, false /*silenced*/);
10474 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010475 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010476 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010477 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010478 }
10479
10480 // abort if start is rejected by audio policy manager
10481 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010482 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010483 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010484 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010485 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010486 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010487 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010488 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010489 }
Andy Hungc5007f82023-08-29 14:26:09 -070010490 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010491 } else {
10492 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010493 }
jiabin09609032022-06-15 19:26:01 +000010494 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 return PERMISSION_DENIED;
10496 }
10497
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010498 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010499 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10500 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010501 mChannelMask, mSessionId, isOutput(),
10502 client.attributionSource,
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020010503 IPCThreadState::self()->getCallingPid(), portId,
10504 volume);
jiabin09609032022-06-15 19:26:01 +000010505 if (!isOutput()) {
10506 track->setSilenced_l(isClientSilenced_l(portId));
10507 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010508
Eric Laurent4eb58f12018-12-07 16:41:02 -080010509 if (isOutput()) {
10510 // force volume update when a new track is added
10511 mHalVolFloat = -1.0f;
10512 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010513 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010514 if (t->isSilenced_l()
10515 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010516 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010517 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010518 }
10519 }
10520
Eric Laurent6acd1d42017-01-04 14:23:29 -080010521 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010522 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010523 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010524 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010525 chain->incTrackCnt();
10526 chain->incActiveTrackCnt();
10527 }
10528
Andy Hungc2b11cb2020-04-22 09:04:01 -070010529 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010530 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010531
10532 if (mActiveTracks.size() == 1) {
10533 ret = exitStandby_l();
10534 }
10535
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536 broadcast_l();
10537
Eric Laurentdda206a2022-07-08 17:28:35 +020010538 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010539
Eric Laurentdda206a2022-07-08 17:28:35 +020010540 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010541}
10542
Andy Hungee58e4a2023-07-07 13:47:37 -070010543status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010544{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010546 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547
10548 if (mHalStream == 0) {
10549 return NO_INIT;
10550 }
10551
Eric Laurenta54f1282017-07-01 19:39:32 -070010552 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010553 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010554 return NO_ERROR;
10555 }
10556
Andy Hung8d31fd22023-06-26 19:20:57 -070010557 sp<IAfMmapTrack> track;
10558 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010559 if (handle == t->portId()) {
10560 track = t;
10561 break;
10562 }
10563 }
10564 if (track == 0) {
10565 return BAD_VALUE;
10566 }
10567
10568 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010569 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570
Andy Hungc5007f82023-08-29 14:26:09 -070010571 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010573 AudioSystem::stopOutput(track->portId());
10574 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010575 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010576 AudioSystem::stopInput(track->portId());
10577 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578 }
Andy Hungc5007f82023-08-29 14:26:09 -070010579 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010580
Andy Hung116bc262023-06-20 18:56:17 -070010581 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 if (chain != 0) {
10583 chain->decActiveTrackCnt();
10584 chain->decTrackCnt();
10585 }
10586
Eric Laurentdda206a2022-07-08 17:28:35 +020010587 if (mActiveTracks.isEmpty()) {
10588 mHalStream->stop();
10589 }
10590
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 broadcast_l();
10592
Eric Laurent6acd1d42017-01-04 14:23:29 -080010593 return NO_ERROR;
10594}
10595
Andy Hungee58e4a2023-07-07 13:47:37 -070010596status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010597NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010598{
10599 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010600 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010601
10602 if (mHalStream == 0) {
10603 return NO_INIT;
10604 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010605 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010606 return INVALID_OPERATION;
10607 }
10608 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010609 if (!mStandby) {
10610 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010611 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010612 mStandby = true;
10613 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010614 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010615 return NO_ERROR;
10616}
10617
Andy Hungee58e4a2023-07-07 13:47:37 -070010618status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010619 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10620 return INVALID_OPERATION;
10621}
10622
Andy Hungee58e4a2023-07-07 13:47:37 -070010623void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624{
10625 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10626 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10627 mFormat = mHALFormat;
10628 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10629 result = mHalStream->getFrameSize(&mFrameSize);
10630 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010631 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10632 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010633 result = mHalStream->getBufferSize(&mBufferSize);
10634 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10635 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010636
Andy Hungcf10d742020-04-28 15:38:24 -070010637 // TODO: make a readHalParameters call?
10638 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010639 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010640 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010641 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10642 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10643 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10644 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10645 /*
10646 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10647 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10648 (int32_t)mHapticChannelMask)
10649 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10650 (int32_t)mHapticChannelCount)
10651 */
10652 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010653 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010654 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10655 (int32_t)mFrameCount) // sic - added HAL
10656 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010657}
10658
Andy Hungee58e4a2023-07-07 13:47:37 -070010659bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660{
Andy Hungab65b182023-09-06 19:41:47 -070010661 {
10662 audio_utils::unique_lock _l(mutex());
10663 checkSilentMode_l();
10664 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010665
10666 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10667
10668 while (!exitPending())
10669 {
Andy Hung116bc262023-06-20 18:56:17 -070010670 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010671
Andy Hung13850be2019-03-14 11:33:09 -070010672 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010673 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010674
Eric Laurent6acd1d42017-01-04 14:23:29 -080010675 if (mSignalPending) {
10676 // A signal was raised while we were unlocked
10677 mSignalPending = false;
10678 } else {
10679 if (mConfigEvents.isEmpty()) {
10680 // we're about to wait, flush the binder command buffer
10681 IPCThreadState::self()->flushCommands();
10682
10683 if (exitPending()) {
10684 break;
10685 }
10686
Eric Laurent6acd1d42017-01-04 14:23:29 -080010687 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010688 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010689 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010690 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010691
10692 checkSilentMode_l();
10693
10694 continue;
10695 }
10696 }
10697
10698 processConfigEvents_l();
10699
10700 processVolume_l();
10701
10702 checkInvalidTracks_l();
10703
Andy Hungab65b182023-09-06 19:41:47 -070010704 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010705
Kevin Rocard069c2712018-03-29 19:09:14 -070010706 updateMetadata_l();
10707
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010709 } // release Thread lock
10710
Eric Laurent6acd1d42017-01-04 14:23:29 -080010711 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010712 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010713 }
Andy Hung13850be2019-03-14 11:33:09 -070010714
10715 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010716 unlockEffectChains(effectChains);
10717 // Effect chains will be actually deleted here if they were removed from
10718 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010719 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010720 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010721 mThreadloopExecutor.process(); // process any remaining deferred actions.
10722 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010723
10724 threadLoop_exit();
10725
10726 if (!mStandby) {
10727 threadLoop_standby();
10728 mStandby = true;
10729 }
10730
Eric Laurent6acd1d42017-01-04 14:23:29 -080010731 ALOGV("Thread %p type %d exiting", this, mType);
10732 return false;
10733}
10734
Andy Hungc5007f82023-08-29 14:26:09 -070010735// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010736bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010737 status_t& status)
10738{
10739 AudioParameter param = AudioParameter(keyValuePair);
10740 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010741 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010742 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010743 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010745 if (sendToHal) {
10746 status = mHalStream->setParameters(keyValuePair);
10747 } else {
10748 status = NO_ERROR;
10749 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750
10751 return false;
10752}
10753
Andy Hungee58e4a2023-07-07 13:47:37 -070010754String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010755{
Andy Hung972bec12023-08-31 16:13:39 -070010756 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010757 String8 out_s8;
10758 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10759 return out_s8;
10760 }
Andy Hung920f6572022-10-06 12:09:49 -070010761 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010762}
10763
Andy Hungab65b182023-09-06 19:41:47 -070010764void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010765 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010766 sp<AudioIoDescriptor> desc;
10767 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010768 switch (event) {
10769 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010770 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010771 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010772 isInput = true;
10773 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010775 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010777 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10778 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780 case AUDIO_INPUT_CLOSED:
10781 case AUDIO_OUTPUT_CLOSED:
10782 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010783 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010784 break;
10785 }
Andy Hungab65b182023-09-06 19:41:47 -070010786 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787}
10788
Andy Hungee58e4a2023-07-07 13:47:37 -070010789status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010791NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010792{
10793 status_t status = NO_ERROR;
10794
10795 // store new device and send to effects
10796 audio_devices_t type = AUDIO_DEVICE_NONE;
10797 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010798 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10799 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10800 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010801 if (isOutput()) {
10802 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010803 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10804 && !mAudioHwDev->supportsAudioPatches(),
10805 "Enumerated device type(%#x) must not be used "
10806 "as it does not support audio patches",
10807 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010808 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010809 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10810 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010811 }
10812 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010813 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010814 } else {
10815 type = patch->sources[0].ext.device.type;
10816 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010817 numDevices = mPatch.num_sources;
10818 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010819 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820 }
10821
10822 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010823 if (isOutput()) {
10824 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10825 } else {
10826 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10827 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010828 }
10829
jiabinc52b1ff2019-10-31 17:20:42 -070010830 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010831 // store new source and send to effects
10832 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10833 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10834 for (size_t i = 0; i < mEffectChains.size(); i++) {
10835 mEffectChains[i]->setAudioSource_l(mAudioSource);
10836 }
10837 }
10838 }
10839
jiabin78b86f22024-02-22 00:39:29 +000010840 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10841 // okay to notify the client earlier before the new patch creation.
10842 if (mDeviceId != deviceId) {
10843 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10844 // The aaudioservice handle the routing changed event asynchronously. In that case,
10845 // it is safe to hold the lock here.
10846 callback->onRoutingChanged(deviceId);
10847 }
10848 }
10849
Eric Laurent6acd1d42017-01-04 14:23:29 -080010850 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010851 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10852 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010853 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010854 audio_port_config port;
10855 std::optional<audio_source_t> source;
10856 if (isOutput()) {
10857 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010858 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010859 port = patch->sources[0];
10860 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010862 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010863 *handle = AUDIO_PATCH_HANDLE_NONE;
10864 }
10865
jiabinc52b1ff2019-10-31 17:20:42 -070010866 if (numDevices == 0 || mDeviceId != deviceId) {
10867 if (isOutput()) {
10868 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10869 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010870 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010871 } else {
10872 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10873 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10874 }
jiabinc52b1ff2019-10-31 17:20:42 -070010875 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010876 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010877 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010878 // Force meteadata update after a route change
10879 mActiveTracks.setHasChanged();
10880
Eric Laurent6acd1d42017-01-04 14:23:29 -080010881 return status;
10882}
10883
Andy Hungee58e4a2023-07-07 13:47:37 -070010884status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010885{
10886 status_t status = NO_ERROR;
10887
jiabinc52b1ff2019-10-31 17:20:42 -070010888 mPatch = audio_patch{};
10889 mOutDeviceTypeAddrs.clear();
10890 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010891
10892 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10893 supportsAudioPatches : false;
10894
10895 if (supportsAudioPatches) {
10896 status = mHalDevice->releaseAudioPatch(handle);
10897 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010898 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010899 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010900 // Force meteadata update after a route change
10901 mActiveTracks.setHasChanged();
10902
Eric Laurent6acd1d42017-01-04 14:23:29 -080010903 return status;
10904}
10905
Andy Hungee58e4a2023-07-07 13:47:37 -070010906void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010907NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010908{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010909 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010910 if (isOutput()) {
10911 config->role = AUDIO_PORT_ROLE_SOURCE;
10912 config->ext.mix.hw_module = mAudioHwDev->handle();
10913 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10914 } else {
10915 config->role = AUDIO_PORT_ROLE_SINK;
10916 config->ext.mix.hw_module = mAudioHwDev->handle();
10917 config->ext.mix.usecase.source = mAudioSource;
10918 }
10919}
10920
Andy Hungee58e4a2023-07-07 13:47:37 -070010921status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010922{
10923 audio_session_t session = chain->sessionId();
10924
10925 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10926 // Attach all tracks with same session ID to this chain.
10927 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010928 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010929 if (session == track->sessionId()) {
10930 chain->incTrackCnt();
10931 chain->incActiveTrackCnt();
10932 }
10933 }
10934
10935 chain->setThread(this);
10936 chain->setInBuffer(nullptr);
10937 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010938 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010939
10940 mEffectChains.add(chain);
10941 checkSuspendOnAddEffectChain_l(chain);
10942 return NO_ERROR;
10943}
10944
Andy Hungee58e4a2023-07-07 13:47:37 -070010945size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010946{
10947 audio_session_t session = chain->sessionId();
10948
10949 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10950
10951 for (size_t i = 0; i < mEffectChains.size(); i++) {
10952 if (chain == mEffectChains[i]) {
10953 mEffectChains.removeAt(i);
10954 // detach all active tracks from the chain
10955 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010956 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010957 if (session == track->sessionId()) {
10958 chain->decActiveTrackCnt();
10959 chain->decTrackCnt();
10960 }
10961 }
10962 break;
10963 }
10964 }
10965 return mEffectChains.size();
10966}
10967
Andy Hungee58e4a2023-07-07 13:47:37 -070010968void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969{
10970 mHalStream->standby();
10971}
10972
Andy Hungee58e4a2023-07-07 13:47:37 -070010973void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010974{
Phil Burk7dce7282017-09-27 13:51:41 -070010975 // Do not call callback->onTearDown() because it is redundant for thread exit
10976 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010977}
10978
Andy Hungee58e4a2023-07-07 13:47:37 -070010979status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010980{
10981 return BAD_VALUE;
10982}
10983
Andy Hungee58e4a2023-07-07 13:47:37 -070010984bool MmapThread::isValidSyncEvent(
10985 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010986{
10987 return false;
10988}
10989
Andy Hungee58e4a2023-07-07 13:47:37 -070010990status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010991 const effect_descriptor_t *desc, audio_session_t sessionId)
10992{
10993 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010994 if (audio_is_global_session(sessionId)) {
10995 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010996 desc->name, mThreadName);
10997 return BAD_VALUE;
10998 }
10999
11000 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
11001 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
11002 desc->name);
11003 return BAD_VALUE;
11004 }
11005 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080011006 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
11007 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011008 return BAD_VALUE;
11009 }
11010
11011 // Only allow effects without processing load or latency
11012 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
11013 return BAD_VALUE;
11014 }
11015
Andy Hung116bc262023-06-20 18:56:17 -070011016 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070011017 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
11018 return BAD_VALUE;
11019 }
11020
Eric Laurent6acd1d42017-01-04 14:23:29 -080011021 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011022}
11023
Andy Hungee58e4a2023-07-07 13:47:37 -070011024void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011025{
Andy Hung8d31fd22023-06-26 19:20:57 -070011026 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011027 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000011028 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
11029 // The aaudioservice handle the routing changed event asynchronously. In that case,
11030 // it is safe to hold the lock here.
11031 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
11032 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020011033 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
11034 mNoCallbackWarningCount++;
11035 }
11036 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011037 }
11038 }
11039}
11040
Andy Hungee58e4a2023-07-07 13:47:37 -070011041void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011042{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
11044 mAttr.content_type, mAttr.usage, mAttr.source);
11045 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070011046 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011047 dprintf(fd, " No active clients\n");
11048 }
11049}
11050
Andy Hungee58e4a2023-07-07 13:47:37 -070011051void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011052{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011053 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011054 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011055 dprintf(fd, " %zu Tracks\n", numtracks);
11056 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080011057 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011058 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070011059 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011060 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011061 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011062 result.append(prefix);
11063 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011064 }
11065 } else {
11066 dprintf(fd, "\n");
11067 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011068 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011069}
11070
Andy Hungee58e4a2023-07-07 13:47:37 -070011071/* static */
11072sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011073 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011074 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011075 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011076}
11077
11078MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011079 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011080 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011081 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011082 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011083 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011084{
11085 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11086 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011087 mMasterVolume = afThreadCallback->masterVolume_l();
11088 mMasterMute = afThreadCallback->masterMute_l();
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020011089 if (!audioserver_flags::portid_volume_management()) {
11090 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11091 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11092 mStreamTypes[stream].volume = 0.0f;
11093 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11094 }
11095 // Audio patch and call assistant volume are always max
11096 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11097 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11098 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11099 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011100 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011101 if (mAudioHwDev) {
11102 if (mAudioHwDev->canSetMasterVolume()) {
11103 mMasterVolume = 1.0;
11104 }
11105
11106 if (mAudioHwDev->canSetMasterMute()) {
11107 mMasterMute = false;
11108 }
11109 }
11110}
11111
Andy Hungee58e4a2023-07-07 13:47:37 -070011112void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011113 audio_stream_type_t streamType,
11114 audio_session_t sessionId,
11115 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011116 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011117 audio_port_handle_t portId)
11118{
Andy Hung8d672e02023-09-15 18:19:28 -070011119 audio_utils::lock_guard l(mutex());
11120 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011121 mStreamType = streamType;
11122}
11123
Andy Hungee58e4a2023-07-07 13:47:37 -070011124AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011125{
Andy Hung972bec12023-08-31 16:13:39 -070011126 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011127 AudioStreamOut *output = mOutput;
11128 mOutput = NULL;
11129 return output;
11130}
11131
Andy Hungee58e4a2023-07-07 13:47:37 -070011132void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011133{
Andy Hung972bec12023-08-31 16:13:39 -070011134 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011135 // Don't apply master volume in SW if our HAL can do it for us.
11136 if (mAudioHwDev &&
11137 mAudioHwDev->canSetMasterVolume()) {
11138 mMasterVolume = 1.0;
11139 } else {
11140 mMasterVolume = value;
11141 }
11142}
11143
Andy Hungee58e4a2023-07-07 13:47:37 -070011144void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011145{
Andy Hung972bec12023-08-31 16:13:39 -070011146 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011147 // Don't apply master mute in SW if our HAL can do it for us.
11148 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11149 mMasterMute = false;
11150 } else {
11151 mMasterMute = muted;
11152 }
11153}
11154
Andy Hungee58e4a2023-07-07 13:47:37 -070011155void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011156{
Andy Hung972bec12023-08-31 16:13:39 -070011157 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011158 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011159 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011160 broadcast_l();
11161 }
11162}
11163
Andy Hungee58e4a2023-07-07 13:47:37 -070011164float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011165{
Andy Hung972bec12023-08-31 16:13:39 -070011166 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011167 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011168}
11169
Andy Hungee58e4a2023-07-07 13:47:37 -070011170void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011171{
Andy Hung972bec12023-08-31 16:13:39 -070011172 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011173 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011174 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011175 broadcast_l();
11176 }
11177}
11178
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020011179sp<VolumePortInterface> MmapPlaybackThread::getVolumePortInterface(audio_port_handle_t port) const
11180{
11181 audio_utils::lock_guard _l(mutex());
11182 if (port == AUDIO_PORT_HANDLE_NONE) {
11183 return nullptr;
11184 }
11185 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
11186 if (port == track->portId()) {
11187 return track;
11188 }
11189 }
11190 return nullptr;
11191}
11192
Andy Hungee58e4a2023-07-07 13:47:37 -070011193void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011194{
Andy Hung972bec12023-08-31 16:13:39 -070011195 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011196 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011197 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011198 track->invalidate();
11199 }
11200 broadcast_l();
11201 }
11202}
11203
Andy Hungee58e4a2023-07-07 13:47:37 -070011204void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011205{
Andy Hung972bec12023-08-31 16:13:39 -070011206 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011207 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011208 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011209 if (portIds.find(track->portId()) != portIds.end()) {
11210 track->invalidate();
11211 trackMatch = true;
11212 portIds.erase(track->portId());
11213 }
11214 if (portIds.empty()) {
11215 break;
11216 }
11217 }
11218 if (trackMatch) {
11219 broadcast_l();
11220 }
11221}
11222
Andy Hungee58e4a2023-07-07 13:47:37 -070011223void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011224NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011225{
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020011226 float volume = 0;
11227 if (!audioserver_flags::portid_volume_management()) {
11228 if (mMasterMute || streamMuted_l()) {
11229 volume = 0;
11230 } else {
11231 volume = mMasterVolume * streamVolume_l();
11232 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011233 } else {
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020011234 if (mMasterMute) {
11235 volume = 0;
11236 } else {
11237 // All mmap tracks are declared with the same audio attributes to the audio policy
11238 // manager. Hence, they follow the same routing / volume group. Any change of volume
11239 // will be broadcasted to all tracks. Thus, take arbitrarily first track volume.
11240 size_t numtracks = mActiveTracks.size();
11241 if (numtracks) {
11242 volume = mMasterVolume * mActiveTracks[0]->getPortVolume();
11243 }
11244 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011245 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011246 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011247 // Convert volumes from float to 8.24
11248 uint32_t vol = (uint32_t)(volume * (1 << 24));
11249
11250 // Delegate volume control to effect in track effect chain if needed
11251 // only one effect chain can be present on DirectOutputThread, so if
11252 // there is one, the track is connected to it
11253 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011254 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011255 volume = (float)vol / (1 << 24);
11256 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011257 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011258 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11259 mHalVolFloat = volume; // HW volume control worked, so update value.
11260 mNoCallbackWarningCount = 0;
11261 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011262 sp<MmapStreamCallback> callback = mCallback.promote();
11263 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011264 mHalVolFloat = volume; // SW volume control worked, so update value.
11265 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011266 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011267 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011268 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011269 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011270 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11271 ALOGW("Could not set MMAP stream volume: no volume callback!");
11272 mNoCallbackWarningCount++;
11273 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011274 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011275 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011276 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011277 track->setMetadataHasChanged();
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020011278 if (!audioserver_flags::portid_volume_management()) {
11279 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11280 /*muteState=*/{mMasterMute,
11281 streamVolume_l() == 0.f,
11282 streamMuted_l(),
11283 // TODO(b/241533526): adjust logic to include mute from AppOps
11284 false /*muteFromPlaybackRestricted*/,
11285 false /*muteFromClientVolume*/,
11286 false /*muteFromVolumeShaper*/});
11287 } else {
11288 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11289 /*muteState=*/{mMasterMute,
11290 track->getPortVolume() == 0.f,
11291 /* muteFromStreamMuted= */ false,
11292 // TODO(b/241533526): adjust logic to include mute from AppOps
11293 false /*muteFromPlaybackRestricted*/,
11294 false /*muteFromClientVolume*/,
11295 false /*muteFromVolumeShaper*/});
11296 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011297 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011298 }
11299}
11300
Andy Hungee58e4a2023-07-07 13:47:37 -070011301ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011302{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011303 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011304 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011305 }
11306 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011307 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011308 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011309 playback_track_metadata_v7_t trackMetadata;
11310 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011311 .usage = track->attributes().usage,
11312 .content_type = track->attributes().content_type,
11313 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011314 };
11315 trackMetadata.channel_mask = track->channelMask(),
11316 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11317 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011318 }
11319 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011320
11321 MetadataUpdate change;
11322 change.playbackMetadataUpdate = metadata.tracks;
11323 return change;
11324};
Kevin Rocard069c2712018-03-29 19:09:14 -070011325
Andy Hungee58e4a2023-07-07 13:47:37 -070011326void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011327{
11328 if (!mMasterMute) {
11329 char value[PROPERTY_VALUE_MAX];
11330 if (property_get("ro.audio.silent", value, "0") > 0) {
11331 char *endptr;
11332 unsigned long ul = strtoul(value, &endptr, 0);
11333 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011334 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011335 // The setprop command will not allow a property to be changed after
11336 // the first time it is set, so we don't have to worry about un-muting.
11337 setMasterMute_l(true);
11338 }
11339 }
11340 }
11341}
11342
Andy Hungee58e4a2023-07-07 13:47:37 -070011343void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011344{
11345 MmapThread::toAudioPortConfig(config);
11346 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11347 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11348 config->flags.output = mOutput->flags;
11349 }
11350}
11351
Andy Hungee58e4a2023-07-07 13:47:37 -070011352status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011353 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011354{
11355 if (mOutput == nullptr) {
11356 return NO_INIT;
11357 }
11358 struct timespec timestamp;
11359 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11360 if (status == NO_ERROR) {
11361 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11362 }
11363 return status;
11364}
11365
Andy Hungee58e4a2023-07-07 13:47:37 -070011366status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011367 // Send to MelProcessor for sound dose measurement.
11368 auto processor = mMelProcessor.load();
11369 if (processor) {
11370 processor->process(buffer, frameCount * mFrameSize);
11371 }
11372
jiabinfc791ee2023-02-15 19:43:40 +000011373 return NO_ERROR;
11374}
11375
Andy Hungc5007f82023-08-29 14:26:09 -070011376// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011377void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011378 const sp<audio_utils::MelProcessor>& processor)
11379{
11380 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011381 mMelProcessor.store(processor);
11382 if (processor) {
11383 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011384 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011385
11386 // no need to update output format for MMapPlaybackThread since it is
11387 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011388}
11389
Andy Hungc5007f82023-08-29 14:26:09 -070011390// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011391void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011392{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011393 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11394 auto melProcessor = mMelProcessor.load();
11395 if (melProcessor != nullptr) {
11396 melProcessor->pause();
11397 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011398}
11399
Andy Hungee58e4a2023-07-07 13:47:37 -070011400void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011401{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011402 MmapThread::dumpInternals_l(fd, args);
Francois Gaffie55b2a0f2021-06-24 15:58:37 +020011403 if (!audioserver_flags::portid_volume_management()) {
11404 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d",
11405 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
11406 } else {
11407 dprintf(fd, " HAL volume: %f", mHalVolFloat);
11408 }
11409 dprintf(fd, "\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011410 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11411}
11412
Andy Hungee58e4a2023-07-07 13:47:37 -070011413/* static */
11414sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011415 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011416 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011417 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011418}
11419
11420MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011421 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011422 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011423 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011424 mInput(input)
11425{
11426 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11427 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11428}
11429
Andy Hungee58e4a2023-07-07 13:47:37 -070011430status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011431{
Phil Burkf054fc32018-12-06 09:45:59 -080011432 {
11433 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011434 if (mInput != nullptr && mInput->stream != nullptr) {
11435 mInput->stream->setGain(1.0f);
11436 }
11437 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011438 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011439}
11440
Andy Hungee58e4a2023-07-07 13:47:37 -070011441AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011442{
Andy Hung972bec12023-08-31 16:13:39 -070011443 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011444 AudioStreamIn *input = mInput;
11445 mInput = NULL;
11446 return input;
11447}
Kevin Rocard069c2712018-03-29 19:09:14 -070011448
Andy Hungee58e4a2023-07-07 13:47:37 -070011449void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011450{
11451 bool changed = false;
11452 bool silenced = false;
11453
11454 sp<MmapStreamCallback> callback = mCallback.promote();
11455 if (callback == 0) {
11456 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11457 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11458 mNoCallbackWarningCount++;
11459 }
11460 }
11461
11462 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11463 // track is silenced and unmute otherwise
11464 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11465 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11466 changed = true;
11467 silenced = mActiveTracks[i]->isSilenced_l();
11468 }
11469 }
11470
11471 if (changed) {
11472 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11473 }
11474}
11475
Andy Hungee58e4a2023-07-07 13:47:37 -070011476ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011477{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011478 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011479 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011480 }
11481 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011482 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011483 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011484 record_track_metadata_v7_t trackMetadata;
11485 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011486 .source = track->attributes().source,
11487 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011488 };
11489 trackMetadata.channel_mask = track->channelMask(),
11490 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11491 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011492 }
11493 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011494 MetadataUpdate change;
11495 change.recordMetadataUpdate = metadata.tracks;
11496 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011497}
11498
Andy Hungee58e4a2023-07-07 13:47:37 -070011499void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011500{
Andy Hung972bec12023-08-31 16:13:39 -070011501 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011502 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011503 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011504 mActiveTracks[i]->setSilenced_l(silenced);
11505 broadcast_l();
11506 }
11507 }
jiabin09609032022-06-15 19:26:01 +000011508 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011509}
11510
Andy Hungee58e4a2023-07-07 13:47:37 -070011511void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011512{
11513 MmapThread::toAudioPortConfig(config);
11514 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11515 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11516 config->flags.input = mInput->flags;
11517 }
11518}
11519
Andy Hungee58e4a2023-07-07 13:47:37 -070011520status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011521 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011522{
11523 if (mInput == nullptr) {
11524 return NO_INIT;
11525 }
11526 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11527}
11528
jiabinc658e452022-10-21 20:52:21 +000011529// ----------------------------------------------------------------------------
11530
Andy Hungee58e4a2023-07-07 13:47:37 -070011531/* static */
11532sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011533 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011534 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011535 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011536}
11537
Andy Hung583043b2023-07-17 17:05:00 -070011538BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011539 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011540 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011541
Andy Hungee58e4a2023-07-07 13:47:37 -070011542PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011543 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011544 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11545 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011546 float volumeLeft = 1.0f;
11547 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011548 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11549 bitPerfectTrack != nullptr) {
11550 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011551 mAudioMixer->setParameter(
11552 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11553 mAudioMixer->setParameter(
11554 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11555 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011556 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011557 mIsBitPerfect = true;
11558 } else {
11559 mIsBitPerfect = false;
11560 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11561 // active.
11562 for (const auto& track : mActiveTracks) {
11563 const int trackId = track->id();
11564 mAudioMixer->setParameter(
11565 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11566 }
11567 }
jiabin76d94692022-12-15 21:51:21 +000011568 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11569 mVolumeLeft = volumeLeft;
11570 mVolumeRight = volumeRight;
11571 setVolumeForOutput_l(volumeLeft, volumeRight);
11572 }
jiabinc658e452022-10-21 20:52:21 +000011573 return result;
11574}
11575
Andy Hungee58e4a2023-07-07 13:47:37 -070011576void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011577 MixerThread::threadLoop_mix();
11578 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11579}
11580
jiabin220eea12024-05-17 17:55:20 +000011581void BitPerfectThread::setTracksInternalMute(
11582 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11583 for (auto& track : mTracks) {
11584 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11585 track->setInternalMute(it->second);
11586 tracksInternalMute->erase(it);
11587 }
11588 }
11589}
11590
11591sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11592 if (com::android::media::audioserver::
11593 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11594 sp<IAfTrack> bitPerfectTrack = nullptr;
11595 bool allOtherTracksMuted = true;
11596 // Return the bit perfect track if all other tracks are muted
11597 for (const auto& track : mActiveTracks) {
11598 if (track->isBitPerfect()) {
11599 bitPerfectTrack = track;
11600 } else if (track->getFinalVolume() != 0.f) {
11601 allOtherTracksMuted = false;
11602 if (bitPerfectTrack != nullptr) {
11603 break;
11604 }
11605 }
11606 }
11607 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11608 } else {
11609 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11610 return mActiveTracks[0];
11611 }
11612 }
11613 return nullptr;
11614}
11615
Glenn Kasten63238ef2015-03-02 15:50:29 -080011616} // namespace android