blob: 2229655e269839ab6b1384a411b85ab336e9bbc5 [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
Atneya Nairf94040f2024-10-07 16:00:49 -070030#include <afutils/FallibleLockGuard.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070031#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>
Andy Hungf767de02024-10-30 19:47:50 -070036#include <audio_utils/Trace.h>
jiabin220eea12024-05-17 17:55:20 +000037#include <com_android_media_audioserver.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070038#ifdef DEBUG_CPU_USAGE
39#include <audio_utils/Statistics.h>
40#include <cpustats/ThreadCpuUsage.h>
41#endif
42#include <audio_utils/channels.h>
43#include <audio_utils/format.h>
44#include <audio_utils/minifloat.h>
45#include <audio_utils/mono_blend.h>
46#include <audio_utils/primitives.h>
47#include <audio_utils/safe_math.h>
48#include <audiomanager/AudioManager.h>
49#include <binder/IPCThreadState.h>
50#include <binder/IServiceManager.h>
51#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010052#include <com_android_media_audio.h>
Andy Hung6b137d12024-08-27 22:35:17 +000053#include <com_android_media_audioserver.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070054#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080055#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070056#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070057#include <media/AudioContainers.h>
58#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070059#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070060#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070061#ifdef ADD_BATTERY_DATA
62#include <media/IMediaPlayerService.h>
63#include <media/IMediaDeathNotifier.h>
64#endif
65#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080066#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070067#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070068#include <media/audiohal/EffectsFactoryHalInterface.h>
69#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070070#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071#include <media/nbaio/AudioStreamOutSink.h>
72#include <media/nbaio/MonoPipe.h>
73#include <media/nbaio/MonoPipeReader.h>
74#include <media/nbaio/Pipe.h>
75#include <media/nbaio/PipeReader.h>
76#include <media/nbaio/SourceAudioBufferProvider.h>
Atneya Nair5997a652024-06-14 17:24:45 -070077#include <media/ValidatedAttributionSourceState.h>
Wei Jia3f273d12015-11-24 09:06:49 -080078#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070079#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070080#include <mediautils/SchedulingPolicyService.h>
81#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070082#include <powermanager/PowerManager.h>
83#include <private/android_filesystem_config.h>
84#include <private/media/AudioTrackShared.h>
Andy Hung88a7afe2024-08-12 20:00:46 -070085#include <psh_utils/AudioPowerManager.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070086#include <system/audio_effects/effect_aec.h>
87#include <system/audio_effects/effect_downmix.h>
88#include <system/audio_effects/effect_ns.h>
89#include <system/audio_effects/effect_spatializer.h>
90#include <utils/Log.h>
91#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080092
Andy Hung25a80ac2023-07-19 12:47:35 -070093#include <fcntl.h>
94#include <linux/futex.h>
95#include <math.h>
96#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080097#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070098#include <sstream>
99#include <string>
100#include <sys/stat.h>
101#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800102
Eric Laurent81784c32012-11-19 14:55:58 -0800103// ----------------------------------------------------------------------------
104
105// Note: the following macro is used for extremely verbose logging message. In
106// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
107// 0; but one side effect of this is to turn all LOGV's as well. Some messages
108// are so verbose that we want to suppress them even when we have ALOG_ASSERT
109// turned on. Do not uncomment the #def below unless you really know what you
110// are doing and want to see all of the extremely verbose messages.
111//#define VERY_VERY_VERBOSE_LOGGING
112#ifdef VERY_VERY_VERBOSE_LOGGING
113#define ALOGVV ALOGV
114#else
115#define ALOGVV(a...) do { } while(0)
116#endif
117
Andy Hung6770c6f2015-04-07 13:43:36 -0700118// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700119#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700120
Andy Hung6770c6f2015-04-07 13:43:36 -0700121template <typename T>
122static inline T min(const T& a, const T& b)
123{
124 return a < b ? a : b;
125}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700126
Atneya Nair5997a652024-06-14 17:24:45 -0700127using com::android::media::permission::ValidatedAttributionSourceState;
Andy Hung6b137d12024-08-27 22:35:17 +0000128namespace audioserver_flags = com::android::media::audioserver;
Atneya Nair5997a652024-06-14 17:24:45 -0700129
Eric Laurent81784c32012-11-19 14:55:58 -0800130namespace android {
131
Andy Hungee58e4a2023-07-07 13:47:37 -0700132using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700133using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000134using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700135
Andy Hung25a80ac2023-07-19 12:47:35 -0700136// Keep in sync with java definition in media/java/android/media/AudioRecord.java
137static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
138
Eric Laurent81784c32012-11-19 14:55:58 -0800139// retry counts for buffer fill timeout
140// 50 * ~20msecs = 1 second
141static const int8_t kMaxTrackRetries = 50;
142static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700143
Eric Laurent81784c32012-11-19 14:55:58 -0800144// allow less retry attempts on direct output thread.
145// direct outputs can be a scarce resource in audio hardware and should
146// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700147// Notes:
148// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
149// in case the data write is bursty for the AudioTrack. The application
150// should endeavor to write at least once every kMaxTrackRetriesDirectMs
151// to prevent an underrun situation. If the data is bursty, then
152// the application can also throttle the data sent to be even.
153// 2) For compressed audio data, any data present in the AudioTrack buffer
154// will be sent and reset the retry count. This delivers data as
155// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
156// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
157// of data to be available, then any remaining data is delivered.
158// This is required to ensure the last bit of data is delivered before underrun.
159//
160// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
161// or the size of the HAL period for proportional / linear PCM tracks.
162static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// don't warn about blocked writes or record buffer overflows more often than this
165static const nsecs_t kWarningThrottleNs = seconds(5);
166
167// RecordThread loop sleep time upon application overrun or audio HAL read error
168static const int kRecordThreadSleepUs = 5000;
169
Eric Laurent10351942014-05-08 18:49:52 -0700170// maximum time to wait in sendConfigEvent_l() for a status to be received
171static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent3fddffe2024-07-31 14:18:34 +0000172// longer timeout for create audio patch to account for specific scenarii
173// with Bluetooth devices
174static const nsecs_t kCreatePatchEventTimeoutNs = seconds(4);
Eric Laurent81784c32012-11-19 14:55:58 -0800175
176// minimum sleep time for the mixer thread loop when tracks are active but in underrun
177static const uint32_t kMinThreadSleepTimeUs = 5000;
178// maximum divider applied to the active sleep time in the mixer thread loop
179static const uint32_t kMaxThreadSleepTimeShift = 2;
180
Andy Hung09a50072014-02-27 14:30:47 -0800181// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700182// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800183static const uint32_t kMinNormalSinkBufferSizeMs = 20;
184// maximum normal sink buffer size
185static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800186
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700187// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
188// FIXME This should be based on experimentally observed scheduling jitter
189static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
190
Eric Laurent972a1732013-09-04 09:42:59 -0700191// Offloaded output thread standby delay: allows track transition without going to standby
192static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
193
Eric Laurent51716182016-02-29 18:00:56 -0800194// Direct output thread minimum sleep time in idle or active(underrun) state
195static const nsecs_t kDirectMinSleepTimeUs = 10000;
196
Brian Lindahl65e90012022-07-27 18:01:07 +0200197// Minimum amount of time between checking to see if the timestamp is advancing
198// for underrun detection. If we check too frequently, we may not detect a
199// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800200static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200201
Glenn Kasten1b291842016-07-18 14:55:21 -0700202// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
203// balance between power consumption and latency, and allows threads to be scheduled reliably
204// by the CFS scheduler.
205// FIXME Express other hardcoded references to 20ms with references to this constant and move
206// it appropriately.
207#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800208
Eric Laurent81784c32012-11-19 14:55:58 -0800209// Whether to use fast mixer
210static const enum {
211 FastMixer_Never, // never initialize or use: for debugging only
212 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
213 // normal mixer multiplier is 1
214 FastMixer_Static, // initialize if needed, then use all the time if initialized,
215 // multiplier is calculated based on min & max normal mixer buffer size
216 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
217 // multiplier is calculated based on min & max normal mixer buffer size
218 // FIXME for FastMixer_Dynamic:
219 // Supporting this option will require fixing HALs that can't handle large writes.
220 // For example, one HAL implementation returns an error from a large write,
221 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
222 // We could either fix the HAL implementations, or provide a wrapper that breaks
223 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
224} kUseFastMixer = FastMixer_Static;
225
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700226// Whether to use fast capture
227static const enum {
228 FastCapture_Never, // never initialize or use: for debugging only
229 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
230 FastCapture_Static, // initialize if needed, then use all the time if initialized
231} kUseFastCapture = FastCapture_Static;
232
Eric Laurent81784c32012-11-19 14:55:58 -0800233// Priorities for requestPriority
234static const int kPriorityAudioApp = 2;
235static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700236static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000237// Request real-time priority for PlaybackThread in ARC
238static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800239
Glenn Kastenea38ee72016-04-18 11:08:01 -0700240// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
241// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
242// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700243
244// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800245static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800246
Glenn Kasten03490092014-05-27 12:30:54 -0700247// The minimum and maximum allowed values
248static const int kFastTrackMultiplierMin = 1;
249static const int kFastTrackMultiplierMax = 2;
250
251// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
252static int sFastTrackMultiplier = kFastTrackMultiplier;
253
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700254// See Thread::readOnlyHeap().
255// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
256// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
257// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700258static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700259
Andy Hung25a80ac2023-07-19 12:47:35 -0700260static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700261
262static nsecs_t getStandbyTimeInNanos() {
263 static nsecs_t standbyTimeInNanos = []() {
264 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
265 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
266 ALOGI("%s: Using %d ms as standby time", __func__, ms);
267 return milliseconds(ms);
268 }();
269 return standbyTimeInNanos;
270}
271
Andy Hung81994d62023-07-20 21:44:14 -0700272// Set kEnableExtendedChannels to true to enable greater than stereo output
273// for the MixerThread and device sink. Number of channels allowed is
274// FCC_2 <= channels <= FCC_LIMIT.
275constexpr bool kEnableExtendedChannels = true;
276
277// Returns true if channel mask is permitted for the PCM sink in the MixerThread
278/* static */
279bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
280 switch (audio_channel_mask_get_representation(channelMask)) {
281 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
282 // Haptic channel mask is only applicable for channel position mask.
283 const uint32_t channelCount = audio_channel_count_from_out_mask(
284 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
285 const uint32_t maxChannelCount = kEnableExtendedChannels
286 ? FCC_LIMIT : FCC_2;
287 if (channelCount < FCC_2 // mono is not supported at this time
288 || channelCount > maxChannelCount) {
289 return false;
290 }
291 // check that channelMask is the "canonical" one we expect for the channelCount.
292 return audio_channel_position_mask_is_out_canonical(channelMask);
293 }
294 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
295 if (kEnableExtendedChannels) {
296 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
297 if (channelCount >= FCC_2 // mono is not supported at this time
298 && channelCount <= FCC_LIMIT) {
299 return true;
300 }
301 }
302 return false;
303 default:
304 return false;
305 }
306}
307
308// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
309constexpr bool kEnableExtendedPrecision = true;
310
311// Returns true if format is permitted for the PCM sink in the MixerThread
312/* static */
313bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
314 switch (format) {
315 case AUDIO_FORMAT_PCM_16_BIT:
316 return true;
317 case AUDIO_FORMAT_PCM_FLOAT:
318 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
319 case AUDIO_FORMAT_PCM_32_BIT:
320 case AUDIO_FORMAT_PCM_8_24_BIT:
321 return kEnableExtendedPrecision;
322 default:
323 return false;
324 }
325}
326
Eric Laurent81784c32012-11-19 14:55:58 -0800327// ----------------------------------------------------------------------------
328
Andy Hung25a80ac2023-07-19 12:47:35 -0700329// formatToString() needs to be exact for MediaMetrics purposes.
330// Do not use media/TypeConverter.h toString().
331/* static */
332std::string IAfThreadBase::formatToString(audio_format_t format) {
333 std::string result;
334 FormatConverter::toString(format, result);
335 return result;
336}
337
Andy Hungb68f5eb2019-12-03 16:49:17 -0800338// TODO: move all toString helpers to audio.h
339// under #ifdef __cplusplus #endif
340static std::string patchSinksToString(const struct audio_patch *patch)
341{
Andy Hungc04a8202024-11-01 17:38:06 -0700342 std::string s;
Andy Hungb68f5eb2019-12-03 16:49:17 -0800343 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc04a8202024-11-01 17:38:06 -0700344 if (i > 0) s.append("|");
345 if (patch->sinks[i].ext.device.address[0]) {
346 s.append("(").append(toString(patch->sinks[i].ext.device.type))
347 .append(", ").append(patch->sinks[i].ext.device.address).append(")");
348 } else {
349 s.append(toString(patch->sinks[i].ext.device.type));
Andy Hungc2b11cb2020-04-22 09:04:01 -0700350 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800351 }
Andy Hungc04a8202024-11-01 17:38:06 -0700352 return s;
Andy Hungb68f5eb2019-12-03 16:49:17 -0800353}
354
355static std::string patchSourcesToString(const struct audio_patch *patch)
356{
Andy Hungc04a8202024-11-01 17:38:06 -0700357 std::string s;
Andy Hungb68f5eb2019-12-03 16:49:17 -0800358 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc04a8202024-11-01 17:38:06 -0700359 if (i > 0) s.append("|");
360 if (patch->sources[i].ext.device.address[0]) {
361 s.append("(").append(toString(patch->sources[i].ext.device.type))
362 .append(", ").append(patch->sources[i].ext.device.address).append(")");
363 } else {
364 s.append(toString(patch->sources[i].ext.device.type));
Andy Hungc2b11cb2020-04-22 09:04:01 -0700365 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800366 }
Andy Hungc04a8202024-11-01 17:38:06 -0700367 return s;
Andy Hungb68f5eb2019-12-03 16:49:17 -0800368}
369
Andy Hung4bd53e72022-11-17 17:21:45 -0800370static std::string toString(audio_latency_mode_t mode) {
371 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000372 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
373 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800374}
375
376// Could be made a template, but other toString overloads for std::vector are confused.
377static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
378 std::string s("{ ");
379 for (const auto& e : elements) {
380 s.append(toString(e));
381 s.append(" ");
382 }
383 s.append("}");
384 return s;
385}
386
Glenn Kasten03490092014-05-27 12:30:54 -0700387static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
388
389static void sFastTrackMultiplierInit()
390{
391 char value[PROPERTY_VALUE_MAX];
392 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
393 char *endptr;
394 unsigned long ul = strtoul(value, &endptr, 0);
395 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
396 sFastTrackMultiplier = (int) ul;
397 }
398 }
399}
400
401// ----------------------------------------------------------------------------
402
Eric Laurent81784c32012-11-19 14:55:58 -0800403#ifdef ADD_BATTERY_DATA
404// To collect the amplifier usage
405static void addBatteryData(uint32_t params) {
406 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
407 if (service == NULL) {
408 // it already logged
409 return;
410 }
411
412 service->addBatteryData(params);
413}
414#endif
415
Andy Hung3f0c9022016-01-15 17:49:46 -0800416// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
417struct {
418 // call when you acquire a partial wakelock
419 void acquire(const sp<IBinder> &wakeLockToken) {
420 pthread_mutex_lock(&mLock);
421 if (wakeLockToken.get() == nullptr) {
422 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
423 } else {
424 if (mCount == 0) {
425 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
426 }
427 ++mCount;
428 }
429 pthread_mutex_unlock(&mLock);
430 }
431
432 // call when you release a partial wakelock.
433 void release(const sp<IBinder> &wakeLockToken) {
434 if (wakeLockToken.get() == nullptr) {
435 return;
436 }
437 pthread_mutex_lock(&mLock);
438 if (--mCount < 0) {
439 ALOGE("negative wakelock count");
440 mCount = 0;
441 }
442 pthread_mutex_unlock(&mLock);
443 }
444
445 // retrieves the boottime timebase offset from monotonic.
446 int64_t getBoottimeOffset() {
447 pthread_mutex_lock(&mLock);
448 int64_t boottimeOffset = mBoottimeOffset;
449 pthread_mutex_unlock(&mLock);
450 return boottimeOffset;
451 }
452
453 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
454 // and the selected timebase.
455 // Currently only TIMEBASE_BOOTTIME is allowed.
456 //
457 // This only needs to be called upon acquiring the first partial wakelock
458 // after all other partial wakelocks are released.
459 //
460 // We do an empirical measurement of the offset rather than parsing
461 // /proc/timer_list since the latter is not a formal kernel ABI.
462 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
463 int clockbase;
464 switch (timebase) {
465 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
466 clockbase = SYSTEM_TIME_BOOTTIME;
467 break;
468 default:
469 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
470 break;
471 }
472 // try three times to get the clock offset, choose the one
473 // with the minimum gap in measurements.
474 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700475 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800476 for (int i = 0; i < tries; ++i) {
477 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
478 const nsecs_t tbase = systemTime(clockbase);
479 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
480 const nsecs_t gap = tmono2 - tmono;
481 if (i == 0 || gap < bestGap) {
482 bestGap = gap;
483 measured = tbase - ((tmono + tmono2) >> 1);
484 }
485 }
486
487 // to avoid micro-adjusting, we don't change the timebase
488 // unless it is significantly different.
489 //
490 // Assumption: It probably takes more than toleranceNs to
491 // suspend and resume the device.
492 static int64_t toleranceNs = 10000; // 10 us
493 if (llabs(*offset - measured) > toleranceNs) {
494 ALOGV("Adjusting timebase offset old: %lld new: %lld",
495 (long long)*offset, (long long)measured);
496 *offset = measured;
497 }
498 }
499
500 pthread_mutex_t mLock;
501 int32_t mCount;
502 int64_t mBoottimeOffset;
503} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800504
505// ----------------------------------------------------------------------------
506// CPU Stats
507// ----------------------------------------------------------------------------
508
509class CpuStats {
510public:
511 CpuStats();
512 void sample(const String8 &title);
513#ifdef DEBUG_CPU_USAGE
514private:
515 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700516 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800517
Andy Hung16698b82018-08-01 10:48:38 -0700518 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800519
520 int mCpuNum; // thread's current CPU number
521 int mCpukHz; // frequency of thread's current CPU in kHz
522#endif
523};
524
525CpuStats::CpuStats()
526#ifdef DEBUG_CPU_USAGE
527 : mCpuNum(-1), mCpukHz(-1)
528#endif
529{
530}
531
Glenn Kasten0f11b512014-01-31 16:18:54 -0800532void CpuStats::sample(const String8 &title
533#ifndef DEBUG_CPU_USAGE
534 __unused
535#endif
536 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800537#ifdef DEBUG_CPU_USAGE
538 // get current thread's delta CPU time in wall clock ns
539 double wcNs;
540 bool valid = mCpuUsage.sampleAndEnable(wcNs);
541
542 // record sample for wall clock statistics
543 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700544 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800545 }
546
547 // get the current CPU number
548 int cpuNum = sched_getcpu();
549
550 // get the current CPU frequency in kHz
551 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
552
553 // check if either CPU number or frequency changed
554 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
555 mCpuNum = cpuNum;
556 mCpukHz = cpukHz;
557 // ignore sample for purposes of cycles
558 valid = false;
559 }
560
561 // if no change in CPU number or frequency, then record sample for cycle statistics
562 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700563 const double cycles = wcNs * cpukHz * 0.000001;
564 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800565 }
566
Eric Tan5b13ff82018-07-27 11:20:17 -0700567 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800568 // mCpuUsage.elapsed() is expensive, so don't call it every loop
569 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700570 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800571 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700572 const double perLoop = elapsed / (double) n;
573 const double perLoop100 = perLoop * 0.01;
574 const double perLoop1k = perLoop * 0.001;
575 const double mean = mWcStats.getMean();
576 const double stddev = mWcStats.getStdDev();
577 const double minimum = mWcStats.getMin();
578 const double maximum = mWcStats.getMax();
579 const double meanCycles = mHzStats.getMean();
580 const double stddevCycles = mHzStats.getStdDev();
581 const double minCycles = mHzStats.getMin();
582 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800583 mCpuUsage.resetElapsed();
584 mWcStats.reset();
585 mHzStats.reset();
586 ALOGD("CPU usage for %s over past %.1f secs\n"
587 " (%u mixer loops at %.1f mean ms per loop):\n"
588 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
589 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
590 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000591 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800592 elapsed * .000000001, n, perLoop * .000001,
593 mean * .001,
594 stddev * .001,
595 minimum * .001,
596 maximum * .001,
597 mean / perLoop100,
598 stddev / perLoop100,
599 minimum / perLoop100,
600 maximum / perLoop100,
601 meanCycles / perLoop1k,
602 stddevCycles / perLoop1k,
603 minCycles / perLoop1k,
604 maxCycles / perLoop1k);
605
606 }
607 }
608#endif
609};
610
611// ----------------------------------------------------------------------------
612// ThreadBase
613// ----------------------------------------------------------------------------
614
Glenn Kasten97b7b752014-09-28 13:04:24 -0700615// static
Andy Hungf767de02024-10-30 19:47:50 -0700616const char* IAfThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700617{
618 switch (type) {
619 case MIXER:
620 return "MIXER";
621 case DIRECT:
622 return "DIRECT";
623 case DUPLICATING:
624 return "DUPLICATING";
625 case RECORD:
626 return "RECORD";
627 case OFFLOAD:
628 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700629 case MMAP_PLAYBACK:
630 return "MMAP_PLAYBACK";
631 case MMAP_CAPTURE:
632 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200633 case SPATIALIZER:
634 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000635 case BIT_PERFECT:
636 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700637 default:
638 return "unknown";
639 }
640}
641
Andy Hung583043b2023-07-17 17:05:00 -0700642ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700643 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800644 : Thread(false /*canCallJava*/),
645 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700646 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700647 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
648 isOut),
649 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700650 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800651 // are set by PlaybackThread::readOutputParameters_l() or
652 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700653 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700654 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700655 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800656 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700657 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800658 mSystemReady(systemReady),
659 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800660{
Andy Hungcf10d742020-04-28 15:38:24 -0700661 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700662 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800663}
664
Andy Hungee58e4a2023-07-07 13:47:37 -0700665ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800666{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700667 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700668 mConfigEvents.clear();
669
Eric Laurent81784c32012-11-19 14:55:58 -0800670 // do not lock the mutex in destructor
671 releaseWakeLock_l();
672 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800673 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800674 binder->unlinkToDeath(mDeathRecipient);
675 }
Andy Hungd0979812019-02-21 15:51:44 -0800676
677 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800678}
679
Andy Hungee58e4a2023-07-07 13:47:37 -0700680status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700681{
682 status_t status = initCheck();
683 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800684 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700685 } else {
686 ALOGE("No working audio driver found.");
687 }
688 return status;
689}
690
Andy Hungee58e4a2023-07-07 13:47:37 -0700691void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800692{
693 ALOGV("ThreadBase::exit");
694 // do any cleanup required for exit to succeed
695 preExit();
696 {
697 // This lock prevents the following race in thread (uniprocessor for illustration):
698 // if (!exitPending()) {
699 // // context switch from here to exit()
700 // // exit() calls requestExit(), what exitPending() observes
701 // // exit() calls signal(), which is dropped since no waiters
702 // // context switch back from exit() to here
703 // mWaitWorkCV.wait(...);
704 // // now thread is hung
705 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700706 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800707 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700708 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800709 }
710 // When Thread::requestExitAndWait is made virtual and this method is renamed to
711 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700712
713 // For TimeCheck: track waiting on the thread join of getTid().
714 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
715
Eric Laurent81784c32012-11-19 14:55:58 -0800716 requestExitAndWait();
717}
718
Andy Hungee58e4a2023-07-07 13:47:37 -0700719status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800720{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000721 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700722 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800723
Eric Laurent10351942014-05-08 18:49:52 -0700724 return sendSetParameterConfigEvent_l(keyValuePairs);
725}
726
727// sendConfigEvent_l() must be called with ThreadBase::mLock held
728// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700729status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700730NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700731{
732 status_t status = NO_ERROR;
733
Eric Laurent72e3f392015-05-20 14:43:50 -0700734 if (event->mRequiresSystemReady && !mSystemReady) {
735 event->mWaitStatus = false;
736 mPendingConfigEvents.add(event);
737 return status;
738 }
Eric Laurent10351942014-05-08 18:49:52 -0700739 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700740 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700741 mWaitWorkCV.notify_one();
742 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700743 {
Andy Hungc5007f82023-08-29 14:26:09 -0700744 audio_utils::unique_lock _l(event->mutex());
Eric Laurent3fddffe2024-07-31 14:18:34 +0000745 nsecs_t timeoutNs = event->mType == CFG_EVENT_CREATE_AUDIO_PATCH ?
746 kCreatePatchEventTimeoutNs : kConfigEventTimeoutNs;
Eric Laurent10351942014-05-08 18:49:52 -0700747 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800748 if (event->mCondition.wait_for(
Eric Laurent3fddffe2024-07-31 14:18:34 +0000749 _l, std::chrono::nanoseconds(timeoutNs), getTid())
Andy Hung02ea2a02024-01-25 17:02:30 -0800750 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700751 event->mStatus = TIMED_OUT;
752 event->mWaitStatus = false;
753 }
754 }
755 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800756 }
Andy Hungc5007f82023-08-29 14:26:09 -0700757 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800758 return status;
759}
760
Andy Hungee58e4a2023-07-07 13:47:37 -0700761void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700762 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800763{
Andy Hung972bec12023-08-31 16:13:39 -0700764 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700765 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800766}
767
Andy Hungc5007f82023-08-29 14:26:09 -0700768// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700769void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700770 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800771{
Andy Hungd0979812019-02-21 15:51:44 -0800772 // The audio statistics history is exponentially weighted to forget events
773 // about five or more seconds in the past. In order to have
774 // crisper statistics for mediametrics, we reset the statistics on
775 // an IoConfigEvent, to reflect different properties for a new device.
776 mIoJitterMs.reset();
777 mLatencyMs.reset();
778 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000779 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100780 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800781
Eric Laurent09f1ed22019-04-24 17:45:17 -0700782 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700783 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800784}
785
Andy Hungee58e4a2023-07-07 13:47:37 -0700786void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700787{
Andy Hung972bec12023-08-31 16:13:39 -0700788 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800789 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700790}
791
Andy Hungc5007f82023-08-29 14:26:09 -0700792// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700793void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800794 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800795{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800796 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700797 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800798}
799
Andy Hungc5007f82023-08-29 14:26:09 -0700800// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700801status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800802{
Andy Hung2ddee192015-12-18 17:34:44 -0800803 sp<ConfigEvent> configEvent;
804 AudioParameter param(keyValuePair);
805 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700806 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800807 setMasterMono_l(value != 0);
808 if (param.size() == 1) {
809 return NO_ERROR; // should be a solo parameter - we don't pass down
810 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700811 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800812 configEvent = new SetParameterConfigEvent(param.toString());
813 } else {
814 configEvent = new SetParameterConfigEvent(keyValuePair);
815 }
Eric Laurent10351942014-05-08 18:49:52 -0700816 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700817}
818
Andy Hungee58e4a2023-07-07 13:47:37 -0700819status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700820 const struct audio_patch *patch,
821 audio_patch_handle_t *handle)
822{
Andy Hung972bec12023-08-31 16:13:39 -0700823 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700824 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
825 status_t status = sendConfigEvent_l(configEvent);
826 if (status == NO_ERROR) {
827 CreateAudioPatchConfigEventData *data =
828 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
829 *handle = data->mHandle;
830 }
831 return status;
832}
833
Andy Hungee58e4a2023-07-07 13:47:37 -0700834status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700835 const audio_patch_handle_t handle)
836{
Andy Hung972bec12023-08-31 16:13:39 -0700837 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700838 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
839 return sendConfigEvent_l(configEvent);
840}
841
Andy Hungee58e4a2023-07-07 13:47:37 -0700842status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700843 const DeviceDescriptorBaseVector& outDevices)
844{
845 if (type() != RECORD) {
846 // The update out device operation is only for record thread.
847 return INVALID_OPERATION;
848 }
Andy Hung972bec12023-08-31 16:13:39 -0700849 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700850 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
851 return sendConfigEvent_l(configEvent);
852}
853
Andy Hungee58e4a2023-07-07 13:47:37 -0700854void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200855{
856 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
857 sp<ConfigEvent> configEvent =
858 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
859 sendConfigEvent_l(configEvent);
860}
Eric Laurent1c333e22014-05-20 10:48:17 -0700861
Andy Hungee58e4a2023-07-07 13:47:37 -0700862void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200863{
Andy Hung972bec12023-08-31 16:13:39 -0700864 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200865 sendCheckOutputStageEffectsEvent_l();
866}
867
Andy Hungee58e4a2023-07-07 13:47:37 -0700868void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200869{
870 sp<ConfigEvent> configEvent =
871 (ConfigEvent *)new CheckOutputStageEffectsEvent();
872 sendConfigEvent_l(configEvent);
873}
874
Andy Hungee58e4a2023-07-07 13:47:37 -0700875void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200876{
877 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
878 sendConfigEvent_l(configEvent);
879}
880
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700881// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700882void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700883{
Eric Laurent10351942014-05-08 18:49:52 -0700884 bool configChanged = false;
885
Eric Laurent81784c32012-11-19 14:55:58 -0800886 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700887 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700888 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800889 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700890 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700891 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700892 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
893 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800894 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700895 true /*asynchronous*/);
896 if (err != 0) {
897 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700898 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700899 }
900 } break;
901 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700902 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700903 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700904 } break;
905 case CFG_EVENT_SET_PARAMETER: {
906 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
907 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
908 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700909 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000910 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700911 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700912 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700913 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700914 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700915 CreateAudioPatchConfigEventData *data =
916 (CreateAudioPatchConfigEventData *)event->mData.get();
917 event->mStatus = createAudioPatch_l(&data->mPatch, &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_CREATE_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());
Eric Laurent1c333e22014-05-20 10:48:17 -0700923 } break;
924 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700925 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700926 ReleaseAudioPatchConfigEventData *data =
927 (ReleaseAudioPatchConfigEventData *)event->mData.get();
928 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700929 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200930 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700931 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
932 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
933 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
934 } break;
935 case CFG_EVENT_UPDATE_OUT_DEVICE: {
936 UpdateOutDevicesConfigEventData *data =
937 (UpdateOutDevicesConfigEventData *)event->mData.get();
938 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700939 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200940 case CFG_EVENT_RESIZE_BUFFER: {
941 ResizeBufferConfigEventData *data =
942 (ResizeBufferConfigEventData *)event->mData.get();
943 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
944 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200945
946 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
947 setCheckOutputStageEffects();
948 } break;
949
Eric Laurent68a40a82022-05-03 18:15:04 +0200950 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
951 onHalLatencyModesChanged_l();
952 } break;
953
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700954 default:
Eric Laurent10351942014-05-08 18:49:52 -0700955 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700956 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800957 }
Eric Laurent10351942014-05-08 18:49:52 -0700958 {
Andy Hung972bec12023-08-31 16:13:39 -0700959 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700960 if (event->mWaitStatus) {
961 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700962 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700963 }
964 }
965 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
966 }
967
968 if (configChanged) {
969 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800970 }
Eric Laurent81784c32012-11-19 14:55:58 -0800971}
972
Marco Nelissenb2208842014-02-07 14:00:50 -0800973String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
974 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700975 const audio_channel_representation_t representation =
976 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700977
978 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800979 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700980 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
981 if (output) {
982 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
983 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
984 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700985 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700986 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
987 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
988 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
989 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
990 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
991 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
992 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
993 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
994 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
995 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
996 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
997 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700998 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
999 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
1000 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
1001 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
1002 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
1003 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
1004 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -07001005 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001006 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
1007 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001008 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
1009 } else {
1010 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
1011 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
1012 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
1013 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
1014 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
1015 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1016 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1017 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1018 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1019 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1020 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1021 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001022 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1023 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1024 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001025 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001026 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1027 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001028 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1029 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1030 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1031 }
1032 const int len = s.length();
1033 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001034 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001035 s.unlockBuffer(len - 2); // remove trailing ", "
1036 }
1037 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001038 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001039 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1040 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1041 return s;
1042 default:
1043 s.appendFormat("unknown mask, representation:%d bits:%#x",
1044 representation, audio_channel_mask_get_bits(mask));
1045 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001046 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001047}
1048
Andy Hungee58e4a2023-07-07 13:47:37 -07001049void ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001050{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001051 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1052 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1053
Atneya Nairf94040f2024-10-07 16:00:49 -07001054 {
1055 afutils::FallibleLockGuard l{mutex()};
1056 if (!l) {
1057 dprintf(fd, " Thread may be deadlocked\n");
1058 }
1059 dumpBase_l(fd, args);
1060 dumpInternals_l(fd, args);
1061 dumpTracks_l(fd, args);
1062 dumpEffectChains_l(fd, args);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001063 }
1064
1065 dprintf(fd, " Local log:\n");
Atneya Nairaa3afcb2024-10-08 16:36:19 -07001066 const auto logHeader = this->getLocalLogHeader();
1067 write(fd, logHeader.data(), logHeader.length());
Atneya Nair0423af92024-10-07 21:23:29 -07001068 mLocalLog.dump(fd, " " /* prefix */);
Andy Hungafc51db2022-04-08 17:33:40 -07001069
1070 // --all does the statistics
1071 bool dumpAll = false;
1072 for (const auto &arg : args) {
1073 if (arg == String16("--all")) {
1074 dumpAll = true;
1075 }
1076 }
1077 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001078 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001079 if (!sched.empty()) {
1080 (void)write(fd, sched.c_str(), sched.size());
1081 }
1082 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001083}
1084
Andy Hungee58e4a2023-07-07 13:47:37 -07001085void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001086{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001087 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001088 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001089 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001090 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001091 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1092 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001093 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001094 dprintf(fd, " Channel count: %u\n", mChannelCount);
1095 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001096 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001097 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1098 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001099 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001100 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001101 size_t numConfig = mConfigEvents.size();
1102 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001103 const size_t SIZE = 256;
1104 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001105 for (size_t i = 0; i < numConfig; i++) {
1106 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001107 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001108 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001109 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001110 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001111 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001112 }
Andy Hung293558a2017-03-21 12:19:20 -07001113 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001114 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001115 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001116 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001117 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001118 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001119
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001120 // Dump timestamp statistics for the Thread types that support it.
1121 if (mType == RECORD
1122 || mType == MIXER
1123 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001124 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001125 || mType == OFFLOAD
1126 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001127 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001128 dprintf(fd, " Timestamp corrected: %s\n",
1129 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001130 }
1131
Andy Hung446f4df2019-02-21 12:26:41 -08001132 if (mLastIoBeginNs > 0) { // MMAP may not set this
1133 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1134 isOutput() ? "write" : "read",
1135 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1136 }
1137
1138 if (mProcessTimeMs.getN() > 0) {
1139 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1140 }
1141
1142 if (mIoJitterMs.getN() > 0) {
1143 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1144 isOutput() ? "write" : "read",
1145 mIoJitterMs.toString().c_str());
1146 }
1147
Andy Hunge6c37112019-02-26 17:38:10 -08001148 if (mLatencyMs.getN() > 0) {
1149 dprintf(fd, " Threadloop %s latency stats: %s\n",
1150 isOutput() ? "write" : "read",
1151 mLatencyMs.toString().c_str());
1152 }
Robert Wu06db0a32021-08-10 19:05:34 +00001153
1154 if (mMonopipePipeDepthStats.getN() > 0) {
1155 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1156 isOutput() ? "write" : "read",
1157 mMonopipePipeDepthStats.toString().c_str());
1158 }
Eric Laurent81784c32012-11-19 14:55:58 -08001159}
1160
Andy Hungee58e4a2023-07-07 13:47:37 -07001161void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001162{
1163 const size_t SIZE = 256;
1164 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001165
Marco Nelissenb2208842014-02-07 14:00:50 -08001166 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001167 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001168 write(fd, buffer, strlen(buffer));
1169
Marco Nelissenb2208842014-02-07 14:00:50 -08001170 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001171 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001172 if (chain != 0) {
1173 chain->dump(fd, args);
1174 }
1175 }
1176}
1177
Andy Hungee58e4a2023-07-07 13:47:37 -07001178void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001179{
Andy Hung972bec12023-08-31 16:13:39 -07001180 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001181 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001182}
1183
Andy Hungee58e4a2023-07-07 13:47:37 -07001184String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001185{
1186 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001187 case MIXER:
1188 return String16("AudioMix");
1189 case DIRECT:
1190 return String16("AudioDirectOut");
1191 case DUPLICATING:
1192 return String16("AudioDup");
1193 case RECORD:
1194 return String16("AudioIn");
1195 case OFFLOAD:
1196 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001197 case MMAP_PLAYBACK:
1198 return String16("MmapPlayback");
1199 case MMAP_CAPTURE:
1200 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001201 case SPATIALIZER:
1202 return String16("AudioSpatial");
jiabin10b2fb82024-09-03 17:51:35 +00001203 case BIT_PERFECT:
1204 return String16("AudioBitPerfect");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001205 default:
1206 ALOG_ASSERT(false);
1207 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001208 }
1209}
1210
Andy Hungee58e4a2023-07-07 13:47:37 -07001211void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001212{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001213 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001214 if (mPowerManager != 0) {
1215 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001216 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001217 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1218 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001219 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001220 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001221 {} /* workSource */,
1222 {} /* historyTag */);
1223 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001224 mWakeLockToken = binder;
Andy Hung88a7afe2024-08-12 20:00:46 -07001225 if (media::psh_utils::AudioPowerManager::enabled()) {
1226 mThreadToken = media::psh_utils::createAudioThreadToken(
1227 getTid(), String8(getWakeLockTag()).c_str());
1228 }
Eric Laurent81784c32012-11-19 14:55:58 -08001229 }
Chris Ye6597d732020-02-28 22:38:25 -08001230 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001231 }
Wei Jia3f273d12015-11-24 09:06:49 -08001232
Andy Hung3f0c9022016-01-15 17:49:46 -08001233 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001234 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1235 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001236}
1237
Andy Hungee58e4a2023-07-07 13:47:37 -07001238void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001239{
Andy Hung972bec12023-08-31 16:13:39 -07001240 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001241 releaseWakeLock_l();
1242}
1243
Andy Hungee58e4a2023-07-07 13:47:37 -07001244void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001245{
Andy Hung3f0c9022016-01-15 17:49:46 -08001246 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001247 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001248 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001249 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001250 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001251 }
1252 mWakeLockToken.clear();
1253 }
Andy Hung88a7afe2024-08-12 20:00:46 -07001254 mThreadToken.reset();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001255}
1256
Andy Hungee58e4a2023-07-07 13:47:37 -07001257void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001258 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001259 // use checkService() to avoid blocking if power service is not up yet
1260 sp<IBinder> binder =
1261 defaultServiceManager()->checkService(String16("power"));
1262 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001263 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001264 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001265 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001266 binder->linkToDeath(mDeathRecipient);
1267 }
1268 }
1269}
1270
Andy Hungee58e4a2023-07-07 13:47:37 -07001271void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001272 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001273
1274#if !LOG_NDEBUG
1275 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001276 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001277 s << uid << " ";
1278 }
1279 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1280#endif
1281
Andy Hung438e7572015-12-14 15:51:17 -08001282 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1283 if (mSystemReady) {
1284 ALOGE("no wake lock to update, but system ready!");
1285 } else {
1286 ALOGW("no wake lock to update, system not ready yet");
1287 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001288 return;
1289 }
1290 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001291 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001292 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1293 mWakeLockToken, uidsAsInt);
1294 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001295 }
1296}
1297
Andy Hungee58e4a2023-07-07 13:47:37 -07001298void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001299{
Andy Hung972bec12023-08-31 16:13:39 -07001300 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001301 releaseWakeLock_l();
1302 mPowerManager.clear();
1303}
1304
Andy Hungee58e4a2023-07-07 13:47:37 -07001305void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001306 const DeviceDescriptorBaseVector& outDevices __unused)
1307{
1308 ALOGE("%s should only be called in RecordThread", __func__);
1309}
1310
Andy Hungee58e4a2023-07-07 13:47:37 -07001311void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001312{
1313 ALOGE("%s should only be called in RecordThread", __func__);
1314}
1315
Andy Hungee58e4a2023-07-07 13:47:37 -07001316void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001317{
1318 sp<ThreadBase> thread = mThread.promote();
1319 if (thread != 0) {
1320 thread->clearPowerManager();
1321 }
1322 ALOGW("power manager service died !!!");
1323}
1324
Andy Hungee58e4a2023-07-07 13:47:37 -07001325void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001326 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001327{
Andy Hung116bc262023-06-20 18:56:17 -07001328 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001329 if (chain != 0) {
1330 if (type != NULL) {
1331 chain->setEffectSuspended_l(type, suspend);
1332 } else {
1333 chain->setEffectSuspendedAll_l(suspend);
1334 }
1335 }
1336
1337 updateSuspendedSessions_l(type, suspend, sessionId);
1338}
1339
Andy Hungee58e4a2023-07-07 13:47:37 -07001340void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001341{
1342 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1343 if (index < 0) {
1344 return;
1345 }
1346
1347 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1348 mSuspendedSessions.valueAt(index);
1349
1350 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001351 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001352 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001353 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001354 chain->setEffectSuspendedAll_l(true);
1355 } else {
1356 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1357 desc->mType.timeLow);
1358 chain->setEffectSuspended_l(&desc->mType, true);
1359 }
1360 }
1361 }
1362}
1363
Andy Hungee58e4a2023-07-07 13:47:37 -07001364void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001365 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001366 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001367{
1368 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1369
1370 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1371
1372 if (suspend) {
1373 if (index >= 0) {
1374 sessionEffects = mSuspendedSessions.valueAt(index);
1375 } else {
1376 mSuspendedSessions.add(sessionId, sessionEffects);
1377 }
1378 } else {
1379 if (index < 0) {
1380 return;
1381 }
1382 sessionEffects = mSuspendedSessions.valueAt(index);
1383 }
1384
1385
Andy Hung116bc262023-06-20 18:56:17 -07001386 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001387 if (type != NULL) {
1388 key = type->timeLow;
1389 }
1390 index = sessionEffects.indexOfKey(key);
1391
1392 sp<SuspendedSessionDesc> desc;
1393 if (suspend) {
1394 if (index >= 0) {
1395 desc = sessionEffects.valueAt(index);
1396 } else {
1397 desc = new SuspendedSessionDesc();
1398 if (type != NULL) {
1399 desc->mType = *type;
1400 }
1401 sessionEffects.add(key, desc);
1402 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1403 }
1404 desc->mRefCount++;
1405 } else {
1406 if (index < 0) {
1407 return;
1408 }
1409 desc = sessionEffects.valueAt(index);
1410 if (--desc->mRefCount == 0) {
1411 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1412 sessionEffects.removeItemsAt(index);
1413 if (sessionEffects.isEmpty()) {
1414 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1415 sessionId);
1416 mSuspendedSessions.removeItem(sessionId);
1417 }
1418 }
1419 }
1420 if (!sessionEffects.isEmpty()) {
1421 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1422 }
1423}
1424
Andy Hungee58e4a2023-07-07 13:47:37 -07001425void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001426 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001427 bool threadLocked)
1428NO_THREAD_SAFETY_ANALYSIS // manual locking
1429{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001430 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001431 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001432 }
Eric Laurent81784c32012-11-19 14:55:58 -08001433
Eric Laurent81784c32012-11-19 14:55:58 -08001434 if (mType != RECORD) {
1435 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1436 // another session. This gives the priority to well behaved effect control panels
1437 // and applications not using global effects.
1438 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1439 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001440 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001441 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1442 }
1443 }
1444
Eric Laurent6b446ce2019-12-13 10:56:31 -08001445 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001446 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001447 }
1448}
1449
Andy Hungc5007f82023-08-29 14:26:09 -07001450// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001451status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001452 const effect_descriptor_t *desc, audio_session_t sessionId)
1453{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001454 // No global output effect sessions on record threads
1455 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1456 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001457 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1458 desc->name, mThreadName);
1459 return BAD_VALUE;
1460 }
1461 // only pre processing effects on record thread
1462 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1463 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1464 desc->name, mThreadName);
1465 return BAD_VALUE;
1466 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001467
1468 // always allow effects without processing load or latency
1469 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1470 return NO_ERROR;
1471 }
1472
Eric Laurent4c415062016-06-17 16:14:16 -07001473 audio_input_flags_t flags = mInput->flags;
1474 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1475 if (flags & AUDIO_INPUT_FLAG_RAW) {
1476 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1477 desc->name, mThreadName);
1478 return BAD_VALUE;
1479 }
1480 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1481 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1482 desc->name, mThreadName);
1483 return BAD_VALUE;
1484 }
1485 }
jiabineb3bda02020-06-30 14:07:03 -07001486
Andy Hung116bc262023-06-20 18:56:17 -07001487 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001488 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1489 return BAD_VALUE;
1490 }
Eric Laurent4c415062016-06-17 16:14:16 -07001491 return NO_ERROR;
1492}
1493
Andy Hungc5007f82023-08-29 14:26:09 -07001494// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001495status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001496 const effect_descriptor_t *desc, audio_session_t sessionId)
1497{
1498 // no preprocessing on playback threads
1499 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001500 ALOGW("%s: pre processing effect %s created on playback"
1501 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001502 return BAD_VALUE;
1503 }
1504
Eric Laurent3e4de772017-07-16 16:55:08 -07001505 // always allow effects without processing load or latency
1506 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1507 return NO_ERROR;
1508 }
1509
Andy Hung116bc262023-06-20 18:56:17 -07001510 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001511 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1512 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001513 return BAD_VALUE;
1514 }
1515
Eric Laurent4eb45d02023-12-20 12:07:17 +01001516 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001517 && mType != SPATIALIZER) {
1518 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1519 __func__, mType);
1520 return BAD_VALUE;
1521 }
1522
Eric Laurent4c415062016-06-17 16:14:16 -07001523 switch (mType) {
1524 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001525 audio_output_flags_t flags = mOutput->flags;
1526 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1527 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1528 // global effects are applied only to non fast tracks if they are SW
1529 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1530 break;
1531 }
1532 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1533 // only post processing on output stage session
1534 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001535 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1536 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001537 return BAD_VALUE;
1538 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001539 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1540 // only post processing on output stage session
1541 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001542 ALOGW("%s: non post processing effect %s not allowed on device session",
1543 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001544 return BAD_VALUE;
1545 }
Eric Laurent4c415062016-06-17 16:14:16 -07001546 } else {
1547 // no restriction on effects applied on non fast tracks
1548 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1549 break;
1550 }
1551 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001552
Eric Laurent4c415062016-06-17 16:14:16 -07001553 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001554 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001555 return BAD_VALUE;
1556 }
1557 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001558 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1559 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001560 return BAD_VALUE;
1561 }
1562 }
1563 } break;
1564 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001565 // nothing actionable on offload threads, if the effect:
1566 // - is offloadable: the effect can be created
1567 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1568 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001569 break;
1570 case DIRECT:
1571 // Reject any effect on Direct output threads for now, since the format of
1572 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001573 ALOGW("%s: effect %s on DIRECT output thread %s",
1574 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001575 return BAD_VALUE;
1576 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001577 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001578 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1579 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001580 return BAD_VALUE;
1581 }
1582 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001583 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1584 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001585 return BAD_VALUE;
1586 }
1587 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001588 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1589 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001590 return BAD_VALUE;
1591 }
1592 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001593 case SPATIALIZER:
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001594 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are supported on spatializer mixer, but only
1595 // the spatialized track have global effects applied for now.
Eric Laurentb62d0362021-10-26 17:40:18 +02001596 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1597 // are supported and added after the spatializer.
1598 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001599 ALOGD("%s: global effect %s on spatializer thread %s", __func__, desc->name,
1600 mThreadName);
Eric Laurentb62d0362021-10-26 17:40:18 +02001601 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1602 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001603 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001604 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1605 break;
1606 }
1607 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1608 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1609 __func__, desc->name);
1610 return BAD_VALUE;
1611 }
1612 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1613 // only post processing on output stage session
1614 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1615 ALOGW("%s: non post processing effect %s not allowed on device session",
1616 __func__, desc->name);
1617 return BAD_VALUE;
1618 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001619 }
1620 break;
jiabinc658e452022-10-21 20:52:21 +00001621 case BIT_PERFECT:
1622 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1623 // Allow HW accelerated effects of tunnel type
1624 break;
1625 }
1626 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1627 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1628 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1629 // 3) there is any bit-perfect track with the given session id.
1630 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1631 sessionId == AUDIO_SESSION_DEVICE) {
1632 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1633 __func__, desc->name, mThreadName);
1634 return BAD_VALUE;
1635 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1636 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1637 __func__, desc->name, sessionId);
1638 return BAD_VALUE;
1639 }
1640 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001641 default:
1642 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1643 }
1644
1645 return NO_ERROR;
1646}
1647
Andy Hungc5007f82023-08-29 14:26:09 -07001648// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001649sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001650 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001651 const sp<IEffectClient>& effectClient,
1652 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001653 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001654 effect_descriptor_t *desc,
1655 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001656 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001657 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001658 bool probe,
1659 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001660{
Andy Hung116bc262023-06-20 18:56:17 -07001661 sp<IAfEffectModule> effect;
1662 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001663 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001664 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001665 bool chainCreated = false;
1666 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001667 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001668
1669 lStatus = initCheck();
1670 if (lStatus != NO_ERROR) {
1671 ALOGW("createEffect_l() Audio driver not initialized.");
1672 goto Exit;
1673 }
1674
Eric Laurent81784c32012-11-19 14:55:58 -08001675 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1676
Andy Hungc5007f82023-08-29 14:26:09 -07001677 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001678 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001679
Eric Laurent4c415062016-06-17 16:14:16 -07001680 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001681 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001682 goto Exit;
1683 }
1684
Eric Laurent81784c32012-11-19 14:55:58 -08001685 // check for existing effect chain with the requested audio session
1686 chain = getEffectChain_l(sessionId);
1687 if (chain == 0) {
1688 // create a new chain for this session
1689 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001690 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001691 addEffectChain_l(chain);
1692 chain->setStrategy(getStrategyForSession_l(sessionId));
1693 chainCreated = true;
1694 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001695 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001696 }
1697
1698 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1699
1700 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001701 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001702 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001703 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001704 if (lStatus != NO_ERROR) {
1705 goto Exit;
1706 }
1707 effectCreated = true;
1708
jiabinc52b1ff2019-10-31 17:20:42 -07001709 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001710 effect->setDevices(outDeviceTypeAddrs());
1711 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001712 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001713 effect->setAudioSource(mAudioSource);
1714 }
jiabin1319f5a2021-03-30 22:21:24 +00001715 if (effect->isHapticGenerator()) {
1716 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1717 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001718 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001719 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001720 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001721 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001722 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001723 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001724 }
1725 }
Eric Laurent81784c32012-11-19 14:55:58 -08001726 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001727 handle = IAfEffectHandle::create(
1728 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001729 lStatus = handle->initCheck();
1730 if (lStatus == OK) {
1731 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001732 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001733 }
Eric Laurent81784c32012-11-19 14:55:58 -08001734 if (enabled != NULL) {
1735 *enabled = (int)effect->isEnabled();
1736 }
1737 }
1738
1739Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001740 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001741 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001742 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001743 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001744 }
Eric Laurent81784c32012-11-19 14:55:58 -08001745 if (chainCreated) {
1746 removeEffectChain_l(chain);
1747 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001748 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001749 }
1750
Glenn Kasten9156ef32013-08-06 15:39:08 -07001751 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001752 return handle;
1753}
1754
Andy Hungee58e4a2023-07-07 13:47:37 -07001755void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001756 bool unpinIfLast)
1757{
1758 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001759 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001760 {
Andy Hung972bec12023-08-31 16:13:39 -07001761 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001762 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001763 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001764 return;
1765 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001766 effect = effectBase->asEffectModule();
1767 if (effect == nullptr) {
1768 return;
1769 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001770 // restore suspended effects if the disconnected handle was enabled and the last one.
1771 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1772 if (remove) {
1773 removeEffect_l(effect, true);
1774 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001775 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001776 }
1777 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001778 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001779 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001780 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001781 }
1782 }
1783}
1784
Andy Hungee58e4a2023-07-07 13:47:37 -07001785void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001786 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001787 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001788 broadcast_l();
1789 }
1790 if (!effect->isOffloadable()) {
1791 if (mType == ThreadBase::OFFLOAD) {
1792 PlaybackThread *t = (PlaybackThread *)this;
1793 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1794 }
1795 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001796 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001797 }
1798 }
1799}
1800
Andy Hungee58e4a2023-07-07 13:47:37 -07001801void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001802 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001803 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001804 broadcast_l();
1805 }
1806}
1807
Andy Hungee58e4a2023-07-07 13:47:37 -07001808sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001809 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001810{
Andy Hung972bec12023-08-31 16:13:39 -07001811 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001812 return getEffect_l(sessionId, effectId);
1813}
1814
Andy Hungee58e4a2023-07-07 13:47:37 -07001815sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001816 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001817{
Andy Hung116bc262023-06-20 18:56:17 -07001818 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001819 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1820}
1821
Andy Hungee58e4a2023-07-07 13:47:37 -07001822std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001823{
Andy Hung116bc262023-06-20 18:56:17 -07001824 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001825 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001826}
1827
Andy Hung972bec12023-08-31 16:13:39 -07001828// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1829// ThreadBase::mutex() held
1830status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001831{
1832 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001833 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001834 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001835 bool chainCreated = false;
1836
Eric Laurent5baf2af2013-09-12 17:37:00 -07001837 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001838 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1839 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001840
Eric Laurent81784c32012-11-19 14:55:58 -08001841 if (chain == 0) {
1842 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001843 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001844 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001845 addEffectChain_l(chain);
1846 chain->setStrategy(getStrategyForSession_l(sessionId));
1847 chainCreated = true;
1848 }
Andy Hung972bec12023-08-31 16:13:39 -07001849 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001850
1851 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001852 ALOGW("%s: %p effect %s already present in chain %p",
1853 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001854 return BAD_VALUE;
1855 }
1856
Shunkai Yaod125e402024-01-20 03:19:06 +00001857 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001858
Shunkai Yao29d10572024-03-19 04:31:47 +00001859 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001860 if (status != NO_ERROR) {
1861 if (chainCreated) {
1862 removeEffectChain_l(chain);
1863 }
1864 return status;
1865 }
1866
jiabin8f278ee2019-11-11 12:16:27 -08001867 effect->setDevices(outDeviceTypeAddrs());
1868 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001869 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001870 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001871
Eric Laurent81784c32012-11-19 14:55:58 -08001872 return NO_ERROR;
1873}
1874
Andy Hungee58e4a2023-07-07 13:47:37 -07001875void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001876
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001877 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001878 effect_descriptor_t desc = effect->desc();
1879 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1880 detachAuxEffect_l(effect->id());
1881 }
1882
Andy Hung116bc262023-06-20 18:56:17 -07001883 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001884 if (chain != 0) {
1885 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001886 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001887 removeEffectChain_l(chain);
1888 }
1889 } else {
1890 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1891 }
1892}
1893
Shunkai Yaof4847652024-01-12 00:25:20 +00001894void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1895 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001896{
1897 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001898 for (const auto& effectChain : effectChains) {
1899 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001900 }
1901}
1902
Shunkai Yaof4847652024-01-12 00:25:20 +00001903void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1904 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001905{
Shunkai Yaof4847652024-01-12 00:25:20 +00001906 for (const auto& effectChain : effectChains) {
1907 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001908 }
1909}
1910
Andy Hungee58e4a2023-07-07 13:47:37 -07001911sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001912{
Andy Hung972bec12023-08-31 16:13:39 -07001913 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001914 return getEffectChain_l(sessionId);
1915}
1916
Andy Hungee58e4a2023-07-07 13:47:37 -07001917sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001918 const
Eric Laurent81784c32012-11-19 14:55:58 -08001919{
1920 size_t size = mEffectChains.size();
1921 for (size_t i = 0; i < size; i++) {
1922 if (mEffectChains[i]->sessionId() == sessionId) {
1923 return mEffectChains[i];
1924 }
1925 }
1926 return 0;
1927}
1928
Andy Hungee58e4a2023-07-07 13:47:37 -07001929void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001930{
Andy Hung972bec12023-08-31 16:13:39 -07001931 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001932 size_t size = mEffectChains.size();
1933 for (size_t i = 0; i < size; i++) {
1934 mEffectChains[i]->setMode_l(mode);
1935 }
1936}
1937
Andy Hungee58e4a2023-07-07 13:47:37 -07001938void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001939{
1940 config->type = AUDIO_PORT_TYPE_MIX;
1941 config->ext.mix.handle = mId;
1942 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001943 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001944 config->channel_mask = mChannelMask;
1945 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1946 AUDIO_PORT_CONFIG_FORMAT;
1947}
1948
Andy Hungee58e4a2023-07-07 13:47:37 -07001949void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001950{
Andy Hung972bec12023-08-31 16:13:39 -07001951 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001952 if (mSystemReady) {
1953 return;
1954 }
1955 mSystemReady = true;
1956
1957 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1958 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1959 }
1960 mPendingConfigEvents.clear();
1961}
1962
Andy Hungdae27702016-10-31 14:01:16 -07001963template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001964ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001965 ssize_t index = mActiveTracks.indexOf(track);
1966 if (index >= 0) {
1967 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1968 return index;
1969 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001970 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001971 mActiveTracksGeneration++;
1972 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001973 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001974 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001975 return mActiveTracks.add(track);
1976}
1977
1978template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001979ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001980 ssize_t index = mActiveTracks.remove(track);
1981 if (index < 0) {
1982 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1983 return index;
1984 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001985 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001986 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001987 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001988 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001989 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001990#ifdef TEE_SINK
1991 track->dumpTee(-1 /* fd */, "_REMOVE");
1992#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001993 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001994 return index;
1995}
1996
1997template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001998void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001999 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07002000 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002001 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07002002 }
2003 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07002004 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07002005 mActiveTracks.clear();
2006 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07002007}
2008
2009template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07002010void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07002011 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07002012 // Updates ActiveTracks client uids to the thread wakelock.
2013 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2014 thread->updateWakeLockUids_l(getWakeLockUids());
2015 mLastActiveTracksGeneration = mActiveTracksGeneration;
2016 }
Andy Hungdae27702016-10-31 14:01:16 -07002017}
Eric Laurent83b88082014-06-20 18:31:16 -07002018
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002019template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002020bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002021 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002022 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002023
2024 for (const sp<T> &track : mActiveTracks) {
2025 // Do not short-circuit as all hasChanged states must be reset
2026 // as all the metadata are going to be sent
2027 hasChanged |= track->readAndClearHasChanged();
2028 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002029 return hasChanged;
2030}
2031
2032template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002033void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002034 const char *funcName, const sp<T> &track) const {
2035 if (mLocalLog != nullptr) {
2036 String8 result;
2037 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002038 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002039 }
2040}
2041
Andy Hungee58e4a2023-07-07 13:47:37 -07002042void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002043{
2044 // Thread could be blocked waiting for async
2045 // so signal it to handle state changes immediately
2046 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2047 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2048 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002049 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002050}
2051
Andy Hungd0979812019-02-21 15:51:44 -08002052// Call only from threadLoop() or when it is idle.
2053// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002054void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002055NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002056{
2057 // Do not log if we have no stats.
2058 // We choose the timestamp verifier because it is the most likely item to be present.
2059 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2060 if (nstats == 0) {
2061 return;
2062 }
2063
2064 // Don't log more frequently than once per 12 hours.
2065 // We use BOOTTIME to include suspend time.
2066 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2067 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2068 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2069 return;
2070 }
2071
2072 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2073 mLastRecordedTimeNs = timeNs;
2074
Ray Essickf27e9872019-12-07 06:28:46 -08002075 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002076
2077#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2078
2079 // thread configuration
2080 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2081 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2082 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2083 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2084 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2085 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2086 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002087 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2088 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002089
2090 // thread statistics
2091 if (mIoJitterMs.getN() > 0) {
2092 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2093 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2094 }
2095 if (mProcessTimeMs.getN() > 0) {
2096 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2097 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2098 }
2099 const auto tsjitter = mTimestampVerifier.getJitterMs();
2100 if (tsjitter.getN() > 0) {
2101 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2102 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2103 }
2104 if (mLatencyMs.getN() > 0) {
2105 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2106 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2107 }
Robert Wu06db0a32021-08-10 19:05:34 +00002108 if (mMonopipePipeDepthStats.getN() > 0) {
2109 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2110 mMonopipePipeDepthStats.getMean());
2111 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2112 mMonopipePipeDepthStats.getStdDev());
2113 }
Andy Hungd0979812019-02-21 15:51:44 -08002114
2115 item->selfrecord();
2116}
2117
Andy Hungee58e4a2023-07-07 13:47:37 -07002118product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002119{
Andy Hung583043b2023-07-17 17:05:00 -07002120 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002121 return PRODUCT_STRATEGY_NONE;
2122 }
2123 return AudioSystem::getStrategyForStream(stream);
2124}
2125
Andy Hungc5007f82023-08-29 14:26:09 -07002126// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002127void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002128 const sp<audio_utils::MelProcessor>& /*processor*/)
2129{
2130 // Do nothing
2131 ALOGW("%s: ThreadBase does not support CSD", __func__);
2132}
2133
Andy Hungc5007f82023-08-29 14:26:09 -07002134// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002135void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002136{
2137 // Do nothing
2138 ALOGW("%s: ThreadBase does not support CSD", __func__);
2139}
2140
Eric Laurent81784c32012-11-19 14:55:58 -08002141// ----------------------------------------------------------------------------
2142// Playback
2143// ----------------------------------------------------------------------------
2144
Andy Hung583043b2023-07-17 17:05:00 -07002145PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002146 AudioStreamOut* output,
2147 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002148 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002149 bool systemReady,
2150 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002151 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002152 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002153 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002154 mMixerBuffer(NULL),
2155 mMixerBufferSize(0),
2156 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2157 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002158 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002159 mEffectBuffer(NULL),
2160 mEffectBufferSize(0),
2161 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2162 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002163 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002164 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002165 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002166 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002167 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002168 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002169 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002170 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002171 mMixerStatus(MIXER_IDLE),
2172 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002173 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002174 mBytesRemaining(0),
2175 mCurrentWriteLength(0),
2176 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002177 mWriteAckSequence(0),
2178 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002179 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002180 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002181 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002182 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002183 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002184 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002185 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002186{
Glenn Kastend7dca052015-03-05 16:05:54 -08002187 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hungf767de02024-10-30 19:47:50 -07002188 mFlagsAsString = toString(output->flags);
Andy Hung583043b2023-07-17 17:05:00 -07002189 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002190
Andy Hungc5007f82023-08-29 14:26:09 -07002191 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002192 // it would be safer to explicitly pass initial masterVolume/masterMute as
2193 // parameter.
2194 //
2195 // If the HAL we are using has support for master volume or master mute,
2196 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2197 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002198 mMasterVolume = afThreadCallback->masterVolume_l();
2199 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002200 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002201 if (mOutput->audioHwDev->canSetMasterVolume()) {
2202 mMasterVolume = 1.0;
2203 }
2204
2205 if (mOutput->audioHwDev->canSetMasterMute()) {
2206 mMasterMute = false;
2207 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002208 mIsMsdDevice = strcmp(
2209 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002210 }
2211
Eric Laurentf1f22e72021-07-13 14:04:14 +02002212 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2213 mMixerChannelMask = mixerConfig->channel_mask;
2214 }
2215
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002216 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002217
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002218 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002219 && mMixerChannelMask != mChannelMask) {
2220 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2221 mChannelMask, mMixerChannelMask);
2222 }
2223
Andy Hungc8fddf32018-08-08 18:32:37 -07002224 // TODO: We may also match on address as well as device type for
2225 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002226 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002227 // TODO: This property should be ensure that only contains one single device type.
2228 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2229 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002230 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2231 : AUDIO_DEVICE_NONE));
2232 }
Andy Hung6b137d12024-08-27 22:35:17 +00002233 if (!audioserver_flags::portid_volume_management()) {
2234 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2235 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2236 mStreamTypes[stream].volume = 0.0f;
2237 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
2238 }
2239 // Audio patch and call assistant volume are always max
2240 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2241 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2242 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2243 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002244 }
Eric Laurent81784c32012-11-19 14:55:58 -08002245}
2246
Andy Hungee58e4a2023-07-07 13:47:37 -07002247PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002248{
Andy Hung583043b2023-07-17 17:05:00 -07002249 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002250 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002251 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002252 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002253 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002254}
2255
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002256// Thread virtuals
2257
Andy Hungee58e4a2023-07-07 13:47:37 -07002258void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002259{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002260 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002261 ALOGE("The stream is not open yet"); // This should not happen.
2262 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002263 // Callbacks take strong or weak pointers as a parameter.
2264 // Since PlaybackThread passes itself as a callback handler, it can only
2265 // be done outside of the constructor. Creating weak and especially strong
2266 // pointers to a refcounted object in its own constructor is strongly
2267 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2268 // Even if a function takes a weak pointer, it is possible that it will
2269 // need to convert it to a strong pointer down the line.
2270 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2271 mOutput->stream->setCallback(this) == OK) {
2272 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002273 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002274 }
2275
jiabinf6eb4c32020-02-25 14:06:25 -08002276 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002277 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002278 }
2279 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002280 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002281 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002282}
2283
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002284// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002285void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002286{
2287 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002288 status_t result = mOutput->stream->exit();
2289 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002290}
2291
Andy Hungee58e4a2023-07-07 13:47:37 -07002292void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002293{
Eric Laurent81784c32012-11-19 14:55:58 -08002294 String8 result;
Andy Hung6b137d12024-08-27 22:35:17 +00002295 if (!audioserver_flags::portid_volume_management()) {
2296 result.appendFormat(" Stream volumes in dB: ");
2297 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2298 const stream_type_t *st = &mStreamTypes[i];
2299 if (i > 0) {
2300 result.appendFormat(", ");
2301 }
2302 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2303 if (st->mute) {
2304 result.append("M");
2305 }
Eric Laurent81784c32012-11-19 14:55:58 -08002306 }
2307 }
2308 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002309 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002310 result.clear();
2311
Eric Laurent81784c32012-11-19 14:55:58 -08002312 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2313 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002314 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002315 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002316
2317 size_t numtracks = mTracks.size();
2318 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002319 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002320 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002321 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002322 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002323 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002324 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002325 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002326 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002327 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002328 if (track != 0) {
2329 bool active = mActiveTracks.indexOf(track) >= 0;
2330 if (active) {
2331 numactiveseen++;
2332 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002333 result.append(prefix);
2334 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002335 }
2336 }
2337 } else {
2338 result.append("\n");
2339 }
2340 if (numactiveseen != numactive) {
2341 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002342 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002343 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002344 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002345 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002346 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002347 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002348 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002349 result.append(prefix);
2350 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002351 }
2352 }
2353 }
2354
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002355 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002356}
2357
Andy Hungee58e4a2023-07-07 13:47:37 -07002358void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002359{
Andy Hung04cb8f72020-03-20 13:44:33 -07002360 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002361 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002362 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2363 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002364 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2365 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2366 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2367 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002368 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002369 dprintf(fd, " Total writes: %d\n", mNumWrites);
2370 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2371 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002372 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002373 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002374 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002375 AudioStreamOut *output = mOutput;
2376 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002377 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002378 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002379 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2380 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2381 if (mPipeSink.get() != nullptr) {
2382 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2383 }
2384 if (output != nullptr) {
2385 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002386 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002387 }
Eric Laurent81784c32012-11-19 14:55:58 -08002388}
2389
Andy Hungc5007f82023-08-29 14:26:09 -07002390// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002391sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002392 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002393 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002394 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002395 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002396 audio_format_t format,
2397 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002398 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002399 size_t *pNotificationFrameCount,
2400 uint32_t notificationsPerBuffer,
2401 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002402 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002403 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002404 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002405 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002406 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002407 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002408 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002409 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002410 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002411 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002412 bool isBitPerfect,
Andy Hung6b137d12024-08-27 22:35:17 +00002413 audio_output_flags_t *afTrackFlags,
Vlad Popa1e865e62024-08-15 19:11:42 -07002414 float volume,
2415 bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002416{
Glenn Kasten74935e42013-12-19 08:56:45 -08002417 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002418 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002419 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002420 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002421 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002422 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002423 uint32_t sampleRate;
2424
2425 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2426 lStatus = BAD_VALUE;
2427 goto Exit;
2428 }
Eric Laurent21da6472017-11-09 16:29:26 -08002429
2430 if (*pSampleRate == 0) {
2431 *pSampleRate = mSampleRate;
2432 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002433 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002434
2435 // special case for FAST flag considered OK if fast mixer is present
2436 if (hasFastMixer()) {
2437 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2438 }
2439
2440 // Check if requested flags are compatible with output stream flags
2441 if ((*flags & outputFlags) != *flags) {
2442 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2443 *flags, outputFlags);
2444 *flags = (audio_output_flags_t)(*flags & outputFlags);
2445 }
Eric Laurent81784c32012-11-19 14:55:58 -08002446
jiabinc658e452022-10-21 20:52:21 +00002447 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002448 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002449 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002450 if (chain.get() != nullptr) {
2451 // Bit-perfect is required according to the configuration and preferred mixer
2452 // attributes, but it is not in the output flag from the client's request. Explicitly
2453 // adding bit-perfect flag to check the compatibility
2454 audio_output_flags_t flagsToCheck =
2455 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2456 chain->checkOutputFlagCompatibility(&flagsToCheck);
2457 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2458 ALOGE("%s cannot create track as there is data-processing effect attached to "
2459 "given session id(%d)", __func__, sessionId);
2460 lStatus = BAD_VALUE;
2461 goto Exit;
2462 }
2463 *flags = flagsToCheck;
2464 }
2465 }
2466
Eric Laurent81784c32012-11-19 14:55:58 -08002467 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002468 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002469 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002470 // PCM data
2471 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002472 // TODO: extract as a data library function that checks that a computationally
2473 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002474 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002475 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2476 (channelMask == AUDIO_CHANNEL_OUT_MONO
2477 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002478 // hardware sample rate
2479 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002480 // normal mixer has an associated fast mixer
2481 hasFastMixer() &&
2482 // there are sufficient fast track slots available
2483 (mFastTrackAvailMask != 0)
2484 // FIXME test that MixerThread for this fast track has a capable output HAL
2485 // FIXME add a permission test also?
2486 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002487 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2488 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002489 // read the fast track multiplier property the first time it is needed
2490 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2491 if (ok != 0) {
2492 ALOGE("%s pthread_once failed: %d", __func__, ok);
2493 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002494 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002495 }
Eric Laurent4c415062016-06-17 16:14:16 -07002496
2497 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002498 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002499 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002500 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002501 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002502 AUDIO_SESSION_OUTPUT_STAGE,
2503 AUDIO_SESSION_OUTPUT_MIX,
2504 sessionId,
2505 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002506 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002507 if (chain.get() != nullptr) {
2508 audio_output_flags_t old = *flags;
2509 chain->checkOutputFlagCompatibility(flags);
2510 if (old != *flags) {
2511 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2512 (int)session, (int)old, (int)*flags);
2513 }
Eric Laurent4c415062016-06-17 16:14:16 -07002514 }
2515 }
2516 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002517 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002518 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2519 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002520 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002521 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002522 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002523 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002524 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002525 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002526 audio_is_linear_pcm(format), channelMask, sampleRate,
2527 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002528 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002529 }
2530 }
Eric Laurent21da6472017-11-09 16:29:26 -08002531
2532 if (!audio_has_proportional_frames(format)) {
2533 if (sharedBuffer != 0) {
2534 // Same comment as below about ignoring frameCount parameter for set()
2535 frameCount = sharedBuffer->size();
2536 } else if (frameCount == 0) {
2537 frameCount = mNormalFrameCount;
2538 }
2539 if (notificationFrameCount != frameCount) {
2540 notificationFrameCount = frameCount;
2541 }
2542 } else if (sharedBuffer != 0) {
2543 // FIXME: Ensure client side memory buffers need
2544 // not have additional alignment beyond sample
2545 // (e.g. 16 bit stereo accessed as 32 bit frame).
2546 size_t alignment = audio_bytes_per_sample(format);
2547 if (alignment & 1) {
2548 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2549 alignment = 1;
2550 }
2551 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2552 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2553 if (channelCount > 1) {
2554 // More than 2 channels does not require stronger alignment than stereo
2555 alignment <<= 1;
2556 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002557 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002558 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002559 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002560 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002561 goto Exit;
2562 }
Eric Laurent21da6472017-11-09 16:29:26 -08002563
2564 // When initializing a shared buffer AudioTrack via constructors,
2565 // there's no frameCount parameter.
2566 // But when initializing a shared buffer AudioTrack via set(),
2567 // there _is_ a frameCount parameter. We silently ignore it.
2568 frameCount = sharedBuffer->size() / frameSize;
2569 } else {
2570 size_t minFrameCount = 0;
2571 // For fast tracks we try to respect the application's request for notifications per buffer.
2572 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2573 if (notificationsPerBuffer > 0) {
2574 // Avoid possible arithmetic overflow during multiplication.
2575 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2576 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2577 notificationsPerBuffer, mFrameCount);
2578 } else {
2579 minFrameCount = mFrameCount * notificationsPerBuffer;
2580 }
2581 }
2582 } else {
2583 // For normal PCM streaming tracks, update minimum frame count.
2584 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2585 // cover audio hardware latency.
2586 // This is probably too conservative, but legacy application code may depend on it.
2587 // If you change this calculation, also review the start threshold which is related.
2588 uint32_t latencyMs = latency_l();
2589 if (latencyMs == 0) {
2590 ALOGE("Error when retrieving output stream latency");
2591 lStatus = UNKNOWN_ERROR;
2592 goto Exit;
2593 }
2594
2595 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2596 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2597
Eric Laurent81784c32012-11-19 14:55:58 -08002598 }
Eric Laurent21da6472017-11-09 16:29:26 -08002599 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002600 frameCount = minFrameCount;
2601 }
Eric Laurent81784c32012-11-19 14:55:58 -08002602 }
Eric Laurent21da6472017-11-09 16:29:26 -08002603
2604 // Make sure that application is notified with sufficient margin before underrun.
2605 // The client can divide the AudioTrack buffer into sub-buffers,
2606 // and expresses its desire to server as the notification frame count.
2607 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2608 size_t maxNotificationFrames;
2609 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2610 // notify every HAL buffer, regardless of the size of the track buffer
2611 maxNotificationFrames = mFrameCount;
2612 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002613 // Triple buffer the notification period for a triple buffered mixer period;
2614 // otherwise, double buffering for the notification period is fine.
2615 //
2616 // TODO: This should be moved to AudioTrack to modify the notification period
2617 // on AudioTrack::setBufferSizeInFrames() changes.
2618 const int nBuffering =
2619 (uint64_t{frameCount} * mSampleRate)
2620 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2621
Eric Laurent21da6472017-11-09 16:29:26 -08002622 maxNotificationFrames = frameCount / nBuffering;
2623 // If client requested a fast track but this was denied, then use the smaller maximum.
2624 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2625 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2626 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2627 maxNotificationFrames = maxNotificationFramesFastDenied;
2628 }
2629 }
2630 }
2631 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2632 if (notificationFrameCount == 0) {
2633 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2634 maxNotificationFrames, frameCount);
2635 } else {
2636 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2637 notificationFrameCount, maxNotificationFrames, frameCount);
2638 }
2639 notificationFrameCount = maxNotificationFrames;
2640 }
2641 }
2642
Glenn Kasten74935e42013-12-19 08:56:45 -08002643 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002644 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002645
Glenn Kastenc3df8382014-03-13 15:05:25 -07002646 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002647 case BIT_PERFECT:
2648 if (isBitPerfect) {
2649 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2650 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2651 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2652 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2653 mChannelMask);
2654 lStatus = BAD_VALUE;
2655 goto Exit;
2656 }
2657 }
2658 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002659
2660 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002661 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002662 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002663 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2664 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002665 sampleRate, format, channelMask, mOutput, mFormat);
2666 lStatus = BAD_VALUE;
2667 goto Exit;
2668 }
2669 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002670 break;
2671
2672 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002674 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2675 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 sampleRate, format, channelMask, mOutput, mFormat);
2677 lStatus = BAD_VALUE;
2678 goto Exit;
2679 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002680 break;
2681
2682 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002683 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002684 ALOGE("createTrack_l() Bad parameter: format %#x \""
2685 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 format, mOutput, mFormat);
2687 lStatus = BAD_VALUE;
2688 goto Exit;
2689 }
Andy Hungcd044842014-08-07 11:04:34 -07002690 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002691 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2692 lStatus = BAD_VALUE;
2693 goto Exit;
2694 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002695 break;
2696
Eric Laurent81784c32012-11-19 14:55:58 -08002697 }
2698
2699 lStatus = initCheck();
2700 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002701 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002702 goto Exit;
2703 }
2704
Andy Hungc5007f82023-08-29 14:26:09 -07002705 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002706 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002707
2708 // all tracks in same audio session must share the same routing strategy otherwise
2709 // conflicts will happen when tracks are moved from one output to another by audio policy
2710 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002711 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002712 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002713 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002714 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002715 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002716 if (sessionId == t->sessionId() && strategy != actual) {
2717 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2718 strategy, actual);
2719 lStatus = BAD_VALUE;
2720 goto Exit;
2721 }
2722 }
2723 }
2724
Deeraj Soman2b515232024-05-14 12:58:24 +05302725 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2726 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002727 // dynamic audio policy.
2728 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302729 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002730 audio_output_flags_t trackFlags = *flags;
2731 if (mType == DIRECT) {
2732 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302733 } else if (mType == OFFLOAD) {
2734 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2735 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002736 }
jiabin94ed47c2023-07-27 23:34:20 +00002737 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002738
Andy Hung8d31fd22023-06-26 19:20:57 -07002739 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002740 channelMask, frameCount,
2741 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002742 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002743 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Vlad Popa1e865e62024-08-15 19:11:42 -07002744 speed, isSpatialized, isBitPerfect, volume, muted);
Glenn Kasten03003332013-08-06 15:40:54 -07002745
Glenn Kasten03003332013-08-06 15:40:54 -07002746 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2747 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002748 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002749 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002750 goto Exit;
2751 }
2752 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002753 {
Andy Hung972bec12023-08-31 16:13:39 -07002754 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002755 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002756 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002757 }
2758 }
Eric Laurent81784c32012-11-19 14:55:58 -08002759
Andy Hung116bc262023-06-20 18:56:17 -07002760 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002761 if (chain != 0) {
2762 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2763 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002764 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002765 chain->incTrackCnt();
2766 }
2767
Eric Laurent05067782016-06-01 18:27:28 -07002768 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002769 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2770 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2771 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002772 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002773 }
2774 }
2775
2776 lStatus = NO_ERROR;
2777
2778Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002779 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002780 return track;
2781}
2782
Andy Hung1bc088a2018-02-09 15:57:31 -08002783template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002784ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002785{
Andy Hungc0691382018-09-12 18:01:57 -07002786 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002787 const ssize_t index = mTracks.remove(track);
2788 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002789 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002790 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002791 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002792 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002793 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002794 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002795 }
2796 return index;
2797}
2798
Andy Hungee58e4a2023-07-07 13:47:37 -07002799uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002800{
2801 return latency;
2802}
2803
Andy Hungee58e4a2023-07-07 13:47:37 -07002804uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002805{
Andy Hung972bec12023-08-31 16:13:39 -07002806 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002807 return latency_l();
2808}
Andy Hungee58e4a2023-07-07 13:47:37 -07002809uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002810NO_THREAD_SAFETY_ANALYSIS
2811// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002812{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002813 uint32_t latency;
2814 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2815 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002816 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002817 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002818}
2819
Andy Hungee58e4a2023-07-07 13:47:37 -07002820void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002821{
Andy Hung972bec12023-08-31 16:13:39 -07002822 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002823 // Don't apply master volume in SW if our HAL can do it for us.
2824 if (mOutput && mOutput->audioHwDev &&
2825 mOutput->audioHwDev->canSetMasterVolume()) {
2826 mMasterVolume = 1.0;
2827 } else {
2828 mMasterVolume = value;
2829 }
2830}
2831
Andy Hungee58e4a2023-07-07 13:47:37 -07002832void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002833{
2834 mMasterBalance.store(balance);
2835}
2836
Andy Hungee58e4a2023-07-07 13:47:37 -07002837void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002838{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002839 if (isDuplicating()) {
2840 return;
2841 }
Andy Hung972bec12023-08-31 16:13:39 -07002842 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002843 // Don't apply master mute in SW if our HAL can do it for us.
2844 if (mOutput && mOutput->audioHwDev &&
2845 mOutput->audioHwDev->canSetMasterMute()) {
2846 mMasterMute = false;
2847 } else {
2848 mMasterMute = muted;
2849 }
2850}
2851
Vlad Popa1e865e62024-08-15 19:11:42 -07002852void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002853{
Vlad Popa1e865e62024-08-15 19:11:42 -07002854 ALOGV("%s: stream %d value %f muted %d", __func__, stream, value, muted);
Andy Hung972bec12023-08-31 16:13:39 -07002855 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002856 mStreamTypes[stream].volume = value;
Vlad Popa1e865e62024-08-15 19:11:42 -07002857 if (com_android_media_audio_ring_my_car()) {
2858 mStreamTypes[stream].mute = muted;
2859 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07002860 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002861}
2862
Andy Hungee58e4a2023-07-07 13:47:37 -07002863void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002864{
Andy Hung972bec12023-08-31 16:13:39 -07002865 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002866 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002867 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002868}
2869
Andy Hungee58e4a2023-07-07 13:47:37 -07002870float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002871{
Andy Hung972bec12023-08-31 16:13:39 -07002872 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002873 return mStreamTypes[stream].volume;
2874}
2875
Andy Hung6b137d12024-08-27 22:35:17 +00002876status_t PlaybackThread::setPortsVolume(
Vlad Popa1e865e62024-08-15 19:11:42 -07002877 const std::vector<audio_port_handle_t>& portIds, float volume, bool muted) {
Andy Hung6b137d12024-08-27 22:35:17 +00002878 audio_utils::lock_guard _l(mutex());
2879 for (const auto& portId : portIds) {
2880 for (size_t i = 0; i < mTracks.size(); i++) {
2881 sp<IAfTrack> track = mTracks[i].get();
2882 if (portId == track->portId()) {
2883 track->setPortVolume(volume);
Vlad Popa1e865e62024-08-15 19:11:42 -07002884 track->setPortMute(muted);
Andy Hung6b137d12024-08-27 22:35:17 +00002885 break;
2886 }
2887 }
2888 }
2889 broadcast_l();
2890 return NO_ERROR;
2891}
2892
Andy Hungee58e4a2023-07-07 13:47:37 -07002893void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002894{
2895 mOutput->stream->setVolume(left, right);
2896}
2897
Andy Hungc5007f82023-08-29 14:26:09 -07002898// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002899status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002900{
2901 status_t status = ALREADY_EXISTS;
2902
Eric Laurent81784c32012-11-19 14:55:58 -08002903 if (mActiveTracks.indexOf(track) < 0) {
2904 // the track is newly added, make sure it fills up all its
2905 // buffers before playing. This is to ensure the client will
2906 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002907 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002908 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002909 // Because the track is not on the ActiveTracks,
2910 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002911 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002912 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002913 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002915 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002917 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002918 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002919 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002920 }
2921 return INVALID_OPERATION;
2922 }
2923 // abort if start is rejected by audio policy manager
2924 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002925 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2926 // current playback thread is reopened, which may happen when clients set preferred
2927 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2928 // immediately.
2929 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002930 }
2931#ifdef ADD_BATTERY_DATA
2932 // to track the speaker usage
2933 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2934#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002935 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 }
2937
Eric Laurent51716182016-02-29 18:00:56 -08002938 // set retry count for buffer fill
2939 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002940 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002941 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002942 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002943 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002944 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002945 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002946 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002947 track->retryCount() = kMaxTrackStartupRetries;
2948 track->fillingStatus() =
2949 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002950 }
2951
Andy Hung116bc262023-06-20 18:56:17 -07002952 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002953 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2954 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002955 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002956 // Unlock due to VibratorService will lock for this call and will
2957 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002958 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002959 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002960 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002961 std::optional<media::AudioVibratorInfo> vibratorInfo;
2962 {
2963 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2964 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002965 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002966 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002967 }
Andy Hungc5007f82023-08-29 14:26:09 -07002968 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002969 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002970 if (vibratorInfo) {
2971 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2972 }
2973
jiabin57303cc2018-12-18 15:45:57 -08002974 // Haptic playback should be enabled by vibrator service.
2975 if (track->getHapticPlaybackEnabled()) {
2976 // Disable haptic playback of all active track to ensure only
2977 // one track playing haptic if current track should play haptic.
2978 for (const auto &t : mActiveTracks) {
2979 t->setHapticPlaybackEnabled(false);
2980 }
jiabin245cdd92018-12-07 17:55:15 -08002981 }
jiabine70bc7f2020-06-30 22:07:55 -07002982
2983 // Set haptic intensity for effect
2984 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002985 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002986 }
jiabin245cdd92018-12-07 17:55:15 -08002987 }
2988
Andy Hung8d31fd22023-06-26 19:20:57 -07002989 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002990 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002991
2992 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2993 // all key changes are complete. It is possible that the threadLoop will begin
2994 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002995 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002996
Eric Laurentd0107bc2013-06-11 14:38:48 -07002997 if (chain != 0) {
2998 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2999 track->sessionId());
3000 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08003001 }
3002
Andy Hungc2b11cb2020-04-22 09:04:01 -07003003 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08003004 status = NO_ERROR;
3005 }
3006
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003007 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08003008 return status;
3009}
3010
Andy Hungee58e4a2023-07-07 13:47:37 -07003011bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003012{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003013 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08003014 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003015 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07003016 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003017 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08003018 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07003019 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07003020 if (track->isPausePending()) {
3021 track->pauseAck();
3022 }
Andy Hung8d31fd22023-06-26 19:20:57 -07003023 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08003024 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003025
3026 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08003027}
3028
Andy Hungee58e4a2023-07-07 13:47:37 -07003029void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003030{
3031 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08003032
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003033 String8 result;
3034 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003035 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08003036
Eric Laurent81784c32012-11-19 14:55:58 -08003037 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003038 {
Andy Hung972bec12023-08-31 16:13:39 -07003039 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003040 mAudioTrackCallbacks.erase(track);
3041 }
Eric Laurent81784c32012-11-19 14:55:58 -08003042 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003043 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003044 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003045 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3046 mFastTrackAvailMask |= 1 << index;
3047 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003048 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003049 }
Andy Hung116bc262023-06-20 18:56:17 -07003050 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003051 if (chain != 0) {
3052 chain->decTrackCnt();
3053 }
3054}
3055
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003056std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3057{
3058 std::set<int32_t> result;
3059 for (const auto& t : mTracks) {
3060 if (t->isExternalTrack()) {
3061 result.insert(t->portId());
3062 }
3063 }
3064 return result;
3065}
3066
3067std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3068{
3069 audio_utils::lock_guard _l(mutex());
3070 return getTrackPortIds_l();
3071}
3072
Andy Hungee58e4a2023-07-07 13:47:37 -07003073String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003074{
Andy Hung972bec12023-08-31 16:13:39 -07003075 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003076 String8 out_s8;
3077 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3078 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003079 }
Andy Hung920f6572022-10-06 12:09:49 -07003080 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003081}
3082
Andy Hungee58e4a2023-07-07 13:47:37 -07003083status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003084 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003085 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003086 return NO_INIT;
3087 }
3088 return mOutput->stream->selectPresentation(presentationId, programId);
3089}
3090
Andy Hungab65b182023-09-06 19:41:47 -07003091void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003092 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003093 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003094 sp<AudioIoDescriptor> desc;
3095 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003096 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003097 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003098 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003099 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003100 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3101 mSampleRate, mFormat, mChannelMask,
3102 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3103 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003104 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003105 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003106 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003107 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003108 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003109 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003110 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003111 break;
3112 }
Andy Hungab65b182023-09-06 19:41:47 -07003113 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003114}
3115
Andy Hungee58e4a2023-07-07 13:47:37 -07003116void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003118 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119}
3120
Andy Hungee58e4a2023-07-07 13:47:37 -07003121void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003122{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003123 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003124}
3125
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003126void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003127{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003128 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003129}
3130
Andy Hungee58e4a2023-07-07 13:47:37 -07003131void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003132 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003133{
Andy Hungee58e4a2023-07-07 13:47:37 -07003134 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003135 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003136 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003137 if (playbackThread == nullptr) {
3138 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3139 return;
3140 }
3141
jiabinf6eb4c32020-02-25 14:06:25 -08003142 audio_utils::metadata::Data metadata =
3143 audio_utils::metadata::dataFromByteString(metadataBs);
3144 if (metadata.empty()) {
3145 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3146 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3147 (int)metadataBs.size());
3148 return;
3149 }
3150
3151 audio_utils::metadata::ByteString metaDataStr =
3152 audio_utils::metadata::byteStringFromData(metadata);
3153 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003154 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003155 for (const auto& callbackPair : mAudioTrackCallbacks) {
3156 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003157 }
3158 }).detach();
3159}
3160
Andy Hungee58e4a2023-07-07 13:47:37 -07003161void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162{
Andy Hung972bec12023-08-31 16:13:39 -07003163 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003164 // reject out of sequence requests
3165 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3166 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003167 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003168 }
3169}
3170
Andy Hungee58e4a2023-07-07 13:47:37 -07003171void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003172{
Andy Hung972bec12023-08-31 16:13:39 -07003173 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003174 // reject out of sequence requests
3175 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003176 // Register discontinuity when HW drain is completed because that can cause
3177 // the timestamp frame position to reset to 0 for direct and offload threads.
3178 // (Out of sequence requests are ignored, since the discontinuity would be handled
3179 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003180 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003181 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003182 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183 }
3184}
3185
Andy Hungee58e4a2023-07-07 13:47:37 -07003186void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003187NO_THREAD_SAFETY_ANALYSIS
3188// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003189{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003190 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003191 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3192 mSampleRate = audioConfig.sample_rate;
3193 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003194 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003195 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003196 }
Andy Hung81994d62023-07-20 21:44:14 -07003197 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003198 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3199 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003200 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003201
3202 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3203 mMixerChannelMask = mChannelMask;
3204 }
3205
Andy Hunge5412692014-05-16 11:25:07 -07003206 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003207 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003208
Eric Laurentf1f22e72021-07-13 14:04:14 +02003209 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3210
Phil Burkca5e6142015-07-14 09:42:29 -07003211 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003212 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003213 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003214 // Get format from the shim, which will be different than the HAL format
3215 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003216 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003217 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003218 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003219 }
Andy Hung81994d62023-07-20 21:44:14 -07003220 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003221 LOG_FATAL("HAL format %#x not supported for mixed output",
3222 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003223 }
Phil Burk062e67a2015-02-11 13:40:50 -08003224 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003225 result = mOutput->stream->getBufferSize(&mBufferSize);
3226 LOG_ALWAYS_FATAL_IF(result != OK,
3227 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003228 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003229 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003230 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003231 mFrameCount);
3232 }
3233
Eric Laurentd1f69b02014-12-15 14:33:13 -08003234 mHwSupportsPause = false;
3235 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003236 bool supportsPause = false, supportsResume = false;
3237 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3238 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003239 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003240 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003241 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003242 } else if (supportsResume) {
3243 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003244 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003245 }
3246 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003247 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3248 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3249 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003250
Andy Hungfbfc3952015-01-15 13:33:51 -08003251 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3252 // For best precision, we use float instead of the associated output
3253 // device format (typically PCM 16 bit).
3254
3255 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3256 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3257 mBufferSize = mFrameSize * mFrameCount;
3258
3259 // TODO: We currently use the associated output device channel mask and sample rate.
3260 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3261 // (if a valid mask) to avoid premature downmix.
3262 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3263 // instead of the output device sample rate to avoid loss of high frequency information.
3264 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3265 }
3266
Andy Hung09a50072014-02-27 14:30:47 -08003267 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003268 double multiplier = 1.0;
Henrik Tillman470b3992024-10-08 12:49:28 +02003269 // Note: mType == SPATIALIZER does not support FastMixer and DEEP is by definition not "fast"
3270 if ((mType == MIXER && !(mOutput->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) &&
3271 (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003272 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3273 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003274
Eric Laurent81784c32012-11-19 14:55:58 -08003275 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3276 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3277 maxNormalFrameCount = maxNormalFrameCount & ~15;
3278 if (maxNormalFrameCount < minNormalFrameCount) {
3279 maxNormalFrameCount = minNormalFrameCount;
3280 }
3281 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3282 if (multiplier <= 1.0) {
3283 multiplier = 1.0;
3284 } else if (multiplier <= 2.0) {
3285 if (2 * mFrameCount <= maxNormalFrameCount) {
3286 multiplier = 2.0;
3287 } else {
3288 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3289 }
3290 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003291 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003292 }
3293 }
3294 mNormalFrameCount = multiplier * mFrameCount;
3295 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003296 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003297 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3298 }
Andy Hungab65b182023-09-06 19:41:47 -07003299 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3300 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003301
Andy Hung08fb1742015-05-31 23:22:10 -07003302 // Check if we want to throttle the processing to no more than 2x normal rate
3303 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003304 mThreadThrottleTimeMs = 0;
3305 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003306 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3307
Andy Hung010a1a12014-03-13 13:57:33 -07003308 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3309 // Originally this was int16_t[] array, need to remove legacy implications.
3310 free(mSinkBuffer);
3311 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003312
Andy Hung5b10a202014-03-13 13:59:29 -07003313 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3314 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3315 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003316 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003317
Andy Hung69aed5f2014-02-25 17:24:40 -08003318 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3319 // drives the output.
3320 free(mMixerBuffer);
3321 mMixerBuffer = NULL;
3322 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003323 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003324 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003325 * audio_bytes_per_sample(mMixerBufferFormat);
3326 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3327 }
Andy Hung98ef9782014-03-04 14:46:50 -08003328 free(mEffectBuffer);
3329 mEffectBuffer = NULL;
3330 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003331 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003332 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003333 * audio_bytes_per_sample(mEffectBufferFormat);
3334 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3335 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003336
Eric Laurentb62d0362021-10-26 17:40:18 +02003337 if (mType == SPATIALIZER) {
3338 free(mPostSpatializerBuffer);
3339 mPostSpatializerBuffer = nullptr;
3340 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3341 * audio_bytes_per_sample(mEffectBufferFormat);
3342 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3343 }
3344
Mikhail Naganov55773032020-10-01 15:08:13 -07003345 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3346 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003347 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3348 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003349 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003350
Eric Laurent81784c32012-11-19 14:55:58 -08003351 // force reconfiguration of effect chains and engines to take new buffer size and audio
3352 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003353 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003354 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3355 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003356 // create a copy of mEffectChains as calling moveEffectChain_ll()
3357 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003358 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003359 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003360 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003361 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003362 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003363
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003364 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003365 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003366 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003367 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003368 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3369 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3370 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3371 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3372 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3373 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3374 (int32_t)mHapticChannelMask)
3375 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3376 (int32_t)mHapticChannelCount)
3377 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003378 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003379 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3380 (int32_t)mFrameCount) // sic - added HAL
3381 ;
3382 uint32_t latencyMs;
3383 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3384 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3385 }
3386 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003387}
3388
Andy Hungee58e4a2023-07-07 13:47:37 -07003389ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003390{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003391 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003392 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003393 }
3394 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003395 static const bool stereo_spatialization_property =
3396 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3397 const bool stereo_spatialization_enabled =
3398 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3399 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003400 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3401 for (const sp<IAfTrack>& track : mActiveTracks) {
3402 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3403 allSessionsMetadata[track->sessionId()];
3404 auto backInserter = std::back_inserter(sessionMetadata);
3405 // No track is invalid as this is called after prepareTrack_l in the same
3406 // critical section
3407 track->copyMetadataTo(backInserter);
3408 }
3409 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3410 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3411 metadata.tracks.insert(metadata.tracks.end(),
3412 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3413 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3414 chain->sendMetadata_l(sessionTrackMetadata, {});
3415 }
3416 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3417 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3418 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3419 }
3420 }
3421 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3422 chain->sendMetadata_l(metadata.tracks, {});
3423 }
3424 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3425 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3426 }
3427 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3428 chain->sendMetadata_l(metadata.tracks, {});
3429 }
3430 } else {
3431 auto backInserter = std::back_inserter(metadata.tracks);
3432 for (const sp<IAfTrack>& track : mActiveTracks) {
3433 // No track is invalid as this is called after prepareTrack_l in the same
3434 // critical section
3435 track->copyMetadataTo(backInserter);
3436 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003437 }
Kevin Rocard12381092018-04-11 09:19:59 -07003438 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003439 MetadataUpdate change;
3440 change.playbackMetadataUpdate = metadata.tracks;
3441 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003442}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003443
Andy Hungee58e4a2023-07-07 13:47:37 -07003444void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003445 const StreamOutHalInterface::SourceMetadata& metadata)
3446{
3447 mOutput->stream->updateSourceMetadata(metadata);
3448};
3449
Andy Hungee58e4a2023-07-07 13:47:37 -07003450status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003451 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003452{
3453 if (halFrames == NULL || dspFrames == NULL) {
3454 return BAD_VALUE;
3455 }
Andy Hung972bec12023-08-31 16:13:39 -07003456 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003457 if (initCheck() != NO_ERROR) {
3458 return INVALID_OPERATION;
3459 }
Andy Hung818e7a32016-02-16 18:08:07 -08003460 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003461 *halFrames = framesWritten;
3462
3463 if (isSuspended()) {
3464 // return an estimation of rendered frames when the output is suspended
3465 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003466 *dspFrames = (uint32_t)
3467 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003468 return NO_ERROR;
3469 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003470 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003471 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003472 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003473 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003474 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003475 }
3476}
3477
Andy Hungee58e4a2023-07-07 13:47:37 -07003478product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003479{
3480 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3481 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3482 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003483 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003484 }
3485 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003486 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003487 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003488 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003489 }
3490 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003491 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003492}
3493
3494
Andy Hungee58e4a2023-07-07 13:47:37 -07003495AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003496{
Andy Hung972bec12023-08-31 16:13:39 -07003497 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003498 return mOutput;
3499}
3500
Andy Hungee58e4a2023-07-07 13:47:37 -07003501AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003502{
Andy Hung972bec12023-08-31 16:13:39 -07003503 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003504 AudioStreamOut *output = mOutput;
3505 mOutput = NULL;
3506 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3507 // must push a NULL and wait for ack
3508 mOutputSink.clear();
3509 mPipeSink.clear();
3510 mNormalSink.clear();
3511 return output;
3512}
3513
Andy Hungc5007f82023-08-29 14:26:09 -07003514// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003515sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003516{
3517 if (mOutput == NULL) {
3518 return NULL;
3519 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003520 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003521}
3522
Andy Hungee58e4a2023-07-07 13:47:37 -07003523uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003524{
3525 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3526}
3527
Andy Hungee58e4a2023-07-07 13:47:37 -07003528status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003529{
3530 if (!isValidSyncEvent(event)) {
3531 return BAD_VALUE;
3532 }
3533
Andy Hung972bec12023-08-31 16:13:39 -07003534 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003535
3536 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003537 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003538 if (event->triggerSession() == track->sessionId()) {
3539 (void) track->setSyncEvent(event);
3540 return NO_ERROR;
3541 }
3542 }
3543
3544 return NAME_NOT_FOUND;
3545}
3546
Andy Hungee58e4a2023-07-07 13:47:37 -07003547bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003548{
3549 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3550}
3551
Andy Hungee58e4a2023-07-07 13:47:37 -07003552void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003553 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003554{
Andy Hungfe726a62018-09-27 15:17:25 -07003555 // Miscellaneous track cleanup when removed from the active list,
3556 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003557#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003558 for (const auto& track : tracksToRemove) {
3559 if (track->isExternalTrack()) {
3560 // to track the speaker usage
3561 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003562 }
3563 }
Andy Hungfe726a62018-09-27 15:17:25 -07003564#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003565}
3566
Andy Hungee58e4a2023-07-07 13:47:37 -07003567void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003568{
Atneya Nair967c85f2024-10-27 16:09:50 -07003569 if (property_get_bool("ro.audio.silent", false)) {
3570 ALOGW("ro.audio.silent is now ignored");
Eric Laurent81784c32012-11-19 14:55:58 -08003571 }
3572}
3573
3574// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003575ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003576{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003577 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003578 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003579 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003580 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003581
3582 // If an NBAIO sink is present, use it to write the normal mixer's submix
3583 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003584
Andy Hung010a1a12014-03-13 13:57:33 -07003585 const size_t count = mBytesRemaining / mFrameSize;
3586
Simon Wilson2d590962012-11-29 15:18:50 -08003587 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003588 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003589 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003590 if (screenState != mScreenState) {
3591 mScreenState = screenState;
3592 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3593 if (pipe != NULL) {
3594 pipe->setAvgFrames((mScreenState & 1) ?
3595 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3596 }
3597 }
Andy Hung010a1a12014-03-13 13:57:33 -07003598 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003599 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003600
Eric Laurent81784c32012-11-19 14:55:58 -08003601 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003602 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003603
Andy Hung8946a282018-04-19 20:04:56 -07003604#ifdef TEE_SINK
3605 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3606#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003607 } else {
3608 bytesWritten = framesWritten;
3609 }
3610 // otherwise use the HAL / AudioStreamOut directly
3611 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003612 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003613
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003615 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3616 mWriteAckSequence += 2;
3617 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003619 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003620 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003621 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003622 // FIXME We should have an implementation of timestamps for direct output threads.
3623 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003624 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003625 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003626
Eric Laurentbfb1b832013-01-07 09:53:42 -08003627 if (mUseAsyncWrite &&
3628 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3629 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003630 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003631 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003632 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003633 }
Eric Laurent81784c32012-11-19 14:55:58 -08003634 }
3635
Eric Laurent81784c32012-11-19 14:55:58 -08003636 mNumWrites++;
3637 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003638 if (mStandby) {
3639 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003640 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003641 mStandby = false;
3642 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003643 return bytesWritten;
3644}
3645
Andy Hungc5007f82023-08-29 14:26:09 -07003646// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003647void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003648 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003649{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003650 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003651 if (outputSink != nullptr) {
3652 outputSink->startMelComputation(processor);
3653 }
Vlad Popab042ee62022-10-20 18:05:00 +02003654}
3655
Andy Hungc5007f82023-08-29 14:26:09 -07003656// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003657void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003658{
3659 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003660 if (outputSink != nullptr) {
3661 outputSink->stopMelComputation();
3662 }
Vlad Popab042ee62022-10-20 18:05:00 +02003663}
3664
Andy Hungee58e4a2023-07-07 13:47:37 -07003665void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003666{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003667 bool supportsDrain = false;
3668 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003669 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3670 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003671 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3672 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003673 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003674 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003675 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003676 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003677 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003678 }
3679}
3680
Andy Hungee58e4a2023-07-07 13:47:37 -07003681void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003682{
Eric Laurent275e8e92014-11-30 15:14:47 -08003683 {
Andy Hung972bec12023-08-31 16:13:39 -07003684 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003685 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003686 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003687 track->invalidate();
3688 }
Andy Hungdae27702016-10-31 14:01:16 -07003689 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3690 // After we exit there are no more track changes sent to BatteryNotifier
3691 // because that requires an active threadLoop.
3692 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3693 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003694 }
Eric Laurent81784c32012-11-19 14:55:58 -08003695}
3696
3697/*
3698The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003699 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003700 - mActiveSleepTimeUs from activeSleepTimeUs()
3701 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003702 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3703 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003704 - maxPeriod from frame count and sample rate (MIXER only)
3705
3706The parameters that affect these derived values are:
3707 - frame count
3708 - frame size
3709 - sample rate
3710 - device type: A2DP or not
3711 - device latency
3712 - format: PCM or not
3713 - active sleep time
3714 - idle sleep time
3715*/
3716
Andy Hungee58e4a2023-07-07 13:47:37 -07003717void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003718{
Andy Hung25c2dac2014-02-27 14:56:00 -08003719 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003720 mActiveSleepTimeUs = activeSleepTimeUs();
3721 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003722
Andy Hung8fe87eb2023-07-20 21:31:38 -07003723 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003724
Eric Laurent42537be2016-01-08 17:16:42 -08003725 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3726 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003727 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003728 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3729 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3730 }
3731 }
Eric Laurent81784c32012-11-19 14:55:58 -08003732}
3733
Andy Hungee58e4a2023-07-07 13:47:37 -07003734bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003735{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003736 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003737 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003738 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003739 size_t size = mTracks.size();
3740 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003741 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003742 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003743 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003744 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003745 }
3746 }
Eric Laurent13084622016-05-17 10:51:49 -07003747 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003748}
3749
Andy Hungee58e4a2023-07-07 13:47:37 -07003750void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003751{
Andy Hung972bec12023-08-31 16:13:39 -07003752 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003753 invalidateTracks_l(streamType);
3754}
3755
Andy Hungee58e4a2023-07-07 13:47:37 -07003756void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003757 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003758 invalidateTracks_l(portIds);
3759}
3760
Andy Hungee58e4a2023-07-07 13:47:37 -07003761bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003762 bool trackMatch = false;
3763 const size_t size = mTracks.size();
3764 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003765 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003766 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3767 t->invalidate();
3768 portIds.erase(t->portId());
3769 trackMatch = true;
3770 }
3771 if (portIds.empty()) {
3772 break;
3773 }
3774 }
3775 return trackMatch;
3776}
3777
jiabinf042b9b2021-05-07 23:46:28 +00003778// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003779IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003780 audio_port_handle_t trackPortId) {
3781 for (size_t i = 0; i < mTracks.size(); i++) {
3782 if (mTracks[i]->portId() == trackPortId) {
3783 return mTracks[i].get();
3784 }
3785 }
3786 return nullptr;
3787}
3788
Andy Hungee58e4a2023-07-07 13:47:37 -07003789status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003790{
Glenn Kastend848eb42016-03-08 13:42:11 -08003791 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003792 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003793 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003794
Andy Hungd3639922022-04-28 18:00:49 -07003795 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003796 if (!audio_is_global_session(session)) {
3797 // player sessions on a spatializer output will use a dedicated input buffer and
3798 // will either output multi channel to mEffectBuffer if the track is spatilaized
3799 // or stereo to mPostSpatializerBuffer if not spatialized.
3800 uint32_t channelMask;
3801 bool isSessionSpatialized =
3802 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3803 if (isSessionSpatialized) {
3804 channelMask = mMixerChannelMask;
3805 } else {
3806 channelMask = mChannelMask;
3807 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003808 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003809 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003810 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003811 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003812 &halInBuffer);
3813 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003814
Andy Hung583043b2023-07-17 17:05:00 -07003815 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003816 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3817 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3818 &halOutBuffer);
3819 if (result != OK) return result;
3820
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003821 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003822
Mikhail Naganov022b9952017-01-04 16:36:51 -08003823 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3824 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003825 } else {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003826 status_t result = INVALID_OPERATION;
3827 // Buffer configuration for global sessions on a SPATIALIZER thread:
3828 // - AUDIO_SESSION_OUTPUT_MIX session uses the mEffectBuffer as input and output buffer
3829 // - AUDIO_SESSION_OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3830 // mPostSpatializerBuffer as output buffer
3831 // - AUDIO_SESSION_DEVICE session uses the mPostSpatializerBuffer as input and output
3832 // buffer
3833 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_OUTPUT_STAGE) {
3834 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3835 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3836 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003837
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003838 if (session == AUDIO_SESSION_OUTPUT_MIX) {
3839 halOutBuffer = halInBuffer;
3840 }
3841 }
3842
3843 if (session == AUDIO_SESSION_OUTPUT_STAGE || session == AUDIO_SESSION_DEVICE) {
3844 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3845 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3846 if (result != OK) return result;
3847
3848 if (session == AUDIO_SESSION_DEVICE) {
3849 halInBuffer = halOutBuffer;
3850 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003851 }
3852 }
3853 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003854 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003855 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3856 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3857 &halInBuffer);
3858 if (result != OK) return result;
3859 halOutBuffer = halInBuffer;
3860 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3861 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003862 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003863 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003864 // Only one effect chain can be present in direct output thread and it uses
3865 // the sink buffer as input
3866 if (mType != DIRECT) {
3867 size_t numSamples = mNormalFrameCount
3868 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3869 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003870 const status_t allocateStatus =
3871 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003872 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003873 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003874 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003875
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003876 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003877 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3878 buffer, session);
3879 }
3880 }
3881 }
3882
3883 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003884 // Attach all tracks with same session ID to this chain.
3885 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003886 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003887 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003888 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3889 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003890 track->setMainBuffer(buffer);
3891 chain->incTrackCnt();
3892 }
3893 }
3894
3895 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003896 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003897 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003898 ALOGV("addEffectChain_l() activating track %p on session %d",
3899 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003900 chain->incActiveTrackCnt();
3901 }
3902 }
3903 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003904
Eric Laurentaaa44472014-09-12 17:41:50 -07003905 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003906 chain->setInBuffer(halInBuffer);
3907 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003908 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3909 // chains list in order to be processed last as it contains output device effects.
3910 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3911 // processing effects specific to an output stream before effects applied to all streams
3912 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003913 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3914 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003915 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003916 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003917 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003918 // Effect chain for other sessions are inserted at beginning of effect
3919 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003920 // sessions is not important.
3921 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003922 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3923 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003924 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003925 size_t size = mEffectChains.size();
3926 size_t i = 0;
3927 for (i = 0; i < size; i++) {
3928 if (mEffectChains[i]->sessionId() < session) {
3929 break;
3930 }
3931 }
3932 mEffectChains.insertAt(chain, i);
3933 checkSuspendOnAddEffectChain_l(chain);
3934
3935 return NO_ERROR;
3936}
3937
Andy Hungee58e4a2023-07-07 13:47:37 -07003938size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003939{
Glenn Kastend848eb42016-03-08 13:42:11 -08003940 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003941
3942 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3943
3944 for (size_t i = 0; i < mEffectChains.size(); i++) {
3945 if (chain == mEffectChains[i]) {
3946 mEffectChains.removeAt(i);
3947 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003948 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003949 if (session == track->sessionId()) {
3950 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3951 chain.get(), session);
3952 chain->decActiveTrackCnt();
3953 }
3954 }
3955
3956 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003957 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003958 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003959 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003960 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003961 chain->decTrackCnt();
3962 }
3963 }
3964 break;
3965 }
3966 }
3967 return mEffectChains.size();
3968}
3969
Andy Hungee58e4a2023-07-07 13:47:37 -07003970status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003971 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003972{
Andy Hung972bec12023-08-31 16:13:39 -07003973 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003974 return attachAuxEffect_l(track, EffectId);
3975}
3976
Andy Hungee58e4a2023-07-07 13:47:37 -07003977status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003978 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003979{
3980 status_t status = NO_ERROR;
3981
3982 if (EffectId == 0) {
3983 track->setAuxBuffer(0, NULL);
3984 } else {
3985 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003986 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003987 if (effect != 0) {
3988 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3989 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3990 } else {
3991 status = INVALID_OPERATION;
3992 }
3993 } else {
3994 status = BAD_VALUE;
3995 }
3996 }
3997 return status;
3998}
3999
Andy Hungee58e4a2023-07-07 13:47:37 -07004000void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08004001{
4002 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004003 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004004 if (track->auxEffectId() == effectId) {
4005 attachAuxEffect_l(track, 0);
4006 }
4007 }
4008}
4009
Andy Hungee58e4a2023-07-07 13:47:37 -07004010bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07004011NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08004012{
Andy Hung78d8d952023-05-30 18:10:23 -07004013 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08004014
Andy Hung077d62e2023-10-03 10:49:34 -07004015 if (mType == SPATIALIZER) {
4016 const pid_t tid = getTid();
4017 if (tid == -1) { // odd: we are here, we must be a running thread.
4018 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
4019 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00004020 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4021 if (priorityBoost > 0) {
4022 stream()->setHalThreadPriority(priorityBoost);
4023 }
Andy Hung077d62e2023-10-03 10:49:34 -07004024 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004025 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4026 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4027 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4028 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4029 // only on ARC.
4030 const pid_t tid = getTid();
4031 if (tid == -1) {
4032 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4033 } else {
4034 const status_t status = requestPriority(getpid(),
4035 tid,
4036 kPriorityPlaybackThreadArc,
4037 false /* isForApp */,
4038 true /* asynchronous */);
4039 if (status != OK) {
4040 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4041 status);
4042 } else {
4043 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4044 }
4045 }
Andy Hung077d62e2023-10-03 10:49:34 -07004046 }
4047
Andy Hung8d31fd22023-06-26 19:20:57 -07004048 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004049
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004050 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004051 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004052
4053 // MIXER
4054 nsecs_t lastWarning = 0;
4055
4056 // DUPLICATING
4057 // FIXME could this be made local to while loop?
4058 writeFrames = 0;
4059
Andy Hung3f2cee62024-09-17 14:17:15 -07004060 {
4061 audio_utils::lock_guard l(mutex());
4062
4063 cacheParameters_l();
4064 checkSilentMode_l();
4065 }
4066
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004067 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004068
Andy Hungd3639922022-04-28 18:00:49 -07004069 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004070 sleepTimeShift = 0;
4071 }
4072
4073 CpuStats cpuStats;
4074 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4075
4076 acquireWakeLock();
4077
Glenn Kasteneef598c2017-04-03 14:41:13 -07004078 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4079 // thread associated with this PlaybackThread.
4080 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4081 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004082 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4083 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004084 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004085 const char *logString = NULL;
4086
rago1bb90822017-05-02 18:31:48 -07004087 // Estimated time for next buffer to be written to hal. This is used only on
4088 // suspended mode (for now) to help schedule the wait time until next iteration.
4089 nsecs_t timeLoopNextNs = 0;
4090
Andy Hung2dbffc22018-08-08 18:50:41 -07004091 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004092
Eric Laurentb3f315a2021-07-13 15:09:05 +02004093 sendCheckOutputStageEffectsEvent();
4094
Andy Hung446f4df2019-02-21 12:26:41 -08004095 // loopCount is used for statistics and diagnostics.
4096 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004097 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004098 // Log merge requests are performed during AudioFlinger binder transactions, but
4099 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004100 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004101
Eric Laurent81784c32012-11-19 14:55:58 -08004102 cpuStats.sample(myName);
4103
Andy Hung116bc262023-06-20 18:56:17 -07004104 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004105 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004106 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004107 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004108
Andy Hung2dbffc22018-08-08 18:50:41 -07004109 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4110 //
Andy Hungc5007f82023-08-29 14:26:09 -07004111 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004112 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004113 // Here, we try for the AF lock, but do not block on it as the latency
4114 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004115 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004116 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004117 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004118 status_t status = INVALID_OPERATION;
4119 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004120 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004121 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004122 && swPatches.size() > 0) {
4123 status = swPatches[0].getLatencyMs_l(&latencyMs);
4124 downstreamPatchHandle = swPatches[0].getPatchHandle();
4125 }
4126 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004127 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004128 lastDownstreamPatchHandle = downstreamPatchHandle;
4129 }
4130 if (status == OK) {
4131 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004132 // latency of 5 seconds).
4133 const double minLatency = 0., maxLatency = 5000.;
4134 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004135 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004136 } else {
4137 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004138 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004139 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004140 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004141 }
Andy Hung583043b2023-07-17 17:05:00 -07004142 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004143 }
4144 } else {
4145 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4146 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004147 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004148 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4149 }
4150 }
4151
Eric Laurentb3f315a2021-07-13 15:09:05 +02004152 if (mCheckOutputStageEffects.exchange(false)) {
4153 checkOutputStageEffects();
4154 }
4155
Vlad Popa7e81cea2023-01-19 16:34:16 +01004156 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004157 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004158
Andy Hungc5007f82023-08-29 14:26:09 -07004159 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004160
Eric Laurent021cf962014-05-13 10:18:14 -07004161 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004162 if (mCheckOutputStageEffects.load()) {
4163 continue;
4164 }
Eric Laurent10351942014-05-08 18:49:52 -07004165
Andy Hungc5007f82023-08-29 14:26:09 -07004166 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004167 if (logString != NULL) {
4168 mNBLogWriter->logTimestamp();
4169 mNBLogWriter->log(logString);
4170 logString = NULL;
4171 }
4172
Dean Wheatley12473e92021-03-18 23:00:55 +11004173 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004174
Eric Laurent81784c32012-11-19 14:55:58 -08004175 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004176 if (mSignalPending) {
4177 // A signal was raised while we were unlocked
4178 mSignalPending = false;
4179 } else if (waitingAsyncCallback_l()) {
4180 if (exitPending()) {
4181 break;
4182 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004183 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004184 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004185 releaseWakeLock_l();
4186 released = true;
4187 }
Andy Hung10cbff12017-02-21 17:30:14 -08004188
4189 const int64_t waitNs = computeWaitTimeNs_l();
4190 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004191 std::cv_status cvstatus =
4192 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4193 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004194 mSignalPending = true; // if timeout recheck everything
4195 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004196 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004197 if (released) {
4198 acquireWakeLock_l();
4199 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004200 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4201 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004202
4203 continue;
4204 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004205 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004206 isSuspended()) {
4207 // put audio hardware into standby after short delay
4208 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004209
4210 threadLoop_standby();
4211
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004212 // This is where we go into standby
4213 if (!mStandby) {
4214 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004215 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004216 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004217 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004218 }
Andy Hungd0979812019-02-21 15:51:44 -08004219 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004220 }
4221
Eric Tan39ec8d62018-07-24 09:49:29 -07004222 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004223 // we're about to wait, flush the binder command buffer
4224 IPCThreadState::self()->flushCommands();
4225
4226 clearOutputTracks();
4227
4228 if (exitPending()) {
4229 break;
4230 }
4231
4232 releaseWakeLock_l();
4233 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004234 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004235 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004236 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004237 acquireWakeLock_l();
4238
4239 mMixerStatus = MIXER_IDLE;
4240 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4241 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004242 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004243 checkSilentMode_l();
4244
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004245 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4246 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004247 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004248 sleepTimeShift = 0;
4249 }
4250
4251 continue;
4252 }
4253 }
Eric Laurent81784c32012-11-19 14:55:58 -08004254 // mMixerStatusIgnoringFastTracks is also updated internally
4255 mMixerStatus = prepareTracks_l(&tracksToRemove);
4256
Andy Hungab65b182023-09-06 19:41:47 -07004257 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004258
Vlad Popa7e81cea2023-01-19 16:34:16 +01004259 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004260
Andy Hungf302e812024-01-26 11:55:15 -08004261 // Acquire a local copy of active tracks with lock (release w/o lock).
4262 //
4263 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4264 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4265 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4266 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4267
4268 setHalLatencyMode_l();
4269
4270 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4271 // so this is done before we lock our effect chains.
4272 for (const auto& track : mActiveTracks) {
4273 track->updateTeePatches_l();
4274 }
4275
Andy Hungf767de02024-10-30 19:47:50 -07004276 // check if traces have been enabled.
4277 bool atraceEnabled = ATRACE_ENABLED();
4278 if (atraceEnabled != mAtraceEnabled) [[unlikely]] {
4279 mAtraceEnabled = atraceEnabled;
4280 if (atraceEnabled) {
4281 const auto devices = patchSinksToString(&mPatch);
4282 for (const auto& track : activeTracks) {
4283 track->logRefreshInterval(devices);
4284 }
4285 }
4286 }
Andy Hungf302e812024-01-26 11:55:15 -08004287 // signal actual start of output stream when the render position reported by
4288 // the kernel starts moving.
4289 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4290 && (mKernelPositionOnStandby
4291 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4292 mHalStarted = true;
4293 mWaitHalStartCV.notify_all();
4294 }
4295
Eric Laurent81784c32012-11-19 14:55:58 -08004296 // prevent any changes in effect chain list and in each effect chain
4297 // during mixing and effect process as the audio buffers could be deleted
4298 // or modified if an effect is created or deleted
4299 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004300
4301 // Determine which session to pick up haptic data.
4302 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004303 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004304 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004305 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004306 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004307 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004308 if (effectChain != nullptr
4309 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004310 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004311 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004312 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004313 break;
4314 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004315 if (activeHapticSessionId == AUDIO_SESSION_NONE
4316 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004317 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004318 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004319 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004320 }
4321 }
4322 }
Andy Hungc5007f82023-08-29 14:26:09 -07004323 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004324
Eric Laurentbfb1b832013-01-07 09:53:42 -08004325 if (mBytesRemaining == 0) {
4326 mCurrentWriteLength = 0;
4327 if (mMixerStatus == MIXER_TRACKS_READY) {
4328 // threadLoop_mix() sets mCurrentWriteLength
4329 threadLoop_mix();
4330 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4331 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004332 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004333 // must be written to HAL
4334 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004335 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004336 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004337
4338 // Tally underrun frames as we are inserting 0s here.
4339 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004340 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004341 && !track->isStopped()
4342 && !track->isPaused()
4343 && !track->isTerminated()) {
4344 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4345 __func__, track->id(), track->getTrackStateAsString(),
4346 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004347 track->audioTrackServerProxy()->tallyUnderrunFrames(
4348 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004349 }
4350 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004351 }
4352 }
Andy Hung98ef9782014-03-04 14:46:50 -08004353 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004354 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004355 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004356 // or mSinkBuffer (if there are no effects and there is no data already copied to
4357 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004358 //
4359 // This is done pre-effects computation; if effects change to
4360 // support higher precision, this needs to move.
4361 //
4362 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004363 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004364 uint32_t mixerChannelCount = mEffectBufferValid ?
4365 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004366 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004367 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4368 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4369
David Li88ee0902022-06-22 10:01:21 +08004370 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4371 // do these processes after effects are applied.
4372 if (!mEffectBufferValid) {
4373 // mono blend occurs for mixer threads only (not direct or offloaded)
4374 // and is handled here if we're going directly to the sink.
4375 if (requireMonoBlend()) {
4376 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4377 mNormalFrameCount, true /*limit*/);
4378 }
Andy Hung2ddee192015-12-18 17:34:44 -08004379
David Li88ee0902022-06-22 10:01:21 +08004380 if (!hasFastMixer()) {
4381 // Balance must take effect after mono conversion.
4382 // We do it here if there is no FastMixer.
4383 // mBalance detects zero balance within the class for speed
4384 // (not needed here).
4385 mBalance.setBalance(mMasterBalance.load());
4386 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4387 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004388 }
4389
Andy Hung98ef9782014-03-04 14:46:50 -08004390 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004391 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004392
4393 // If we're going directly to the sink and there are haptic channels,
4394 // we should adjust channels as the sample data is partially interleaved
4395 // in this case.
4396 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4397 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4398 mChannelCount + mHapticChannelCount,
4399 audio_bytes_per_sample(format),
4400 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4401 }
Andy Hung98ef9782014-03-04 14:46:50 -08004402 }
4403
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 mBytesRemaining = mCurrentWriteLength;
4405 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004406 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4407 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4408 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4409 mBytesWritten += mBytesRemaining;
4410 mFramesWritten += framesRemaining;
4411 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004412 mBytesRemaining = 0;
4413 }
Eric Laurent81784c32012-11-19 14:55:58 -08004414
Eric Laurentbfb1b832013-01-07 09:53:42 -08004415 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004416 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004417 for (size_t i = 0; i < effectChains.size(); i ++) {
4418 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004419 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004420 if (activeHapticSessionId != AUDIO_SESSION_NONE
4421 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004422 // Haptic data is active in this case, copy it directly from
4423 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004424 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4425 audio_channel_count_from_out_mask(mMixerChannelMask) :
4426 mChannelCount;
4427 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4428 hapticSessionChannelCount = mChannelCount;
4429 }
4430
jiabin47affe52019-04-04 18:02:07 -07004431 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004432 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004433 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004434 memcpy_by_audio_format(
4435 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004436 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004437 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004438 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004439 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004440 }
Eric Laurent81784c32012-11-19 14:55:58 -08004441 }
4442 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004443 // Process effect chains for offloaded thread even if no audio
4444 // was read from audio track: process only updates effect state
4445 // and thus does have to be synchronized with audio writes but may have
4446 // to be called while waiting for async write callback
4447 if (mType == OFFLOAD) {
4448 for (size_t i = 0; i < effectChains.size(); i ++) {
4449 effectChains[i]->process_l();
4450 }
4451 }
Eric Laurent81784c32012-11-19 14:55:58 -08004452
Andy Hung98ef9782014-03-04 14:46:50 -08004453 // Only if the Effects buffer is enabled and there is data in the
4454 // Effects buffer (buffer valid), we need to
4455 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004456 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004457 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004458 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004459 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004460 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004461 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004462 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004463 }
4464
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004465 if (!hasFastMixer()) {
4466 // Balance must take effect after mono conversion.
4467 // We do it here if there is no FastMixer.
4468 // mBalance detects zero balance within the class for speed (not needed here).
4469 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004470 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004471 }
4472
Eric Laurentb62d0362021-10-26 17:40:18 +02004473 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4474 // mPostSpatializerBuffer if the haptics track is spatialized.
4475 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4476 // For other thread types, the haptics channels are already in mEffectBuffer.
4477 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4478 const size_t srcBufferSize = mNormalFrameCount *
4479 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4480 mEffectBufferFormat);
4481 const size_t dstBufferSize = mNormalFrameCount
4482 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4483
4484 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4485 mEffectBufferFormat,
4486 (uint8_t*)mEffectBuffer + srcBufferSize,
4487 mEffectBufferFormat,
4488 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004489 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004490 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4491 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4492 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4493 // Clamp PCM float values more than this distance from 0 to insulate
4494 // a HAL which doesn't handle NaN correctly.
4495 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4496 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4497 static_cast<const float*>(effectBuffer),
4498 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4499 } else {
4500 memcpy_by_audio_format(mSinkBuffer, mFormat,
4501 effectBuffer, mEffectBufferFormat, framesToCopy);
4502 }
jiabin245cdd92018-12-07 17:55:15 -08004503 // The sample data is partially interleaved when haptic channels exist,
4504 // we need to adjust channels here.
4505 if (mHapticChannelCount > 0) {
4506 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4507 mChannelCount + mHapticChannelCount,
4508 audio_bytes_per_sample(mFormat),
4509 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4510 }
Andy Hung98ef9782014-03-04 14:46:50 -08004511 }
4512
Eric Laurent81784c32012-11-19 14:55:58 -08004513 // enable changes in effect chain
4514 unlockEffectChains(effectChains);
4515
Vlad Popafce10862023-02-03 10:37:07 +01004516 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004517 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004518 metadataUpdate.playbackMetadataUpdate);
4519 }
4520
Eric Laurentbfb1b832013-01-07 09:53:42 -08004521 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004522 // mSleepTimeUs == 0 means we must write to audio hardware
4523 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004524 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004525 // writePeriodNs is updated >= 0 when ret > 0.
4526 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004527 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004528 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004529 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004530 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004531 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004532 if (ret < 0) {
4533 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004534 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004535 mBytesWritten += ret;
4536 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004537 const int64_t frames = ret / mFrameSize;
4538 mFramesWritten += frames;
4539
4540 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4541 // process information relating to write time.
4542 if (audio_has_proportional_frames(mFormat)) {
4543 // we are in a continuous mixing cycle
4544 if (mMixerStatus == MIXER_TRACKS_READY &&
4545 loopCount == lastLoopCountWritten + 1) {
4546
4547 const double jitterMs =
4548 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4549 {frames, writePeriodNs},
4550 {0, 0} /* lastTimestamp */, mSampleRate);
4551 const double processMs =
4552 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4553
Andy Hung972bec12023-08-31 16:13:39 -07004554 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004555 mIoJitterMs.add(jitterMs);
4556 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004557
4558 if (mPipeSink.get() != nullptr) {
4559 // Using the Monopipe availableToWrite, we estimate the current
4560 // buffer size.
4561 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4562 const ssize_t
4563 availableToWrite = mPipeSink->availableToWrite();
4564 const size_t pipeFrames = monoPipe->maxFrames();
4565 const size_t
4566 remainingFrames = pipeFrames - max(availableToWrite, 0);
4567 mMonopipePipeDepthStats.add(remainingFrames);
4568 }
Andy Hung446f4df2019-02-21 12:26:41 -08004569 }
4570
4571 // write blocked detection
4572 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004573 if ((mType == MIXER || mType == SPATIALIZER)
4574 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004575 mNumDelayedWrites++;
4576 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4577 ATRACE_NAME("underrun");
4578 ALOGW("write blocked for %lld msecs, "
4579 "%d delayed writes, thread %d",
4580 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4581 mNumDelayedWrites, mId);
4582 lastWarning = lastIoEndNs;
4583 }
4584 }
4585 }
4586 // update timing info.
4587 mLastIoBeginNs = lastIoBeginNs;
4588 mLastIoEndNs = lastIoEndNs;
4589 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004590 }
4591 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4592 (mMixerStatus == MIXER_DRAIN_ALL)) {
4593 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004594 }
Andy Hungd3639922022-04-28 18:00:49 -07004595 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004596
4597 if (mThreadThrottle
4598 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004599 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004600 // Limit MixerThread data processing to no more than twice the
4601 // expected processing rate.
4602 //
4603 // This helps prevent underruns with NuPlayer and other applications
4604 // which may set up buffers that are close to the minimum size, or use
4605 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4606 //
4607 // The throttle smooths out sudden large data drains from the device,
4608 // e.g. when it comes out of standby, which often causes problems with
4609 // (1) mixer threads without a fast mixer (which has its own warm-up)
4610 // (2) minimum buffer sized tracks (even if the track is full,
4611 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004612 //
4613 // Total time spent in last processing cycle equals time spent in
4614 // 1. threadLoop_write, as well as time spent in
4615 // 2. threadLoop_mix (significant for heavy mixing, especially
4616 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004617
Andy Hung446f4df2019-02-21 12:26:41 -08004618 // it's OK if deltaMs is an overestimate.
4619
4620 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004621
Ivan Lozanoea04d392017-11-07 14:37:07 -08004622 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004623 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004624 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004625
Andy Hung08fb1742015-05-31 23:22:10 -07004626 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004627 // notify of throttle start on verbose log
4628 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4629 "mixer(%p) throttle begin:"
4630 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004631 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004632 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004633 // Throttle must be attributed to the previous mixer loop's write time
4634 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004635 // This also ensures proper timing statistics.
4636 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004637 } else {
4638 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4639 if (diff > 0) {
4640 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004641 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004642 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004643 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004644 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004645 outDeviceTypes_l(),
4646 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004647 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004648 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4649 }
Andy Hung08fb1742015-05-31 23:22:10 -07004650 }
4651 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004652 }
Eric Laurent81784c32012-11-19 14:55:58 -08004653
Eric Laurentbfb1b832013-01-07 09:53:42 -08004654 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004655 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004656 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004657 // suspended requires accurate metering of sleep time.
4658 if (isSuspended()) {
4659 // advance by expected sleepTime
4660 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4661 const nsecs_t nowNs = systemTime();
4662
4663 // compute expected next time vs current time.
4664 // (negative deltas are treated as delays).
4665 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4666 if (deltaNs < -kMaxNextBufferDelayNs) {
4667 // Delays longer than the max allowed trigger a reset.
4668 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4669 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4670 timeLoopNextNs = nowNs + deltaNs;
4671 } else if (deltaNs < 0) {
4672 // Delays within the max delay allowed: zero the delta/sleepTime
4673 // to help the system catch up in the next iteration(s)
4674 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4675 deltaNs = 0;
4676 }
4677 // update sleep time (which is >= 0)
4678 mSleepTimeUs = deltaNs / 1000;
4679 }
Eric Laurente93cc032016-05-05 10:15:10 -07004680 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004681 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004682 }
Glenn Kastene7754022014-10-31 12:11:26 -07004683 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004684 }
Eric Laurent81784c32012-11-19 14:55:58 -08004685 }
4686
4687 // Finally let go of removed track(s), without the lock held
4688 // since we can't guarantee the destructors won't acquire that
4689 // same lock. This will also mutate and push a new fast mixer state.
4690 threadLoop_removeTracks(tracksToRemove);
4691 tracksToRemove.clear();
4692
4693 // FIXME I don't understand the need for this here;
4694 // it was in the original code but maybe the
4695 // assignment in saveOutputTracks() makes this unnecessary?
4696 clearOutputTracks();
4697
4698 // Effect chains will be actually deleted here if they were removed from
4699 // mEffectChains list during mixing or effects processing
4700 effectChains.clear();
4701
4702 // FIXME Note that the above .clear() is no longer necessary since effectChains
4703 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004704
4705 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004706 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004707 mThreadloopExecutor.process(); // process any remaining deferred actions.
4708 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004709
Eric Laurentbfb1b832013-01-07 09:53:42 -08004710 threadLoop_exit();
4711
Eric Laurentcf817a22014-08-04 20:36:31 -07004712 if (!mStandby) {
4713 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004714 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004715 }
4716
4717 releaseWakeLock();
4718
4719 ALOGV("Thread %p type %d exiting", this, mType);
4720 return false;
4721}
4722
Andy Hungee58e4a2023-07-07 13:47:37 -07004723void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004724{
Dean Wheatley12473e92021-03-18 23:00:55 +11004725 if (mStandby) {
4726 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4727 return;
4728 } else if (mHwPaused) {
4729 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4730 return;
4731 }
4732
4733 // Gather the framesReleased counters for all active tracks,
4734 // and associate with the sink frames written out. We need
4735 // this to convert the sink timestamp to the track timestamp.
4736 bool kernelLocationUpdate = false;
4737 ExtendedTimestamp timestamp; // use private copy to fetch
4738
4739 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4740 // HAL may be draining some small duration buffered data for fade out.
4741 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4742 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4743 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4744 mSampleRate);
4745
Andy Hungab65b182023-09-06 19:41:47 -07004746 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004747 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4748 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4749 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4750 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4751 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4752 = correctedTimestamp.mFrames;
4753 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4754 = correctedTimestamp.mTimeNs;
4755 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4756 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4757 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4758
4759 // Note: Downstream latency only added if timestamp correction enabled.
4760 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4761 const int64_t newPosition =
4762 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4763 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4764 // prevent retrograde
4765 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4766 newPosition,
4767 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4768 - mSuspendedFrames));
4769 }
4770 }
4771
4772 // We always fetch the timestamp here because often the downstream
4773 // sink will block while writing.
4774
4775 // We keep track of the last valid kernel position in case we are in underrun
4776 // and the normal mixer period is the same as the fast mixer period, or there
4777 // is some error from the HAL.
4778 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4779 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4780 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4781 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4782 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4783
4784 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4785 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4786 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4787 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4788 }
4789
4790 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4791 kernelLocationUpdate = true;
4792 } else {
4793 ALOGVV("getTimestamp error - no valid kernel position");
4794 }
4795
4796 // copy over kernel info
4797 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4798 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4799 + mSuspendedFrames; // add frames discarded when suspended
4800 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4801 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4802 } else {
4803 mTimestampVerifier.error();
4804 }
4805
4806 // mFramesWritten for non-offloaded tracks are contiguous
4807 // even after standby() is called. This is useful for the track frame
4808 // to sink frame mapping.
4809 bool serverLocationUpdate = false;
4810 if (mFramesWritten != mLastFramesWritten) {
4811 serverLocationUpdate = true;
4812 mLastFramesWritten = mFramesWritten;
4813 }
4814 // Only update timestamps if there is a meaningful change.
4815 // Either the kernel timestamp must be valid or we have written something.
4816 if (kernelLocationUpdate || serverLocationUpdate) {
4817 if (serverLocationUpdate) {
4818 // use the time before we called the HAL write - it is a bit more accurate
4819 // to when the server last read data than the current time here.
4820 //
4821 // If we haven't written anything, mLastIoBeginNs will be -1
4822 // and we use systemTime().
4823 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4824 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004825 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004826 }
4827
Andy Hung8d31fd22023-06-26 19:20:57 -07004828 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004829 if (!t->isFastTrack()) {
4830 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004831 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004832 mFramesWritten,
4833 mSampleRate,
4834 mTimestamp);
4835 }
4836 }
4837 }
4838
4839 if (audio_has_proportional_frames(mFormat)) {
4840 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4841 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4842 mLatencyMs.add(latencyMs);
4843 }
4844 }
4845#if 0
4846 // logFormat example
4847 if (z % 100 == 0) {
4848 timespec ts;
4849 clock_gettime(CLOCK_MONOTONIC, &ts);
4850 LOGT("This is an integer %d, this is a float %f, this is my "
4851 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4852 LOGT("A deceptive null-terminated string %\0");
4853 }
4854 ++z;
4855#endif
4856}
4857
Andy Hungc5007f82023-08-29 14:26:09 -07004858// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004859void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004860NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004861{
Andy Hung6c498e92023-12-05 17:28:17 -08004862 if (tracksToRemove.empty()) return;
4863
4864 // Block all incoming TrackHandle requests until we are finished with the release.
4865 setThreadBusy_l(true);
4866
Andy Hungfe726a62018-09-27 15:17:25 -07004867 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004868 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004869 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004870 if (chain != 0) {
4871 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4872 __func__, track->id(), chain.get(), track->sessionId());
4873 chain->decActiveTrackCnt();
4874 }
Andy Hung6c498e92023-12-05 17:28:17 -08004875
Andy Hungfe726a62018-09-27 15:17:25 -07004876 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004877 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004878 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004879 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004880 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004881 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004882 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004883 }
Andy Hung6c498e92023-12-05 17:28:17 -08004884 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004885 }
jiabineb3bda02020-06-30 14:07:03 -07004886 if (mHapticChannelCount > 0 &&
4887 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004888 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004889 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004890 // Unlock due to VibratorService will lock for this call and will
4891 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004892 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004893 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004894
4895 // When the track is stop, set the haptic intensity as MUTE
4896 // for the HapticGenerator effect.
4897 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004898 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004899 }
jiabin245cdd92018-12-07 17:55:15 -08004900 }
Andy Hung6c498e92023-12-05 17:28:17 -08004901
4902 // Under lock, the track is removed from the active tracks list.
4903 //
4904 // Once the track is no longer active, the TrackHandle may directly
4905 // modify it as the threadLoop() is no longer responsible for its maintenance.
4906 // Do not modify the track from threadLoop after the mutex is unlocked
4907 // if it is not active.
4908 mActiveTracks.remove(track);
4909
4910 if (track->isTerminated()) {
4911 // remove from our tracks vector
4912 removeTrack_l(track);
4913 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004914 }
Andy Hung6c498e92023-12-05 17:28:17 -08004915
4916 // Allow incoming TrackHandle requests. We still hold the mutex,
4917 // so pending TrackHandle requests will occur after we unlock it.
4918 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004919}
Eric Laurent81784c32012-11-19 14:55:58 -08004920
Andy Hungee58e4a2023-07-07 13:47:37 -07004921status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004922{
4923 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004924 ExtendedTimestamp ets;
4925 status_t status = mNormalSink->getTimestamp(ets);
4926 if (status == NO_ERROR) {
4927 status = ets.getBestTimestamp(&timestamp);
4928 }
4929 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004930 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004931 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004932 collectTimestamps_l();
4933 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4934 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004935 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004936 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4937 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4938 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4939 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4940 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004941 }
4942 return INVALID_OPERATION;
4943}
Eric Laurent1c333e22014-05-20 10:48:17 -07004944
Eric Laurenteab90452019-06-24 15:17:46 -07004945// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4946// still applied by the mixer.
4947// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4948// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4949// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004950status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004951{
4952 status_t result = NO_ERROR;
4953 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4954 if (*volume != mLeftVolFloat) {
4955 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004956 // HAL can return INVALID_OPERATION if operation is not supported.
4957 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004958 "Error when setting output stream volume: %d", result);
4959 if (result == NO_ERROR) {
4960 mLeftVolFloat = *volume;
4961 }
4962 }
4963 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4964 // remove stream volume contribution from software volume.
4965 if (mLeftVolFloat == *volume) {
4966 *volume = 1.0f;
4967 }
4968 }
4969 return result;
4970}
4971
Andy Hungee58e4a2023-07-07 13:47:37 -07004972status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004973 audio_patch_handle_t *handle)
4974{
Andy Hungf60abce2016-08-26 11:37:54 -07004975 status_t status;
4976 if (property_get_bool("af.patch_park", false /* default_value */)) {
4977 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4978 // or if HAL does not properly lock against access.
4979 AutoPark<FastMixer> park(mFastMixer);
4980 status = PlaybackThread::createAudioPatch_l(patch, handle);
4981 } else {
4982 status = PlaybackThread::createAudioPatch_l(patch, handle);
4983 }
Eric Laurentb0463942022-12-20 16:31:10 +01004984
4985 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004986 return status;
4987}
4988
Andy Hungee58e4a2023-07-07 13:47:37 -07004989status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004990 audio_patch_handle_t *handle)
4991{
4992 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004993
4994 // store new device and send to effects
4995 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004996 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004997 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004998 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4999 && !mOutput->audioHwDev->supportsAudioPatches(),
5000 "Enumerated device type(%#x) must not be used "
5001 "as it does not support audio patches",
5002 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07005003 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07005004 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
5005 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07005006 }
5007
François Gaffie0c280aa2018-07-25 10:02:15 +02005008 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07005009#ifdef ADD_BATTERY_DATA
5010 // when changing the audio output device, call addBatteryData to notify
5011 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07005012 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005013 uint32_t params = 0;
5014 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07005015 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005016 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07005017 }
5018
Eric Laurent054d9d32015-04-24 08:48:48 -07005019 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07005020 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005021 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5022 }
5023
5024 if (params != 0) {
5025 addBatteryData(params);
5026 }
5027 }
5028#endif
5029
5030 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08005031 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07005032 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07005033
jiabinc52b1ff2019-10-31 17:20:42 -07005034 // mPatch.num_sinks is not set when the thread is created so that
5035 // the first patch creation triggers an ioConfigChanged callback
5036 bool configChanged = (mPatch.num_sinks == 0) ||
5037 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005038 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005039 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005040 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005041
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005042 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005043 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5044 status = hwDevice->createAudioPatch(patch->num_sources,
5045 patch->sources,
5046 patch->num_sinks,
5047 patch->sinks,
5048 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005049 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005050 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005051 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005052 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005053 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005054
5055 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005056 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005057 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005058 // also dispatch to active AudioTracks for MediaMetrics
5059 for (const auto &track : mActiveTracks) {
5060 track->logEndInterval();
5061 track->logBeginInterval(patchSinksAsString);
5062 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005063
Eric Laurente8726fe2015-06-26 09:39:24 -07005064 if (configChanged) {
5065 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5066 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005067 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005068 mActiveTracks.setHasChanged();
5069
Eric Laurent1c333e22014-05-20 10:48:17 -07005070 return status;
5071}
5072
Andy Hungee58e4a2023-07-07 13:47:37 -07005073status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005074{
Andy Hungf60abce2016-08-26 11:37:54 -07005075 status_t status;
5076 if (property_get_bool("af.patch_park", false /* default_value */)) {
5077 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5078 // or if HAL does not properly lock against access.
5079 AutoPark<FastMixer> park(mFastMixer);
5080 status = PlaybackThread::releaseAudioPatch_l(handle);
5081 } else {
5082 status = PlaybackThread::releaseAudioPatch_l(handle);
5083 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005084 return status;
5085}
5086
Andy Hungee58e4a2023-07-07 13:47:37 -07005087status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005088{
5089 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005090
jiabinc52b1ff2019-10-31 17:20:42 -07005091 mPatch = audio_patch{};
5092 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005093
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005094 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005095 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5096 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005097 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005098 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005099 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005100 // Force meteadata update after a route change
5101 mActiveTracks.setHasChanged();
5102
Eric Laurent1c333e22014-05-20 10:48:17 -07005103 return status;
5104}
5105
Andy Hungee58e4a2023-07-07 13:47:37 -07005106void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005107{
Andy Hung972bec12023-08-31 16:13:39 -07005108 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005109 mTracks.add(track);
5110}
5111
Andy Hungee58e4a2023-07-07 13:47:37 -07005112void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005113{
Andy Hung972bec12023-08-31 16:13:39 -07005114 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005115 destroyTrack_l(track);
5116}
5117
Andy Hungee58e4a2023-07-07 13:47:37 -07005118void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005119{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005120 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005121 config->role = AUDIO_PORT_ROLE_SOURCE;
5122 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5123 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005124 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5125 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5126 config->flags.output = mOutput->flags;
5127 }
Eric Laurent83b88082014-06-20 18:31:16 -07005128}
5129
Atneya Nairaa3afcb2024-10-08 16:36:19 -07005130std::string PlaybackThread::getLocalLogHeader() const {
5131 using namespace std::literals;
5132 static constexpr auto indent = " "
5133 " "sv;
5134 return std::string{indent}.append(IAfTrack::getLogHeader());
5135}
Eric Laurent81784c32012-11-19 14:55:58 -08005136// ----------------------------------------------------------------------------
5137
Andy Hungee58e4a2023-07-07 13:47:37 -07005138/* static */
5139sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005140 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005141 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005142 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005143}
5144
Andy Hung583043b2023-07-17 17:05:00 -07005145MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005146 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005147 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005148 // mAudioMixer below
5149 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005150 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005151 mFastMixerFutex(0),
5152 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005153 // mOutputSink below
5154 // mPipeSink below
5155 // mNormalSink below
5156{
jiabinc52b1ff2019-10-31 17:20:42 -07005157 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005158 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005159 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005160 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5161 mNormalFrameCount);
5162 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5163
Andy Hungfbfc3952015-01-15 13:33:51 -08005164 if (type == DUPLICATING) {
5165 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5166 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5167 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005168 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5169 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005170 return;
5171 }
Eric Laurent81784c32012-11-19 14:55:58 -08005172 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005173 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005174 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005175 const NBAIO_Format offers[1] = {Format_from_SR_C(
5176 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005177#if !LOG_NDEBUG
5178 ssize_t index =
5179#else
5180 (void)
5181#endif
5182 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005183 ALOG_ASSERT(index == 0);
5184
5185 // initialize fast mixer depending on configuration
5186 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005187 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005188 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005189 } else {
5190 switch (kUseFastMixer) {
5191 case FastMixer_Never:
5192 initFastMixer = false;
5193 break;
5194 case FastMixer_Always:
5195 initFastMixer = true;
5196 break;
5197 case FastMixer_Static:
5198 case FastMixer_Dynamic:
Henrik Tillman470b3992024-10-08 12:49:28 +02005199 if (mType == MIXER && (output->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) {
5200 /* Do not init fast mixer on deep buffer, warn if buffers are confed too small */
5201 initFastMixer = false;
5202 ALOGW_IF(mFrameCount * 1000 / mSampleRate < kMinNormalSinkBufferSizeMs,
5203 "HAL DEEP BUFFER Buffer (%zu ms) is smaller than set minimal buffer "
5204 "(%u ms), seems like a configuration error",
5205 mFrameCount * 1000 / mSampleRate, kMinNormalSinkBufferSizeMs);
5206 } else {
5207 initFastMixer = mFrameCount < mNormalFrameCount;
5208 }
Eric Laurentb62d0362021-10-26 17:40:18 +02005209 break;
5210 }
5211 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5212 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5213 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005214 }
5215 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005216 audio_format_t fastMixerFormat;
5217 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5218 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5219 } else {
5220 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5221 }
5222 if (mFormat != fastMixerFormat) {
5223 // change our Sink format to accept our intermediate precision
5224 mFormat = fastMixerFormat;
5225 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005226 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005227 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5228 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5229 }
Eric Laurent81784c32012-11-19 14:55:58 -08005230
5231 // create a MonoPipe to connect our submix to FastMixer
5232 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005233
Andy Hung1258c1a2014-05-23 21:22:17 -07005234 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005235 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005236 format.mFormat = fastMixerFormat;
5237 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5238
Eric Laurent81784c32012-11-19 14:55:58 -08005239 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5240 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5241 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5242 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005243 const NBAIO_Format offersFast[1] = {format};
5244 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005245#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005246 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005247#else
5248 (void)
5249#endif
Andy Hung920f6572022-10-06 12:09:49 -07005250 monoPipe->negotiate(offersFast, std::size(offersFast),
5251 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005252 ALOG_ASSERT(index == 0);
5253 monoPipe->setAvgFrames((mScreenState & 1) ?
5254 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5255 mPipeSink = monoPipe;
5256
Eric Laurent81784c32012-11-19 14:55:58 -08005257 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005258 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005259 FastMixerStateQueue *sq = mFastMixer->sq();
5260#ifdef STATE_QUEUE_DUMP
5261 sq->setObserverDump(&mStateQueueObserverDump);
5262 sq->setMutatorDump(&mStateQueueMutatorDump);
5263#endif
5264 FastMixerState *state = sq->begin();
5265 FastTrack *fastTrack = &state->mFastTracks[0];
5266 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5267 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5268 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005269 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5270 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5271 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005272 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005273 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Lais Andradee8995e92024-07-24 15:00:38 +01005274 fastTrack->mHapticScale = os::HapticScale::none();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005275 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005276 fastTrack->mGeneration++;
Andy Hungf767de02024-10-30 19:47:50 -07005277 snprintf(fastTrack->mTraceName, sizeof(fastTrack->mTraceName),
5278 "%s.0.0.%d", AUDIO_TRACE_PREFIX_AUDIO_TRACK_FRDY, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005279 state->mFastTracksGen++;
5280 state->mTrackMask = 1;
5281 // fast mixer will use the HAL output sink
5282 state->mOutputSink = mOutputSink.get();
5283 state->mOutputSinkGen++;
5284 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005285 // specify sink channel mask when haptic channel mask present as it can not
5286 // be calculated directly from channel count
5287 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005288 ? AUDIO_CHANNEL_NONE
5289 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005290 state->mCommand = FastMixerState::COLD_IDLE;
5291 // already done in constructor initialization list
5292 //mFastMixerFutex = 0;
5293 state->mColdFutexAddr = &mFastMixerFutex;
5294 state->mColdGen++;
5295 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005296 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005297 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005298 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07005299 {
5300 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastMixer->getTid());
5301 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5302 }
Eric Laurent81784c32012-11-19 14:55:58 -08005303
Eric Tan0513b5d2018-09-17 10:32:48 -07005304 NBLog::thread_info_t info;
5305 info.id = mId;
5306 info.type = NBLog::FASTMIXER;
5307 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5308
Eric Laurent81784c32012-11-19 14:55:58 -08005309 // start the fast mixer
5310 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5311 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005312 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005313 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005314
5315#ifdef AUDIO_WATCHDOG
5316 // create and start the watchdog
5317 mAudioWatchdog = new AudioWatchdog();
5318 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5319 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5320 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005321 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005322#endif
Andy Hung8946a282018-04-19 20:04:56 -07005323 } else {
5324#ifdef TEE_SINK
5325 // Only use the MixerThread tee if there is no FastMixer.
5326 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5327 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5328#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005329 }
5330
5331 switch (kUseFastMixer) {
5332 case FastMixer_Never:
5333 case FastMixer_Dynamic:
5334 mNormalSink = mOutputSink;
5335 break;
5336 case FastMixer_Always:
5337 mNormalSink = mPipeSink;
5338 break;
5339 case FastMixer_Static:
5340 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5341 break;
5342 }
Andy Hung922617c2024-06-25 17:07:58 -07005343 // setMasterBalance needs to be called after the FastMixer
5344 // (if any) is set up, in order to deliver the balance settings to it.
5345 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005346}
5347
Andy Hungee58e4a2023-07-07 13:47:37 -07005348MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005349{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005350 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005351 FastMixerStateQueue *sq = mFastMixer->sq();
5352 FastMixerState *state = sq->begin();
5353 if (state->mCommand == FastMixerState::COLD_IDLE) {
5354 int32_t old = android_atomic_inc(&mFastMixerFutex);
5355 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005356 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005357 }
5358 }
5359 state->mCommand = FastMixerState::EXIT;
5360 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07005361 {
5362 audio_utils::mutex::scoped_join_wait_check queueWaitCheck(mFastMixer->getTid());
5363 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5364 mFastMixer->join();
5365 }
Eric Laurent81784c32012-11-19 14:55:58 -08005366 // Though the fast mixer thread has exited, it's state queue is still valid.
5367 // We'll use that extract the final state which contains one remaining fast track
5368 // corresponding to our sub-mix.
5369 state = sq->begin();
5370 ALOG_ASSERT(state->mTrackMask == 1);
5371 FastTrack *fastTrack = &state->mFastTracks[0];
5372 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5373 delete fastTrack->mBufferProvider;
5374 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005375 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005376#ifdef AUDIO_WATCHDOG
5377 if (mAudioWatchdog != 0) {
5378 mAudioWatchdog->requestExit();
5379 mAudioWatchdog->requestExitAndWait();
5380 mAudioWatchdog.clear();
5381 }
5382#endif
5383 }
Andy Hung583043b2023-07-17 17:05:00 -07005384 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005385 delete mAudioMixer;
5386}
5387
Andy Hungee58e4a2023-07-07 13:47:37 -07005388void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005389 PlaybackThread::onFirstRef();
5390
Andy Hung972bec12023-08-31 16:13:39 -07005391 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005392 if (mOutput != nullptr && mOutput->stream != nullptr) {
5393 status_t status = mOutput->stream->setLatencyModeCallback(this);
5394 if (status != INVALID_OPERATION) {
5395 updateHalSupportedLatencyModes_l();
5396 }
5397 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5398 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5399 mBluetoothLatencyModesEnabled.store(
5400 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5401 }
5402}
Eric Laurent81784c32012-11-19 14:55:58 -08005403
Andy Hungee58e4a2023-07-07 13:47:37 -07005404uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005405{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005406 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005407 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5408 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5409 }
5410 return latency;
5411}
5412
Andy Hungee58e4a2023-07-07 13:47:37 -07005413ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005414{
5415 // FIXME we should only do one push per cycle; confirm this is true
5416 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005417 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005418 FastMixerStateQueue *sq = mFastMixer->sq();
5419 FastMixerState *state = sq->begin();
5420 if (state->mCommand != FastMixerState::MIX_WRITE &&
5421 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5422 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005423
5424 // FIXME workaround for first HAL write being CPU bound on some devices
5425 ATRACE_BEGIN("write");
5426 mOutput->write((char *)mSinkBuffer, 0);
5427 ATRACE_END();
5428
Eric Laurent81784c32012-11-19 14:55:58 -08005429 int32_t old = android_atomic_inc(&mFastMixerFutex);
5430 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005431 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005432 }
5433#ifdef AUDIO_WATCHDOG
5434 if (mAudioWatchdog != 0) {
5435 mAudioWatchdog->resume();
5436 }
5437#endif
5438 }
5439 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005440#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005441 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005442 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005443#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005444 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07005445 {
5446 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastMixer->getTid());
5447 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5448 }
Eric Laurent81784c32012-11-19 14:55:58 -08005449 if (kUseFastMixer == FastMixer_Dynamic) {
5450 mNormalSink = mPipeSink;
5451 }
5452 } else {
5453 sq->end(false /*didModify*/);
5454 }
5455 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005457}
5458
Andy Hungee58e4a2023-07-07 13:47:37 -07005459void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005460{
5461 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005462 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005463 FastMixerStateQueue *sq = mFastMixer->sq();
5464 FastMixerState *state = sq->begin();
5465 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005466 // Report any frames trapped in the Monopipe
5467 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5468 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5469 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5470 "monoPipeWritten:%lld monoPipeLeft:%lld",
5471 (long long)mFramesWritten, (long long)mSuspendedFrames,
5472 (long long)mPipeSink->framesWritten(), pipeFrames);
5473 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5474
Eric Laurent81784c32012-11-19 14:55:58 -08005475 state->mCommand = FastMixerState::COLD_IDLE;
5476 state->mColdFutexAddr = &mFastMixerFutex;
5477 state->mColdGen++;
5478 mFastMixerFutex = 0;
5479 sq->end();
5480 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
Andy Hung82f39d62024-09-30 17:19:14 -07005481 {
5482 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastMixer->getTid());
5483 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5484 }
Eric Laurent81784c32012-11-19 14:55:58 -08005485 if (kUseFastMixer == FastMixer_Dynamic) {
5486 mNormalSink = mOutputSink;
5487 }
5488#ifdef AUDIO_WATCHDOG
5489 if (mAudioWatchdog != 0) {
5490 mAudioWatchdog->pause();
5491 }
5492#endif
5493 } else {
5494 sq->end(false /*didModify*/);
5495 }
5496 }
5497 PlaybackThread::threadLoop_standby();
5498}
5499
Andy Hungee58e4a2023-07-07 13:47:37 -07005500bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005501{
5502 return false;
5503}
5504
Andy Hungee58e4a2023-07-07 13:47:37 -07005505bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005506{
5507 return !mStandby;
5508}
5509
Andy Hungee58e4a2023-07-07 13:47:37 -07005510bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005511{
Andy Hung972bec12023-08-31 16:13:39 -07005512 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005513 return waitingAsyncCallback_l();
5514}
5515
Eric Laurent81784c32012-11-19 14:55:58 -08005516// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005517void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005518{
Andy Hung8d672e02023-09-15 18:19:28 -07005519 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5520 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005521 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005522 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005523 // discard any pending drain or write ack by incrementing sequence
5524 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5525 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005526 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005527 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5528 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005529 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005530 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005531 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005532}
5533
Andy Hungee58e4a2023-07-07 13:47:37 -07005534void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005535{
5536 ALOGV("signal playback thread");
5537 broadcast_l();
5538}
5539
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005540void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005541{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005542 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005543 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5544 invalidateTracks((audio_stream_type_t)i);
5545 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005546 if (isHardError) {
5547 mAfThreadCallback->onHardError(allTrackPortIds);
5548 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005549}
5550
Andy Hungee58e4a2023-07-07 13:47:37 -07005551void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005552{
Eric Laurent81784c32012-11-19 14:55:58 -08005553 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005554 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005555 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005556 // increase sleep time progressively when application underrun condition clears.
5557 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5558 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5559 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005560 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005561 sleepTimeShift--;
5562 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005563 mSleepTimeUs = 0;
5564 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005565 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005566
Eric Laurent81784c32012-11-19 14:55:58 -08005567}
5568
Andy Hungee58e4a2023-07-07 13:47:37 -07005569void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005570{
5571 // If no tracks are ready, sleep once for the duration of an output
5572 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005573 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005574 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005575 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5576 // Using the Monopipe availableToWrite, we estimate the
5577 // sleep time to retry for more data (before we underrun).
5578 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5579 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5580 const size_t pipeFrames = monoPipe->maxFrames();
5581 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5582 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5583 const size_t framesDelay = std::min(
5584 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5585 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5586 pipeFrames, framesLeft, framesDelay);
5587 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5588 } else {
5589 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5590 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5591 mSleepTimeUs = kMinThreadSleepTimeUs;
5592 }
5593 // reduce sleep time in case of consecutive application underruns to avoid
5594 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5595 // duration we would end up writing less data than needed by the audio HAL if
5596 // the condition persists.
5597 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5598 sleepTimeShift++;
5599 }
Eric Laurent81784c32012-11-19 14:55:58 -08005600 }
5601 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005602 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005603 }
5604 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005605 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5606 // before effects processing or output.
5607 if (mMixerBufferValid) {
5608 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005609 if (mType == SPATIALIZER) {
5610 memset(mSinkBuffer, 0, mSinkBufferSize);
5611 }
Andy Hung98ef9782014-03-04 14:46:50 -08005612 } else {
5613 memset(mSinkBuffer, 0, mSinkBufferSize);
5614 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005615 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005616 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5617 "anticipated start");
5618 }
5619 // TODO add standby time extension fct of effect tail
5620}
5621
Andy Hungc5007f82023-08-29 14:26:09 -07005622// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005623PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005624 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005625{
Andy Hungc0691382018-09-12 18:01:57 -07005626 // clean up deleted track ids in AudioMixer before allocating new tracks
5627 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5628 // for each trackId, destroy it in the AudioMixer
5629 if (mAudioMixer->exists(trackId)) {
5630 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005631 }
5632 });
Andy Hungc0691382018-09-12 18:01:57 -07005633 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005634
5635 mixer_state mixerStatus = MIXER_IDLE;
5636 // find out which tracks need to be processed
5637 size_t count = mActiveTracks.size();
5638 size_t mixedTracks = 0;
5639 size_t tracksWithEffect = 0;
5640 // counts only _active_ fast tracks
5641 size_t fastTracks = 0;
5642 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5643
5644 float masterVolume = mMasterVolume;
5645 bool masterMute = mMasterMute;
5646
5647 if (masterMute) {
5648 masterVolume = 0;
5649 }
5650 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005651 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005652 if (chain != 0) {
5653 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005654 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005655 masterVolume = (float)((v + (1 << 23)) >> 24);
5656 chain.clear();
5657 }
5658
5659 // prepare a new state to push
5660 FastMixerStateQueue *sq = NULL;
5661 FastMixerState *state = NULL;
5662 bool didModify = false;
5663 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005664 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005665 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005666 sq = mFastMixer->sq();
5667 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005668 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005669 }
5670
Andy Hung69aed5f2014-02-25 17:24:40 -08005671 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005672 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005673
Andy Hungbd3b2b02018-05-21 10:53:11 -07005674 // DeferredOperations handles statistics after setting mixerStatus.
5675 class DeferredOperations {
5676 public:
Andy Hungea840382020-05-05 21:50:17 -07005677 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5678 : mMixerStatus(mixerStatus)
5679 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005680
5681 // when leaving scope, tally frames properly.
5682 ~DeferredOperations() {
5683 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5684 // because that is when the underrun occurs.
5685 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005686 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005687 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005688 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005689 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005690 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005691 }
5692 }
Andy Hungea840382020-05-05 21:50:17 -07005693 // send the max underrun frames for this mixer period
5694 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005695 }
5696
5697 // tallyUnderrunFrames() is called to update the track counters
5698 // with the number of underrun frames for a particular mixer period.
5699 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005700 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005701 mUnderrunFrames.emplace_back(track, underrunFrames);
5702 }
5703
5704 private:
5705 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005706 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005707 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005708 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005709 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005710
jiabin245cdd92018-12-07 17:55:15 -08005711 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005712 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005713 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005714
5715 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005716 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005717
5718 // process fast tracks
5719 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005720 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5721 "%s(%d): FastTrack(%d) present without FastMixer",
5722 __func__, id(), track->id());
5723
jiabin245cdd92018-12-07 17:55:15 -08005724 if (track->getHapticPlaybackEnabled()) {
5725 noFastHapticTrack = false;
5726 }
Eric Laurent81784c32012-11-19 14:55:58 -08005727
5728 // It's theoretically possible (though unlikely) for a fast track to be created
5729 // and then removed within the same normal mix cycle. This is not a problem, as
5730 // the track never becomes active so it's fast mixer slot is never touched.
5731 // The converse, of removing an (active) track and then creating a new track
5732 // at the identical fast mixer slot within the same normal mix cycle,
5733 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005734 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005735 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005736 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5737 FastTrack *fastTrack = &state->mFastTracks[j];
5738
5739 // Determine whether the track is currently in underrun condition,
5740 // and whether it had a recent underrun.
5741 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5742 FastTrackUnderruns underruns = ftDump->mUnderruns;
5743 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005744 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005745 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005746 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005747 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005748 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005749 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005750 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005751 // don't count underruns that occur while stopping or pausing
5752 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005753 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005754 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5755 recentUnderruns > 0) {
5756 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005757 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005758 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005759 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005760 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005761
5762 // This is similar to the state machine for normal tracks,
5763 // with a few modifications for fast tracks.
5764 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005765 switch (track->state()) {
5766 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005767 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005768 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005769 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005770 }
5771 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005772 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005773 // ramp down is not yet implemented
5774 track->setPaused();
5775 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005776 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005777 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005778 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005779 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005780 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005781 if (recentFull > 0 || recentPartial > 0) {
5782 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005783 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005784 }
5785 if (recentUnderruns == 0) {
5786 // no recent underruns: stay active
5787 break;
5788 }
5789 // there has recently been an underrun of some kind
5790 if (track->sharedBuffer() == 0) {
5791 // were any of the recent underruns "empty" (no frames available)?
5792 if (recentEmpty == 0) {
5793 // no, then ignore the partial underruns as they are allowed indefinitely
5794 break;
5795 }
5796 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005797 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005798 break;
5799 }
5800 // indicate to client process that the track was disabled because of underrun;
5801 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005802 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005803 // remove from active list, but state remains ACTIVE [confusing but true]
5804 isActive = false;
5805 break;
5806 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005807 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005808 case IAfTrackBase::STOPPING_2:
5809 case IAfTrackBase::PAUSED:
5810 case IAfTrackBase::STOPPED:
5811 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005812 // Check for presentation complete if track is inactive
5813 // We have consumed all the buffers of this track.
5814 // This would be incomplete if we auto-paused on underrun
5815 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005816 uint32_t latency = 0;
5817 status_t result = mOutput->stream->getLatency(&latency);
5818 ALOGE_IF(result != OK,
5819 "Error when retrieving output stream latency: %d", result);
5820 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005821 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005822 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5823 // track stays in active list until presentation is complete
5824 break;
5825 }
5826 }
5827 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005828 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005829 }
5830 if (track->isStopped()) {
5831 // Can't reset directly, as fast mixer is still polling this track
5832 // track->reset();
5833 // So instead mark this track as needing to be reset after push with ack
5834 resetMask |= 1 << i;
5835 }
5836 isActive = false;
5837 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005838 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005839 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005840 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005841 }
5842
5843 if (isActive) {
5844 // was it previously inactive?
5845 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005846 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5847 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005848 fastTrack->mBufferProvider = eabp;
5849 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005850 fastTrack->mChannelMask = track->channelMask();
5851 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005852 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005853 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005854 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005855 fastTrack->mGeneration++;
Andy Hungf767de02024-10-30 19:47:50 -07005856 snprintf(fastTrack->mTraceName, sizeof(fastTrack->mTraceName),
5857 "%s%s", AUDIO_TRACE_PREFIX_AUDIO_TRACK_FRDY,
5858 track->getTraceSuffix().c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08005859 state->mTrackMask |= 1 << j;
5860 didModify = true;
5861 // no acknowledgement required for newly active tracks
5862 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005863 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005864 float volume;
Andy Hung6b137d12024-08-27 22:35:17 +00005865 if (!audioserver_flags::portid_volume_management()) {
5866 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5867 volume = 0.f;
5868 } else {
5869 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5870 }
Eric Laurenteab90452019-06-24 15:17:46 -07005871 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07005872 if (track->isPlaybackRestricted() || track->getPortMute()) {
Andy Hung6b137d12024-08-27 22:35:17 +00005873 volume = 0.f;
5874 } else {
5875 volume = masterVolume * track->getPortVolume();
5876 }
Eric Laurenteab90452019-06-24 15:17:46 -07005877 }
Eric Laurenteab90452019-06-24 15:17:46 -07005878 handleVoipVolume_l(&volume);
5879
Eric Laurent81784c32012-11-19 14:55:58 -08005880 // cache the combined master volume and stream type volume for fast mixer; this
5881 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005882 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005883 proxy->framesReleased()).first;
5884 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005885 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005886 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005887 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5888 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Andy Hung6b137d12024-08-27 22:35:17 +00005889 if (!audioserver_flags::portid_volume_management()) {
5890 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5891 /*muteState=*/{masterVolume == 0.f,
5892 mStreamTypes[track->streamType()].volume == 0.f,
5893 mStreamTypes[track->streamType()].mute,
5894 track->isPlaybackRestricted(),
5895 vlf == 0.f && vrf == 0.f,
Vlad Popa1e865e62024-08-15 19:11:42 -07005896 vh == 0.f,
5897 /*muteFromPortVolume=*/false});
Andy Hung6b137d12024-08-27 22:35:17 +00005898 } else {
5899 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5900 /*muteState=*/{masterVolume == 0.f,
5901 track->getPortVolume() == 0.f,
5902 /* muteFromStreamMuted= */ false,
5903 track->isPlaybackRestricted(),
5904 vlf == 0.f && vrf == 0.f,
Vlad Popa1e865e62024-08-15 19:11:42 -07005905 vh == 0.f,
5906 track->getPortMute()});
Andy Hung6b137d12024-08-27 22:35:17 +00005907 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005908 vlf *= volume;
5909 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005910
jiabin220eea12024-05-17 17:55:20 +00005911 if (track->getInternalMute()) {
5912 vlf = 0.f;
5913 vrf = 0.f;
5914 }
5915
jiabin76d94692022-12-15 21:51:21 +00005916 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005917 ++fastTracks;
5918 } else {
5919 // was it previously active?
5920 if (state->mTrackMask & (1 << j)) {
5921 fastTrack->mBufferProvider = NULL;
5922 fastTrack->mGeneration++;
5923 state->mTrackMask &= ~(1 << j);
5924 didModify = true;
5925 // If any fast tracks were removed, we must wait for acknowledgement
5926 // because we're about to decrement the last sp<> on those tracks.
5927 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5928 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005929 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5930 // AudioTrack may start (which may not be with a start() but with a write()
5931 // after underrun) and immediately paused or released. In that case the
5932 // FastTrack state hasn't had time to update.
5933 // TODO Remove the ALOGW when this theory is confirmed.
5934 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005935 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005936 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005937 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005938 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005939 }
5940 tracksToRemove->add(track);
5941 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005942 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005943 }
jiabin245cdd92018-12-07 17:55:15 -08005944 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5945 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5946 didModify = true;
5947 }
Eric Laurent81784c32012-11-19 14:55:58 -08005948 continue;
5949 }
5950
5951 { // local variable scope to avoid goto warning
5952
5953 audio_track_cblk_t* cblk = track->cblk();
5954
5955 // The first time a track is added we wait
5956 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005957 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005958
5959 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005960 // use the trackId as the AudioMixer name.
5961 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005962 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005963 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005964 track->channelMask(),
5965 track->format(),
5966 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005967 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005968 ALOGW("%s(): AudioMixer cannot create track(%d)"
5969 " mask %#x, format %#x, sessionId %d",
5970 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005971 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005972 tracksToRemove->add(track);
5973 track->invalidate(); // consider it dead.
5974 continue;
5975 }
5976 }
5977
Eric Laurent81784c32012-11-19 14:55:58 -08005978 // make sure that we have enough frames to mix one full buffer.
5979 // enforce this condition only once to enable draining the buffer in case the client
5980 // app does not call stop() and relies on underrun to stop:
5981 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5982 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005983 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005984 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5985 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005986
5987 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005988 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005989 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5990 // add frames already consumed but not yet released by the resampler
5991 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005992 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005993
Eric Laurent81784c32012-11-19 14:55:58 -08005994 uint32_t minFrames = 1;
5995 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5996 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005997 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005998 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005999
6000 size_t framesReady = track->framesReady();
Andy Hungf767de02024-10-30 19:47:50 -07006001 if (ATRACE_ENABLED()) [[unlikely]] {
6002 ATRACE_INT(std::string(AUDIO_TRACE_PREFIX_AUDIO_TRACK_NRDY)
6003 .append(track->getTraceSuffix()).c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07006004 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006005 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08006006 !track->isPaused() && !track->isTerminated())
6007 {
Andy Hungc0691382018-09-12 18:01:57 -07006008 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006009
6010 mixedTracks++;
6011
Shunkai Yaof4847652024-01-12 00:25:20 +00006012 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08006013 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08006014 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08006015 if (track->mainBuffer() != mSinkBuffer &&
6016 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08006017 if (mEffectBufferEnabled) {
6018 mEffectBufferValid = true; // Later can set directly.
6019 }
Eric Laurent81784c32012-11-19 14:55:58 -08006020 chain = getEffectChain_l(track->sessionId());
6021 // Delegate volume control to effect in track effect chain if needed
6022 if (chain != 0) {
6023 tracksWithEffect++;
6024 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006025 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08006026 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07006027 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006028 }
6029 }
6030
6031
6032 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07006033 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08006034 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07006035 track->fillingStatus() = IAfTrack::FS_ACTIVE;
6036 if (track->state() == IAfTrackBase::RESUMING) {
6037 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08006038 // If a new track is paused immediately after start, do not ramp on resume.
6039 if (cblk->mServer != 0) {
6040 param = AudioMixer::RAMP_VOLUME;
6041 }
Eric Laurent81784c32012-11-19 14:55:58 -08006042 }
Andy Hungc0691382018-09-12 18:01:57 -07006043 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07006044 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07006045 // FIXME should not make a decision based on mServer
6046 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006047 // If the track is stopped before the first frame was mixed,
6048 // do not apply ramp
6049 param = AudioMixer::RAMP_VOLUME;
6050 }
6051
6052 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07006053 uint32_t vl, vr; // in U8.24 integer format
6054 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07006055 // read original volumes with volume control
Andy Hung333ab962019-05-28 20:23:35 -07006056 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07006057 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07006058 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07006059 track->audioTrackServerProxy()->framesReleased()).first;
Andy Hung6b137d12024-08-27 22:35:17 +00006060 float v;
6061 if (!audioserver_flags::portid_volume_management()) {
6062 v = masterVolume * mStreamTypes[track->streamType()].volume;
6063 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6064 v = 0;
6065 }
6066 } else {
6067 v = masterVolume * track->getPortVolume();
Vlad Popa1e865e62024-08-15 19:11:42 -07006068 if (track->isPlaybackRestricted() || track->getPortMute()) {
Andy Hung6b137d12024-08-27 22:35:17 +00006069 v = 0;
6070 }
Eric Laurenteab90452019-06-24 15:17:46 -07006071 }
Eric Laurenteab90452019-06-24 15:17:46 -07006072 handleVoipVolume_l(&v);
6073
6074 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07006075 vl = vr = 0;
6076 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07006077 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08006078 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07006079 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07006080 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
6081 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08006082 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07006083 if (vlf > GAIN_FLOAT_UNITY) {
6084 ALOGV("Track left volume out of range: %.3g", vlf);
6085 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006086 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006087 if (vrf > GAIN_FLOAT_UNITY) {
6088 ALOGV("Track right volume out of range: %.3g", vrf);
6089 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006090 }
Andy Hung6b137d12024-08-27 22:35:17 +00006091 if (!audioserver_flags::portid_volume_management()) {
6092 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6093 /*muteState=*/{masterVolume == 0.f,
6094 mStreamTypes[track->streamType()].volume == 0.f,
6095 mStreamTypes[track->streamType()].mute,
6096 track->isPlaybackRestricted(),
6097 vlf == 0.f && vrf == 0.f,
Vlad Popa1e865e62024-08-15 19:11:42 -07006098 vh == 0.f,
6099 /*muteFromPortVolume=*/false});
Andy Hung6b137d12024-08-27 22:35:17 +00006100 } else {
6101 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6102 /*muteState=*/{masterVolume == 0.f,
6103 track->getPortVolume() == 0.f,
6104 /* muteFromStreamMuted= */ false,
6105 track->isPlaybackRestricted(),
6106 vlf == 0.f && vrf == 0.f,
Vlad Popa1e865e62024-08-15 19:11:42 -07006107 vh == 0.f,
6108 track->getPortMute()});
Andy Hung6b137d12024-08-27 22:35:17 +00006109 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006110 // now apply the master volume and stream type volume and shaper volume
6111 vlf *= v * vh;
6112 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006113 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006114 // then derive vl and vr as U8.24 versions for the effect chain
6115 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6116 vl = (uint32_t) (scaleto8_24 * vlf);
6117 vr = (uint32_t) (scaleto8_24 * vrf);
6118 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006119 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006120 // send level comes from shared memory and so may be corrupt
6121 if (sendLevel > MAX_GAIN_INT) {
6122 ALOGV("Track send level out of range: %04X", sendLevel);
6123 sendLevel = MAX_GAIN_INT;
6124 }
Andy Hung6be49402014-05-30 10:42:03 -07006125 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6126 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006127 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006128
jiabin220eea12024-05-17 17:55:20 +00006129 if (track->getInternalMute()) {
6130 vrf = 0.f;
6131 vlf = 0.f;
6132 }
6133
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006134 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006135
Eric Laurent81784c32012-11-19 14:55:58 -08006136 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006137 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006138 // Do not ramp volume if volume is controlled by effect
6139 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006140 // Update remaining floating point volume levels
6141 vlf = (float)vl / (1 << 24);
6142 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006143 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006144 } else {
6145 // force no volume ramp when volume controller was just disabled or removed
6146 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006147 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006148 param = AudioMixer::VOLUME;
6149 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006150 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006151 }
6152
Eric Laurent81784c32012-11-19 14:55:58 -08006153 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006154 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006155 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006156
Andy Hungc0691382018-09-12 18:01:57 -07006157 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6158 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6159 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006160 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006161 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006162 AudioMixer::TRACK,
6163 AudioMixer::FORMAT, (void *)track->format());
6164 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006165 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006166 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006167 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006168
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006169 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006170 mAudioMixer->setParameter(
6171 trackId,
6172 AudioMixer::TRACK,
6173 AudioMixer::MIXER_CHANNEL_MASK,
6174 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6175 } else {
6176 mAudioMixer->setParameter(
6177 trackId,
6178 AudioMixer::TRACK,
6179 AudioMixer::MIXER_CHANNEL_MASK,
6180 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6181 }
6182
Glenn Kastene3aa6592012-12-04 12:22:46 -08006183 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006184 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006185 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006186 if (reqSampleRate == 0) {
6187 reqSampleRate = mSampleRate;
6188 } else if (reqSampleRate > maxSampleRate) {
6189 reqSampleRate = maxSampleRate;
6190 }
Eric Laurent81784c32012-11-19 14:55:58 -08006191 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006192 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006193 AudioMixer::RESAMPLE,
6194 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006195 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006196
Andy Hung8edb8dc2015-03-26 19:13:55 -07006197 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006198 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006199 AudioMixer::TIMESTRETCH,
6200 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006201 // cast away constness for this generic API.
6202 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006203
Andy Hung69aed5f2014-02-25 17:24:40 -08006204 /*
6205 * Select the appropriate output buffer for the track.
6206 *
Andy Hung98ef9782014-03-04 14:46:50 -08006207 * Tracks with effects go into their own effects chain buffer
6208 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006209 *
6210 * Other tracks can use mMixerBuffer for higher precision
6211 * channel accumulation. If this buffer is enabled
6212 * (mMixerBufferEnabled true), then selected tracks will accumulate
6213 * into it.
6214 *
6215 */
6216 if (mMixerBufferEnabled
6217 && (track->mainBuffer() == mSinkBuffer
6218 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006219 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006220 mAudioMixer->setParameter(
6221 trackId,
6222 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006223 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006224 mAudioMixer->setParameter(
6225 trackId,
6226 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006227 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006228 } else {
6229 mAudioMixer->setParameter(
6230 trackId,
6231 AudioMixer::TRACK,
6232 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6233 mAudioMixer->setParameter(
6234 trackId,
6235 AudioMixer::TRACK,
6236 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6237 // TODO: override track->mainBuffer()?
6238 mMixerBufferValid = true;
6239 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006240 } else {
6241 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006242 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006243 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006244 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006245 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006246 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006247 AudioMixer::TRACK,
6248 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6249 }
Eric Laurent81784c32012-11-19 14:55:58 -08006250 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006251 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006252 AudioMixer::TRACK,
6253 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006254 mAudioMixer->setParameter(
6255 trackId,
6256 AudioMixer::TRACK,
6257 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006258 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006259 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006260 trackId,
6261 AudioMixer::TRACK,
6262 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006263 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006264 mAudioMixer->setParameter(
6265 trackId,
6266 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006267 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006268
6269 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006270 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006271
6272 // If one track is ready, set the mixer ready if:
6273 // - the mixer was not ready during previous round OR
6274 // - no other track is not ready
6275 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6276 mixerStatus != MIXER_TRACKS_ENABLED) {
6277 mixerStatus = MIXER_TRACKS_READY;
6278 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006279
6280 // Enable the next few lines to instrument a test for underrun log handling.
6281 // TODO: Remove when we have a better way of testing the underrun log.
6282#if 0
6283 static int i;
6284 if ((++i & 0xf) == 0) {
6285 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6286 }
6287#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006288 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006289 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006290 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006291 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6292 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006293 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006294 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006295 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006296
Eric Laurent81784c32012-11-19 14:55:58 -08006297 // clear effect chain input buffer if an active track underruns to avoid sending
6298 // previous audio buffer again to effects
6299 chain = getEffectChain_l(track->sessionId());
6300 if (chain != 0) {
6301 chain->clearInputBuffer();
6302 }
6303
Andy Hungc0691382018-09-12 18:01:57 -07006304 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006305 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6306 track->isStopped() || track->isPaused()) {
6307 // We have consumed all the buffers of this track.
6308 // Remove it from the list of active tracks.
6309 // TODO: use actual buffer filling status instead of latency when available from
6310 // audio HAL
6311 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006312 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006313 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6314 if (track->isStopped()) {
6315 track->reset();
6316 }
6317 tracksToRemove->add(track);
6318 }
6319 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006320 // No buffers for this track. Give it a few chances to
6321 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006322 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006323 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6324 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006325 tracksToRemove->add(track);
6326 // indicate to client process that the track was disabled because of underrun;
6327 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006328 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006329 // If one track is not ready, mark the mixer also not ready if:
6330 // - the mixer was ready during previous round OR
6331 // - no other track is ready
6332 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6333 mixerStatus != MIXER_TRACKS_READY) {
6334 mixerStatus = MIXER_TRACKS_ENABLED;
6335 }
6336 }
Andy Hungc0691382018-09-12 18:01:57 -07006337 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006338 }
6339
6340 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006341
6342 }
6343
jiabin245cdd92018-12-07 17:55:15 -08006344 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6345 // When there is no fast track playing haptic and FastMixer exists,
6346 // enabling the first FastTrack, which provides mixed data from normal
6347 // tracks, to play haptic data.
6348 FastTrack *fastTrack = &state->mFastTracks[0];
6349 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6350 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6351 didModify = true;
6352 }
6353 }
6354
Eric Laurent81784c32012-11-19 14:55:58 -08006355 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006356 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006357 if (didModify) {
6358 state->mFastTracksGen++;
6359 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6360 if (kUseFastMixer == FastMixer_Dynamic &&
6361 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6362 state->mCommand = FastMixerState::COLD_IDLE;
6363 state->mColdFutexAddr = &mFastMixerFutex;
6364 state->mColdGen++;
6365 mFastMixerFutex = 0;
6366 if (kUseFastMixer == FastMixer_Dynamic) {
6367 mNormalSink = mOutputSink;
6368 }
6369 // If we go into cold idle, need to wait for acknowledgement
6370 // so that fast mixer stops doing I/O.
6371 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6372 pauseAudioWatchdog = true;
6373 }
Eric Laurent81784c32012-11-19 14:55:58 -08006374 }
6375 if (sq != NULL) {
6376 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006377 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6378 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6379 // when bringing the output sink into standby.)
6380 //
6381 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6382 //
6383 // This occurs with BT suspend when we idle the FastMixer with
6384 // active tracks, which may be added or removed.
Andy Hung82f39d62024-09-30 17:19:14 -07006385 {
6386 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastMixer->getTid());
6387 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
6388 }
Eric Laurent81784c32012-11-19 14:55:58 -08006389 }
6390#ifdef AUDIO_WATCHDOG
6391 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6392 mAudioWatchdog->pause();
6393 }
6394#endif
6395
6396 // Now perform the deferred reset on fast tracks that have stopped
6397 while (resetMask != 0) {
6398 size_t i = __builtin_ctz(resetMask);
6399 ALOG_ASSERT(i < count);
6400 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006401 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006402 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6403 track->reset();
6404 }
6405
Andy Hung80d03d22018-04-10 10:32:11 -07006406 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6407 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6408 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6409 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6410 // See also the implementation of destroyTrack_l().
6411 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006412 const int trackId = track->id();
6413 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6414 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006415 }
6416 }
6417
Eric Laurent81784c32012-11-19 14:55:58 -08006418 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006419 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006420
Eric Laurentb3f315a2021-07-13 15:09:05 +02006421 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6422 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006423 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006424 }
6425
6426 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006427 // as long as there are effects we should clear the effects buffer, to avoid
6428 // passing a non-clean buffer to the effect chain
6429 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006430 if (mType == SPATIALIZER) {
6431 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6432 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006433 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006434 // sink or mix buffer must be cleared if all tracks are connected to an
6435 // effect chain as in this case the mixer will not write to the sink or mix buffer
6436 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006437 // always clear sink buffer for spatializer output as the output of the spatializer
6438 // effect will be accumulated into it
6439 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6440 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006441 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006442 if (mMixerBufferValid) {
6443 memset(mMixerBuffer, 0, mMixerBufferSize);
6444 // TODO: In testing, mSinkBuffer below need not be cleared because
6445 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6446 // after mixing.
6447 //
6448 // To enforce this guarantee:
6449 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6450 // (mixedTracks == 0 && fastTracks > 0))
6451 // must imply MIXER_TRACKS_READY.
6452 // Later, we may clear buffers regardless, and skip much of this logic.
6453 }
Andy Hung98ef9782014-03-04 14:46:50 -08006454 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006455 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006456 }
6457
6458 // if any fast tracks, then status is ready
6459 mMixerStatusIgnoringFastTracks = mixerStatus;
6460 if (fastTracks > 0) {
6461 mixerStatus = MIXER_TRACKS_READY;
6462 }
6463 return mixerStatus;
6464}
6465
Andy Hungc5007f82023-08-29 14:26:09 -07006466// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006467uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006468{
6469 uint32_t trackCount = 0;
6470 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006471 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006472 trackCount++;
6473 }
6474 }
6475 return trackCount;
6476}
6477
Andy Hungee58e4a2023-07-07 13:47:37 -07006478bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006479{
Brian Lindahl65e90012022-07-27 18:01:07 +02006480 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6481 // could falsely detect that the frame position has stalled due to underrun because we haven't
6482 // given the Audio HAL enough time to update.
6483 const nsecs_t nowNs = systemTime();
6484 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6485 return mLatchedValue;
6486 }
6487 mPreviousNs = nowNs;
6488 mLatchedValue = false;
6489 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006490 uint64_t position = 0;
6491 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006492 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006493 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006494 if (position != mPreviousPosition) {
6495 mPreviousPosition = position;
6496 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006497 }
6498 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006499 return mLatchedValue;
6500}
6501
Andy Hungee58e4a2023-07-07 13:47:37 -07006502void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006503{
6504 mLatchedValue = true;
6505 mPreviousPosition = 0;
6506 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006507}
6508
Andy Hungc5007f82023-08-29 14:26:09 -07006509// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006510bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006511 audio_channel_mask_t channelMask, audio_format_t format,
6512 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006513{
Andy Hung1bc088a2018-02-09 15:57:31 -08006514 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6515 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006516 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006517 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006518 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006519 ALOGW("%s: invalid format: %#x", __func__, format);
6520 return false;
6521 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006522 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006523 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6524 return false;
6525 }
6526 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006527}
6528
Andy Hungc5007f82023-08-29 14:26:09 -07006529// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006530bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006531 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006532{
Eric Laurent81784c32012-11-19 14:55:58 -08006533 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006534 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006535
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006536 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006537
Eric Laurent10351942014-05-08 18:49:52 -07006538 AudioParameter param = AudioParameter(keyValuePair);
6539 int value;
6540 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6541 reconfig = true;
6542 }
6543 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006544 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006545 status = BAD_VALUE;
6546 } else {
6547 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006548 reconfig = true;
6549 }
Eric Laurent10351942014-05-08 18:49:52 -07006550 }
6551 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006552 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006553 status = BAD_VALUE;
6554 } else {
6555 // no need to save value, since it's constant
6556 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006557 }
Eric Laurent10351942014-05-08 18:49:52 -07006558 }
6559 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6560 // do not accept frame count changes if tracks are open as the track buffer
6561 // size depends on frame count and correct behavior would not be guaranteed
6562 // if frame count is changed after track creation
6563 if (!mTracks.isEmpty()) {
6564 status = INVALID_OPERATION;
6565 } else {
6566 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006567 }
Eric Laurent10351942014-05-08 18:49:52 -07006568 }
6569 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006570 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006571 }
Eric Laurent81784c32012-11-19 14:55:58 -08006572
Eric Laurent10351942014-05-08 18:49:52 -07006573 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006574 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006575 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006576 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6577 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006578 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006579 mThreadMetrics.logEndInterval();
6580 mThreadSnapshot.onEnd();
6581 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006582 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006583 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006584 }
Eric Laurent10351942014-05-08 18:49:52 -07006585 if (status == NO_ERROR && reconfig) {
6586 readOutputParameters_l();
6587 delete mAudioMixer;
6588 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006589 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006590 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006591 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006592 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006593 track->channelMask(),
6594 track->format(),
6595 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006596 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006597 "%s(): AudioMixer cannot create track(%d)"
6598 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006599 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006600 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006601 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006602 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006603 }
Eric Laurent81784c32012-11-19 14:55:58 -08006604 }
6605
Dean Wheatley68918102021-03-19 22:09:19 +11006606 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006607}
6608
6609
Andy Hungee58e4a2023-07-07 13:47:37 -07006610void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006611{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006612 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006613 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006614 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006615 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006616 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6617 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6618 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006619 if (hasFastMixer()) {
6620 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6621
6622 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6623 // while we are dumping it. It may be inconsistent, but it won't mutate!
6624 // This is a large object so we place it on the heap.
6625 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006626 const std::unique_ptr<FastMixerDumpState> copy =
6627 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006628 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006629
6630#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006631 // Similar for state queue
6632 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6633 observerCopy.dump(fd);
6634 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6635 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006636#endif
6637
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006638#ifdef AUDIO_WATCHDOG
6639 if (mAudioWatchdog != 0) {
6640 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6641 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6642 wdCopy.dump(fd);
6643 }
6644#endif
6645
6646 } else {
6647 dprintf(fd, " No FastMixer\n");
6648 }
Eric Laurent90cea102023-05-15 15:08:27 +02006649
6650 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6651 mBluetoothLatencyModesEnabled ? "" : "not ");
6652 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6653 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6654 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006655}
6656
Andy Hungee58e4a2023-07-07 13:47:37 -07006657uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006658{
6659 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6660}
6661
Andy Hungee58e4a2023-07-07 13:47:37 -07006662uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006663{
6664 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6665}
6666
Andy Hungee58e4a2023-07-07 13:47:37 -07006667void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006668{
6669 PlaybackThread::cacheParameters_l();
6670
6671 // FIXME: Relaxed timing because of a certain device that can't meet latency
6672 // Should be reduced to 2x after the vendor fixes the driver issue
6673 // increase threshold again due to low power audio mode. The way this warning
6674 // threshold is calculated and its usefulness should be reconsidered anyway.
6675 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6676}
6677
Andy Hungee58e4a2023-07-07 13:47:37 -07006678void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006679 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006680}
6681
Andy Hungee58e4a2023-07-07 13:47:37 -07006682void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006683 // Only handle latency mode if:
6684 // - mBluetoothLatencyModesEnabled is true
6685 // - the HAL supports latency modes
6686 // - the selected device is Bluetooth LE or A2DP
6687 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6688 return;
6689 }
6690 if (mOutDeviceTypeAddrs.size() != 1
6691 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6692 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6693 return;
6694 }
6695
6696 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6697 if (mSupportedLatencyModes.size() == 1) {
6698 // If the HAL only support one latency mode currently, confirm the choice
6699 latencyMode = mSupportedLatencyModes[0];
6700 } else if (mSupportedLatencyModes.size() > 1) {
6701 // Request low latency if:
6702 // - At least one active track is either:
6703 // - a fast track with gaming usage or
6704 // - a track with acessibility usage
6705 for (const auto& track : mActiveTracks) {
6706 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6707 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6708 latencyMode = AUDIO_LATENCY_MODE_LOW;
6709 break;
6710 }
6711 }
6712 }
6713
6714 if (latencyMode != mSetLatencyMode) {
6715 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6716 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6717 __func__, mId, toString(latencyMode).c_str(), status);
6718 if (status == NO_ERROR) {
6719 mSetLatencyMode = latencyMode;
6720 }
6721 }
6722}
6723
Andy Hungee58e4a2023-07-07 13:47:37 -07006724void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006725
6726 if (mOutput == nullptr || mOutput->stream == nullptr) {
6727 return;
6728 }
6729 std::vector<audio_latency_mode_t> latencyModes;
6730 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6731 if (status != NO_ERROR) {
6732 latencyModes.clear();
6733 }
6734 if (latencyModes != mSupportedLatencyModes) {
6735 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6736 __func__, mId, status, toString(latencyModes).c_str());
6737 mSupportedLatencyModes.swap(latencyModes);
6738 sendHalLatencyModesChangedEvent_l();
6739 }
6740}
6741
Andy Hungee58e4a2023-07-07 13:47:37 -07006742status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006743 std::vector<audio_latency_mode_t>* modes) {
6744 if (modes == nullptr) {
6745 return BAD_VALUE;
6746 }
Andy Hung972bec12023-08-31 16:13:39 -07006747 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006748 *modes = mSupportedLatencyModes;
6749 return NO_ERROR;
6750}
6751
Andy Hungee58e4a2023-07-07 13:47:37 -07006752void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006753 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006754 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006755 if (modes != mSupportedLatencyModes) {
6756 ALOGD("%s: thread(%d) supported latency modes: %s",
6757 __func__, mId, toString(modes).c_str());
6758 mSupportedLatencyModes.swap(modes);
6759 sendHalLatencyModesChangedEvent_l();
6760 }
6761}
6762
Andy Hungee58e4a2023-07-07 13:47:37 -07006763status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006764 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6765 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6766 return INVALID_OPERATION;
6767 }
6768 mBluetoothLatencyModesEnabled.store(enabled);
6769 return NO_ERROR;
6770}
6771
Eric Laurent81784c32012-11-19 14:55:58 -08006772// ----------------------------------------------------------------------------
6773
Andy Hungee58e4a2023-07-07 13:47:37 -07006774/* static */
6775sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006776 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006777 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6778 const audio_offload_info_t& offloadInfo) {
6779 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006780 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006781}
6782
Andy Hung583043b2023-07-17 17:05:00 -07006783DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006784 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6785 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006786 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006787 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006788{
Andy Hung583043b2023-07-17 17:05:00 -07006789 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006790}
6791
Andy Hungee58e4a2023-07-07 13:47:37 -07006792DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006793{
6794}
6795
Andy Hungee58e4a2023-07-07 13:47:37 -07006796void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006797{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006798 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006799 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6800 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6801}
6802
Andy Hungee58e4a2023-07-07 13:47:37 -07006803void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006804{
Andy Hung972bec12023-08-31 16:13:39 -07006805 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006806 if (mMasterBalance != balance) {
6807 mMasterBalance.store(balance);
6808 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6809 broadcast_l();
6810 }
6811}
6812
Andy Hungee58e4a2023-07-07 13:47:37 -07006813void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006814{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006815 float left, right;
6816
Andy Hung333ab962019-05-28 20:23:35 -07006817 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006818 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006819
Andy Hung398ffa22022-12-13 19:19:53 -08006820 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6821 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6822
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006823 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6824 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006825
6826 const int64_t volumeShaperFrames =
6827 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6828 const auto [shaperVolume, shaperActive] =
6829 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006830 mVolumeShaperActive = shaperActive;
6831
Vlad Popae2f5aef2022-07-25 16:00:20 +02006832 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6833 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6834 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6835
6836 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6837
Andy Hung6b137d12024-08-27 22:35:17 +00006838 if (!audioserver_flags::portid_volume_management()) {
6839 if (mMasterMute || mStreamTypes[track->streamType()].mute ||
6840 track->isPlaybackRestricted()) {
6841 left = right = 0;
6842 } else {
6843 float typeVolume = mStreamTypes[track->streamType()].volume;
6844 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurent277a37e2024-07-29 18:37:52 +00006845
Andy Hung6b137d12024-08-27 22:35:17 +00006846 if (left > GAIN_FLOAT_UNITY) {
6847 left = GAIN_FLOAT_UNITY;
6848 }
6849 if (right > GAIN_FLOAT_UNITY) {
6850 right = GAIN_FLOAT_UNITY;
6851 }
6852 left *= v;
6853 right *= v;
6854 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006855 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
Andy Hung6b137d12024-08-27 22:35:17 +00006856 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6857 right *= mMasterBalanceRight;
6858 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006859 }
Andy Hung6b137d12024-08-27 22:35:17 +00006860 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6861 /*muteState=*/{mMasterMute,
6862 mStreamTypes[track->streamType()].volume == 0.f,
6863 mStreamTypes[track->streamType()].mute,
6864 track->isPlaybackRestricted(),
6865 clientVolumeMute,
Vlad Popa1e865e62024-08-15 19:11:42 -07006866 shaperVolume == 0.f,
6867 /*muteFromPortVolume=*/false});
Andy Hung6b137d12024-08-27 22:35:17 +00006868 } else {
6869 if (mMasterMute || track->isPlaybackRestricted()) {
6870 left = right = 0;
6871 } else {
6872 float typeVolume = track->getPortVolume();
6873 const float v = mMasterVolume * typeVolume * shaperVolume;
Liana Kazanova (xWF)d3e99d22024-08-23 22:15:51 +00006874
Andy Hung6b137d12024-08-27 22:35:17 +00006875 if (left > GAIN_FLOAT_UNITY) {
6876 left = GAIN_FLOAT_UNITY;
6877 }
6878 if (right > GAIN_FLOAT_UNITY) {
6879 right = GAIN_FLOAT_UNITY;
6880 }
6881 left *= v;
6882 right *= v;
6883 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6884 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6885 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6886 right *= mMasterBalanceRight;
6887 }
6888 }
6889 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6890 /*muteState=*/{mMasterMute,
6891 track->getPortVolume() == 0.f,
6892 /* muteFromStreamMuted= */ false,
6893 track->isPlaybackRestricted(),
6894 clientVolumeMute,
Vlad Popa1e865e62024-08-15 19:11:42 -07006895 shaperVolume == 0.f,
6896 track->getPortMute()});
Andy Hung6b137d12024-08-27 22:35:17 +00006897 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006898
Eric Laurentbfb1b832013-01-07 09:53:42 -08006899 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006900 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006901 if (left != mLeftVolFloat || right != mRightVolFloat) {
6902 mLeftVolFloat = left;
6903 mRightVolFloat = right;
6904
Eric Laurentbfb1b832013-01-07 09:53:42 -08006905 // Delegate volume control to effect in track effect chain if needed
6906 // only one effect chain can be present on DirectOutputThread, so if
6907 // there is one, the track is connected to it
6908 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006909 // if effect chain exists, volume is handled by it.
6910 // Convert volumes from float to 8.24
6911 uint32_t vl = (uint32_t)(left * (1 << 24));
6912 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006913 // Direct/Offload effect chains set output volume in setVolume().
6914 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006915 } else {
6916 // otherwise we directly set the volume.
6917 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006918 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006919 }
6920 }
6921}
6922
Andy Hungee58e4a2023-07-07 13:47:37 -07006923void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006924{
Andy Hung8d31fd22023-06-26 19:20:57 -07006925 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6926 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006927
Eric Laurent0f0631e2015-07-06 18:01:25 -07006928 if (previousTrack != 0 && latestTrack != 0) {
6929 if (mType == DIRECT) {
6930 if (previousTrack.get() != latestTrack.get()) {
6931 mFlushPending = true;
6932 }
6933 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006934 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6935 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006936 mFlushPending = true;
6937 }
6938 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006939 } else if (previousTrack == 0) {
6940 // there could be an old track added back during track transition for direct
6941 // output, so always issues flush to flush data of the previous track if it
6942 // was already destroyed with HAL paused, then flush can resume the playback
6943 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006944 }
6945 PlaybackThread::onAddNewTrack_l();
6946}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006947
Andy Hungee58e4a2023-07-07 13:47:37 -07006948PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006949 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006950)
6951{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006952 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006953 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006954 bool doHwPause = false;
6955 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006956
6957 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006958 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006959 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006960 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006961 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006962 continue;
6963 }
6964
Andy Hung8d31fd22023-06-26 19:20:57 -07006965 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006966#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006967 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006968#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006969 // Only consider last track started for volume and mixer state control.
6970 // In theory an older track could underrun and restart after the new one starts
6971 // but as we only care about the transition phase between two tracks on a
6972 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006973 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006974 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006975
Kuowei Li23666472021-01-20 10:23:25 +08006976 if (track->isPausePending()) {
6977 track->pauseAck();
6978 // It is possible a track might have been flushed or stopped.
6979 // Other operations such as flush pending might occur on the next prepare.
6980 if (track->isPausing()) {
6981 track->setPaused();
6982 }
6983 // Always perform pause, as an immediate flush will change
6984 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006985 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006986 doHwPause = true;
6987 mHwPaused = true;
6988 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006989 } else if (track->isFlushPending()) {
6990 track->flushAck();
6991 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006992 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006993 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006994 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006995 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006996 if (last) {
6997 mLeftVolFloat = mRightVolFloat = -1.0;
6998 if (mHwPaused) {
6999 doHwResume = true;
7000 mHwPaused = false;
7001 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08007002 }
7003 }
7004
Eric Laurent81784c32012-11-19 14:55:58 -08007005 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08007006 // for all its buffers to be filled before processing it.
7007 // Allow draining the buffer in case the client
7008 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07007009 // hence the test on (track->retryCount() > 1).
7010 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07007011 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
7012 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07007013 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07007014
7015 // target retry count that we will use is based on the time we wait for retries.
7016 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
7017 // the retry threshold is when we accept any size for PCM data. This is slightly
7018 // smaller than the retry count so we can push small bits of data without a glitch.
7019 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08007020 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08007021 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07007022 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007023 minFrames = mNormalFrameCount;
7024 } else {
7025 minFrames = 1;
7026 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007027
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07007028 const size_t framesReady = track->framesReady();
7029 const int trackId = track->id();
Andy Hungf767de02024-10-30 19:47:50 -07007030 if (ATRACE_ENABLED()) [[unlikely]] {
7031 ATRACE_INT(std::string(AUDIO_TRACE_PREFIX_AUDIO_TRACK_NRDY)
7032 .append(track->getTraceSuffix()).c_str(), framesReady);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07007033 }
7034 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07007035 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08007036 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07007037 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08007038
Andy Hung8d31fd22023-06-26 19:20:57 -07007039 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7040 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007041 if (last) {
7042 // make sure processVolume_l() will apply new volume even if 0
7043 mLeftVolFloat = mRightVolFloat = -1.0;
7044 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08007045 if (!mHwSupportsPause) {
7046 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08007047 }
7048 }
7049
7050 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08007051 processVolume_l(track, last);
7052 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007053 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007054 if (previousTrack != 0) {
7055 if (track != previousTrack.get()) {
7056 // Flush any data still being written from last track
7057 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07007058 // Invalidate previous track to force a seek when resuming.
7059 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007060 }
7061 }
7062 mPreviousTrack = track;
7063
Eric Laurentd595b7c2013-04-03 17:27:56 -07007064 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07007065 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08007066 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07007067 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07007068 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007069 doHwResume = true;
7070 mHwPaused = false;
7071 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007072 }
Eric Laurent81784c32012-11-19 14:55:58 -08007073 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07007074 // clear effect chain input buffer if the last active track started underruns
7075 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07007076 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08007077 mEffectChains[0]->clearInputBuffer();
7078 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007079 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007080 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07007081 if (last && mHwPaused) {
7082 doHwResume = true;
7083 mHwPaused = false;
7084 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007085 }
7086 if ((track->sharedBuffer() != 0) || track->isStopped() ||
7087 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007088 // We have consumed all the buffers of this track.
7089 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04007090 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07007091 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04007092 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08007093 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04007094 if (presComplete) {
7095 mOutput->presentationComplete();
7096 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007097 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007098 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07007099 }
Eric Laurent81784c32012-11-19 14:55:58 -08007100 if (track->isStopped()) {
7101 track->reset();
7102 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007103 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08007104 }
7105 } else {
7106 // No buffers for this track. Give it a few chances to
7107 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07007108 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02007109 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007110 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007111 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007112 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007113 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08007114 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007115 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7116 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08007117 tracksToRemove->add(track);
7118 // indicate to client process that the track was disabled because of
7119 // underrun; it will then automatically call start() when data is available
7120 track->disable();
7121 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
7122 // unlike mixerthread, HAL can be paused for direct output
7123 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
7124 "minFrames = %u, mFormat = %#x",
7125 framesReady, minFrames, mFormat);
7126 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
7127 doHwPause = true;
7128 mHwPaused = true;
7129 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007130 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08007131 } else if (last) {
7132 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007133 }
7134 }
7135 }
7136 }
7137
Eric Laurentd1f69b02014-12-15 14:33:13 -08007138 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007139 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007140 for (size_t i = 0; i < mTracks.size(); i++) {
7141 if (mTracks[i]->isFlushPending()) {
7142 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007143 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007144 }
7145 }
7146 }
7147
7148 // make sure the pause/flush/resume sequence is executed in the right order.
7149 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7150 // before flush and then resume HW. This can happen in case of pause/flush/resume
7151 // if resume is received before pause is executed.
7152 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007153 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007154 status_t result = mOutput->stream->pause();
7155 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007156 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007157 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007158 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007159 flushHw_l();
7160 }
7161 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007162 status_t result = mOutput->stream->resume();
7163 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007164 }
Eric Laurent81784c32012-11-19 14:55:58 -08007165 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007166 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007167
7168 return mixerStatus;
7169}
7170
Andy Hungee58e4a2023-07-07 13:47:37 -07007171void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007172{
Eric Laurent81784c32012-11-19 14:55:58 -08007173 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007174 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007175 // output audio to hardware
7176 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007177 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007178 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007179 status_t status = mActiveTrack->getNextBuffer(&buffer);
7180 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007181 // no need to pad with 0 for compressed audio
7182 if (audio_has_proportional_frames(mFormat)) {
7183 memset(curBuf, 0, frameCount * mFrameSize);
7184 }
Eric Laurent81784c32012-11-19 14:55:58 -08007185 break;
7186 }
7187 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7188 frameCount -= buffer.frameCount;
7189 curBuf += buffer.frameCount * mFrameSize;
7190 mActiveTrack->releaseBuffer(&buffer);
7191 }
Andy Hung2098f272014-02-27 14:00:06 -08007192 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007193 mSleepTimeUs = 0;
7194 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007195 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007196}
7197
Andy Hungee58e4a2023-07-07 13:47:37 -07007198void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007199{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007200 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007201 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007202 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007203 return;
7204 }
Andy Hung85ba3332021-04-27 17:40:26 -07007205 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7206 mSleepTimeUs = mActiveSleepTimeUs;
7207 } else {
7208 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007209 }
Andy Hung85ba3332021-04-27 17:40:26 -07007210 // Note: In S or later, we do not write zeroes for
7211 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007212}
7213
Andy Hungee58e4a2023-07-07 13:47:37 -07007214void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007215{
7216 {
Andy Hung972bec12023-08-31 16:13:39 -07007217 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007218 for (size_t i = 0; i < mTracks.size(); i++) {
7219 if (mTracks[i]->isFlushPending()) {
7220 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007221 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007222 }
7223 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007224 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007225 flushHw_l();
7226 }
7227 }
7228 PlaybackThread::threadLoop_exit();
7229}
7230
7231// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007232bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007233{
7234 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007235 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007236 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007237
Eric Laurent022a5132024-04-12 17:02:51 +00007238 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007239 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007240 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007241 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007242 const auto& mainTrack = mTracks[mTracks.size() - 1];
7243
7244 trackPaused = mainTrack->isPaused();
7245 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7246 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007247 }
7248
Eric Laurent022a5132024-04-12 17:02:51 +00007249 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007250}
7251
Andy Hungc5007f82023-08-29 14:26:09 -07007252// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007253bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007254 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007255{
7256 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007257 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007258
Eric Laurent10351942014-05-08 18:49:52 -07007259 AudioParameter param = AudioParameter(keyValuePair);
7260 int value;
7261 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007262 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007263 }
Eric Laurent10351942014-05-08 18:49:52 -07007264 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7265 // do not accept frame count changes if tracks are open as the track buffer
7266 // size depends on frame count and correct behavior would not be garantied
7267 // if frame count is changed after track creation
7268 if (!mTracks.isEmpty()) {
7269 status = INVALID_OPERATION;
7270 } else {
7271 reconfig = true;
7272 }
7273 }
7274 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007275 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007276 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007277 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007278 if (!mStandby) {
7279 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007280 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007281 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007282 }
Eric Laurent10351942014-05-08 18:49:52 -07007283 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007284 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007285 }
7286 if (status == NO_ERROR && reconfig) {
7287 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007288 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007289 }
7290 }
7291
Dean Wheatley68918102021-03-19 22:09:19 +11007292 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007293}
7294
Andy Hungee58e4a2023-07-07 13:47:37 -07007295uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007296{
7297 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007298 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007299 time = PlaybackThread::activeSleepTimeUs();
7300 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007301 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007302 }
7303 return time;
7304}
7305
Andy Hungee58e4a2023-07-07 13:47:37 -07007306uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007307{
7308 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007309 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007310 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7311 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007312 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007313 }
7314 return time;
7315}
7316
Andy Hungee58e4a2023-07-07 13:47:37 -07007317uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007318{
7319 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007320 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007321 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7322 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007323 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007324 }
7325 return time;
7326}
7327
Andy Hungee58e4a2023-07-07 13:47:37 -07007328void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007329{
7330 PlaybackThread::cacheParameters_l();
7331
7332 // use shorter standby delay as on normal output to release
7333 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007334 // no delay on outputs with HW A/V sync
7335 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007336 mStandbyDelayNs = 0;
Andy Hunge8273252024-08-07 16:42:42 -07007337 } else if (mType == OFFLOAD) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007338 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007339 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007340 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007341 }
Eric Laurent81784c32012-11-19 14:55:58 -08007342}
7343
Andy Hungee58e4a2023-07-07 13:47:37 -07007344void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007345{
ziyangch8f194f12021-12-01 13:48:04 -08007346 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007347 mOutput->flush();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007348 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007349 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007350 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007351 mMonotonicFrameCounter.onFlush();
Haofan Wang0770bc82024-10-03 17:37:55 +00007352 // We do not reset mHwPaused which is hidden from the Track client.
7353 // Note: the client track in Tracks.cpp and AudioTrack.cpp
7354 // has a FLUSHED state but the DirectOutputThread does not;
7355 // those tracks will continue to show isStopped().
Eric Laurente659ef42014-09-29 13:06:46 -07007356}
7357
Andy Hungee58e4a2023-07-07 13:47:37 -07007358int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007359 // If a VolumeShaper is active, we must wake up periodically to update volume.
7360 const int64_t NS_PER_MS = 1000000;
7361 return mVolumeShaperActive ?
7362 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7363}
7364
Eric Laurent81784c32012-11-19 14:55:58 -08007365// ----------------------------------------------------------------------------
7366
Andy Hungee58e4a2023-07-07 13:47:37 -07007367AsyncCallbackThread::AsyncCallbackThread(
7368 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007369 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007370 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007371 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007372 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007373 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007374{
7375}
7376
Andy Hungee58e4a2023-07-07 13:47:37 -07007377void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007378{
7379 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7380}
7381
Andy Hungee58e4a2023-07-07 13:47:37 -07007382bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007383{
7384 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007385 uint32_t writeAckSequence;
7386 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007387 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007388
7389 {
Andy Hungc5007f82023-08-29 14:26:09 -07007390 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007391 while (!((mWriteAckSequence & 1) ||
7392 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007393 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007394 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007395 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007396 }
7397
Eric Laurentbfb1b832013-01-07 09:53:42 -08007398 if (exitPending()) {
7399 break;
7400 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007401 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7402 mWriteAckSequence, mDrainSequence);
7403 writeAckSequence = mWriteAckSequence;
7404 mWriteAckSequence &= ~1;
7405 drainSequence = mDrainSequence;
7406 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007407 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007408 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007409 }
7410 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007411 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007412 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007413 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007414 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007415 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007416 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007417 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007418 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007419 if (asyncError != ASYNC_ERROR_NONE) {
7420 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007421 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007422 }
7423 }
7424 }
7425 return false;
7426}
7427
Andy Hungee58e4a2023-07-07 13:47:37 -07007428void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007429{
7430 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007431 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007432 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007433 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007434}
7435
Andy Hungee58e4a2023-07-07 13:47:37 -07007436void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007437{
Andy Hung972bec12023-08-31 16:13:39 -07007438 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007439 // bit 0 is cleared
7440 mWriteAckSequence = sequence << 1;
7441}
7442
Andy Hungee58e4a2023-07-07 13:47:37 -07007443void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007444{
Andy Hung972bec12023-08-31 16:13:39 -07007445 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007446 // ignore unexpected callbacks
7447 if (mWriteAckSequence & 2) {
7448 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007449 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007450 }
7451}
7452
Andy Hungee58e4a2023-07-07 13:47:37 -07007453void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007454{
Andy Hung972bec12023-08-31 16:13:39 -07007455 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007456 // bit 0 is cleared
7457 mDrainSequence = sequence << 1;
7458}
7459
Andy Hungee58e4a2023-07-07 13:47:37 -07007460void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007461{
Andy Hung972bec12023-08-31 16:13:39 -07007462 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007463 // ignore unexpected callbacks
7464 if (mDrainSequence & 2) {
7465 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007466 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007467 }
7468}
7469
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007470void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007471{
Andy Hung972bec12023-08-31 16:13:39 -07007472 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007473 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007474 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007475}
7476
Eric Laurentbfb1b832013-01-07 09:53:42 -08007477
7478// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007479
7480/* static */
7481sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007482 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007483 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7484 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007485 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007486}
7487
Andy Hung583043b2023-07-17 17:05:00 -07007488OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007489 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7490 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007491 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007492 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007493{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007494 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007495 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007496 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007497}
7498
Andy Hungee58e4a2023-07-07 13:47:37 -07007499void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007500{
7501 if (mFlushPending || mHwPaused) {
7502 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007503 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007504 flushHw_l();
7505 } else {
7506 mMixerStatus = MIXER_DRAIN_ALL;
7507 threadLoop_drain();
7508 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007509 if (mUseAsyncWrite) {
7510 ALOG_ASSERT(mCallbackThread != 0);
7511 mCallbackThread->exit();
7512 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007513 PlaybackThread::threadLoop_exit();
7514}
7515
Andy Hungee58e4a2023-07-07 13:47:37 -07007516PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007517 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007518)
7519{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007520 size_t count = mActiveTracks.size();
7521
7522 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007523 bool doHwPause = false;
7524 bool doHwResume = false;
7525
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007526 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007527
Eric Laurentbfb1b832013-01-07 09:53:42 -08007528 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007529 for (const sp<IAfTrack>& t : mActiveTracks) {
7530 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007531#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007532 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007533#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007534 // Only consider last track started for volume and mixer state control.
7535 // In theory an older track could underrun and restart after the new one starts
7536 // but as we only care about the transition phase between two tracks on a
7537 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007538 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007539 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007540
Haynes Mathew George7844f672014-01-15 12:32:55 -08007541 if (track->isInvalid()) {
7542 ALOGW("An invalidated track shouldn't be in active list");
7543 tracksToRemove->add(track);
7544 continue;
7545 }
7546
Andy Hung8d31fd22023-06-26 19:20:57 -07007547 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007548 ALOGW("An idle track shouldn't be in active list");
7549 continue;
7550 }
7551
Andy Hungf767de02024-10-30 19:47:50 -07007552 const size_t framesReady = track->framesReady();
7553 if (ATRACE_ENABLED()) [[unlikely]] {
7554 ATRACE_INT(std::string(AUDIO_TRACE_PREFIX_AUDIO_TRACK_NRDY)
7555 .append(track->getTraceSuffix()).c_str(), framesReady);
7556 }
Kuowei Li23666472021-01-20 10:23:25 +08007557 if (track->isPausePending()) {
7558 track->pauseAck();
7559 // It is possible a track might have been flushed or stopped.
7560 // Other operations such as flush pending might occur on the next prepare.
7561 if (track->isPausing()) {
7562 track->setPaused();
7563 }
7564 // Always perform pause if last, as an immediate flush will change
7565 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007566 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007567 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007568 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007569 mHwPaused = true;
7570 }
7571 // If we were part way through writing the mixbuffer to
7572 // the HAL we must save this until we resume
7573 // BUG - this will be wrong if a different track is made active,
7574 // in that case we want to discard the pending data in the
7575 // mixbuffer and tell the client to present it again when the
7576 // track is resumed
7577 mPausedWriteLength = mCurrentWriteLength;
7578 mPausedBytesRemaining = mBytesRemaining;
7579 mBytesRemaining = 0; // stop writing
7580 }
7581 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007582 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007583 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007584 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007585 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007586 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007587 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007588 track->flushAck();
7589 if (last) {
7590 mFlushPending = true;
7591 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007592 } else if (track->isResumePending()){
7593 track->resumeAck();
7594 if (last) {
7595 if (mPausedBytesRemaining) {
7596 // Need to continue write that was interrupted
7597 mCurrentWriteLength = mPausedWriteLength;
7598 mBytesRemaining = mPausedBytesRemaining;
7599 mPausedBytesRemaining = 0;
7600 }
7601 if (mHwPaused) {
7602 doHwResume = true;
7603 mHwPaused = false;
7604 // threadLoop_mix() will handle the case that we need to
7605 // resume an interrupted write
7606 }
7607 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007608 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007609
Eric Laurent3df841a2016-07-15 15:15:40 -07007610 mLeftVolFloat = mRightVolFloat = -1.0;
7611
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007612 // Do not handle new data in this iteration even if track->framesReady()
7613 mixerStatus = MIXER_TRACKS_ENABLED;
7614 }
Andy Hungf767de02024-10-30 19:47:50 -07007615 } else if (framesReady && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007616 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007617 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007618 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7619 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007620 if (last) {
7621 // make sure processVolume_l() will apply new volume even if 0
7622 mLeftVolFloat = mRightVolFloat = -1.0;
7623 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007624 }
7625
7626 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007627 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007628 if (previousTrack != 0) {
7629 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007630 // Flush any data still being written from last track
7631 mBytesRemaining = 0;
7632 if (mPausedBytesRemaining) {
7633 // Last track was paused so we also need to flush saved
7634 // mixbuffer state and invalidate track so that it will
7635 // re-submit that unwritten data when it is next resumed
7636 mPausedBytesRemaining = 0;
7637 // Invalidate is a bit drastic - would be more efficient
7638 // to have a flag to tell client that some of the
7639 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007640 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007641 }
7642 // flush data already sent to the DSP if changing audio session as audio
7643 // comes from a different source. Also invalidate previous track to force a
7644 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007645 if (previousTrack->sessionId() != track->sessionId()) {
7646 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007647 }
7648 }
7649 }
7650 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007651 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007652 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007653 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007654 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007655 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007656 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007657 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007658 mixerStatus = MIXER_TRACKS_READY;
7659 }
7660 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007661 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007662 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007663 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007664 // Hardware buffer can hold a large amount of audio so we must
7665 // wait for all current track's data to drain before we say
7666 // that the track is stopped.
7667 if (mBytesRemaining == 0) {
7668 // Only start draining when all data in mixbuffer
7669 // has been written
7670 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007671 track->setState(IAfTrackBase::STOPPING_2);
7672 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007673 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7674 if (last && !mStandby) {
7675 // do not modify drain sequence if we are already draining. This happens
7676 // when resuming from pause after drain.
7677 if ((mDrainSequence & 1) == 0) {
7678 mSleepTimeUs = 0;
7679 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7680 mixerStatus = MIXER_DRAIN_TRACK;
7681 mDrainSequence += 2;
7682 }
7683 if (mHwPaused) {
7684 // It is possible to move from PAUSED to STOPPING_1 without
7685 // a resume so we must ensure hardware is running
7686 doHwResume = true;
7687 mHwPaused = false;
7688 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007689 }
7690 }
Eric Laurente93cc032016-05-05 10:15:10 -07007691 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007692 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007693 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007694 }
7695 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007696 // Drain has completed or we are in standby, signal presentation complete
7697 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007698 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007699 mOutput->presentationComplete();
7700 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007701 track->reset();
7702 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007703 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007704 if (!mUseAsyncWrite) {
7705 // If we don't get explicit drain notification we must
7706 // register discontinuity regardless of whether this is
7707 // the previous (!last) or the upcoming (last) track
7708 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007709 mTimestampVerifier.discontinuity(
7710 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007711 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007712 }
7713 } else {
7714 // No buffers for this track. Give it a few chances to
7715 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007716 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007717 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007718 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007719 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007720 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007721 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007722 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7723 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007724 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007725 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007726 // it will then automatically call start() when data is available
7727 track->disable();
7728 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007729 } else if (last){
7730 mixerStatus = MIXER_TRACKS_ENABLED;
7731 }
7732 }
7733 }
7734 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007735 if (track->isReady()) { // check ready to prevent premature start.
7736 processVolume_l(track, last);
7737 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007738 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007739
Eric Laurentea0fade2013-10-04 16:23:48 -07007740 // make sure the pause/flush/resume sequence is executed in the right order.
7741 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7742 // before flush and then resume HW. This can happen in case of pause/flush/resume
7743 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007744 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007745 status_t result = mOutput->stream->pause();
7746 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007747 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007748 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007749 if (mFlushPending) {
7750 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007751 }
Eric Laurentfd477972013-10-25 18:10:40 -07007752 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007753 status_t result = mOutput->stream->resume();
7754 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007755 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007756
Eric Laurentbfb1b832013-01-07 09:53:42 -08007757 // remove all the tracks that need to be...
7758 removeTracks_l(*tracksToRemove);
7759
7760 return mixerStatus;
7761}
7762
Eric Laurentbfb1b832013-01-07 09:53:42 -08007763// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007764bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007765{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007766 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7767 mWriteAckSequence, mDrainSequence);
7768 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007769 return true;
7770 }
7771 return false;
7772}
7773
Andy Hungee58e4a2023-07-07 13:47:37 -07007774bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007775{
Andy Hung972bec12023-08-31 16:13:39 -07007776 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007777 return waitingAsyncCallback_l();
7778}
7779
Andy Hungee58e4a2023-07-07 13:47:37 -07007780void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007781{
Eric Laurente659ef42014-09-29 13:06:46 -07007782 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007783 // Flush anything still waiting in the mixbuffer
7784 mCurrentWriteLength = 0;
7785 mBytesRemaining = 0;
7786 mPausedWriteLength = 0;
7787 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007788 // reset bytes written count to reflect that DSP buffers are empty after flush.
7789 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007790
Eric Laurentbfb1b832013-01-07 09:53:42 -08007791 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007792 // discard any pending drain or write ack by incrementing sequence
7793 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7794 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007795 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007796 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7797 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007798 }
7799}
7800
Andy Hungee58e4a2023-07-07 13:47:37 -07007801void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007802{
Andy Hung972bec12023-08-31 16:13:39 -07007803 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007804 if (PlaybackThread::invalidateTracks_l(streamType)) {
7805 mFlushPending = true;
7806 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007807}
7808
Andy Hungee58e4a2023-07-07 13:47:37 -07007809void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007810 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007811 if (PlaybackThread::invalidateTracks_l(portIds)) {
7812 mFlushPending = true;
7813 }
7814}
7815
Eric Laurentbfb1b832013-01-07 09:53:42 -08007816// ----------------------------------------------------------------------------
7817
Andy Hungee58e4a2023-07-07 13:47:37 -07007818/* static */
7819sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007820 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007821 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007822 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007823}
7824
Andy Hung583043b2023-07-17 17:05:00 -07007825DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007826 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007827 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007828 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007829 mWaitTimeMs(UINT_MAX)
7830{
7831 addOutputTrack(mainThread);
7832}
7833
Andy Hungee58e4a2023-07-07 13:47:37 -07007834DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007835{
7836 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7837 mOutputTracks[i]->destroy();
7838 }
7839}
7840
Andy Hungee58e4a2023-07-07 13:47:37 -07007841void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007842{
7843 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007844 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007845 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007846 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007847 if (mMixerBufferValid) {
7848 memset(mMixerBuffer, 0, mMixerBufferSize);
7849 } else {
7850 memset(mSinkBuffer, 0, mSinkBufferSize);
7851 }
Eric Laurent81784c32012-11-19 14:55:58 -08007852 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007853 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007854 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007855 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007856 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007857}
7858
Andy Hungee58e4a2023-07-07 13:47:37 -07007859void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007860{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007861 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007862 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007863 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007864 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007865 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007866 }
7867 } else if (mBytesWritten != 0) {
7868 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7869 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007870 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007871 } else {
7872 // flush remaining overflow buffers in output tracks
7873 writeFrames = 0;
7874 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007875 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007876 }
7877}
7878
Andy Hungee58e4a2023-07-07 13:47:37 -07007879ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007880{
Jiabin Huang4d0c9e82024-10-28 21:51:36 +00007881 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08007882 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007883 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7884
7885 // Consider the first OutputTrack for timestamp and frame counting.
7886
7887 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7888 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7889 // we always claim success.
7890 if (i == 0) {
7891 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7892 ALOGD_IF(correction != 0 && writeFrames != 0,
7893 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7894 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7895 mFramesWritten -= correction;
7896 }
7897
7898 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007899 }
Jiabin Huang4d0c9e82024-10-28 21:51:36 +00007900 ATRACE_END();
Andy Hungcf10d742020-04-28 15:38:24 -07007901 if (mStandby) {
7902 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007903 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007904 mStandby = false;
7905 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007906 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007907}
7908
Andy Hungee58e4a2023-07-07 13:47:37 -07007909void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007910{
7911 // DuplicatingThread implements standby by stopping all tracks
7912 for (size_t i = 0; i < outputTracks.size(); i++) {
7913 outputTracks[i]->stop();
7914 }
7915}
7916
Andy Hung8a5abfd2023-12-07 19:35:12 -08007917void DuplicatingThread::threadLoop_exit()
7918{
7919 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7920 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7921 // Do so here in the threadLoop_exit().
7922
7923 SortedVector <sp<IAfOutputTrack>> localTracks;
7924 {
7925 audio_utils::lock_guard l(mutex());
7926 localTracks = std::move(mOutputTracks);
7927 mOutputTracks.clear();
jiabinc62d6032024-09-03 23:39:57 +00007928 for (size_t i = 0; i < localTracks.size(); ++i) {
7929 localTracks[i]->destroy();
7930 }
Andy Hung8a5abfd2023-12-07 19:35:12 -08007931 }
7932 localTracks.clear();
7933 outputTracks.clear();
7934 PlaybackThread::threadLoop_exit();
7935}
7936
Andy Hungee58e4a2023-07-07 13:47:37 -07007937void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007938{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007939 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007940
7941 std::stringstream ss;
7942 const size_t numTracks = mOutputTracks.size();
7943 ss << " " << numTracks << " OutputTracks";
7944 if (numTracks > 0) {
7945 ss << ":";
7946 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007947 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007948 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007949 if (thread.get() != nullptr) {
7950 ss << thread.get() << ", " << thread->id();
7951 } else {
7952 ss << "null";
7953 }
7954 ss << ")";
7955 }
7956 }
7957 ss << "\n";
7958 std::string result = ss.str();
7959 write(fd, result.c_str(), result.size());
7960}
7961
Andy Hungee58e4a2023-07-07 13:47:37 -07007962void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007963{
7964 outputTracks = mOutputTracks;
7965}
7966
Andy Hungee58e4a2023-07-07 13:47:37 -07007967void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007968{
7969 outputTracks.clear();
7970}
7971
Andy Hungee58e4a2023-07-07 13:47:37 -07007972void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007973{
Andy Hung972bec12023-08-31 16:13:39 -07007974 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007975 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7976 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7977 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7978 const size_t frameCount =
7979 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7980 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7981 // from different OutputTracks and their associated MixerThreads (e.g. one may
7982 // nearly empty and the other may be dropping data).
7983
Svet Ganov33761132021-05-13 22:51:08 +00007984 // TODO b/182392769: use attribution source util, move to server edge
7985 AttributionSourceState attributionSource = AttributionSourceState();
7986 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007987 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007988 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007989 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007990 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007991 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007992 this,
7993 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007994 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007995 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007996 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007997 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007998 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7999 if (status != NO_ERROR) {
8000 ALOGE("addOutputTrack() initCheck failed %d", status);
8001 return;
Eric Laurent81784c32012-11-19 14:55:58 -08008002 }
Andy Hung6b137d12024-08-27 22:35:17 +00008003 if (!audioserver_flags::portid_volume_management()) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008004 thread->setStreamVolume(AUDIO_STREAM_PATCH, /*volume=*/1.0f, /*muted=*/false);
Andy Hung6b137d12024-08-27 22:35:17 +00008005 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008006
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07008007 mOutputTracks.add(outputTrack);
8008 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
8009 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008010}
8011
Andy Hungee58e4a2023-07-07 13:47:37 -07008012void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08008013{
Andy Hung972bec12023-08-31 16:13:39 -07008014 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08008015 for (size_t i = 0; i < mOutputTracks.size(); i++) {
8016 if (mOutputTracks[i]->thread() == thread) {
8017 mOutputTracks[i]->destroy();
8018 mOutputTracks.removeAt(i);
8019 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07008020 // NO_THREAD_SAFETY_ANALYSIS
8021 // Lambda workaround: as thread != this
8022 // we can safely call the remote thread getOutput.
8023 const bool equalOutput =
8024 [&](){ return thread->getOutput() == mOutput; }();
8025 if (equalOutput) {
8026 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07008027 }
Eric Laurent81784c32012-11-19 14:55:58 -08008028 return;
8029 }
8030 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07008031 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08008032}
8033
Andy Hungc5007f82023-08-29 14:26:09 -07008034// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07008035void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008036{
Jiabin Huang48e8f0c2024-10-29 00:03:42 +00008037 // Initialize mWaitTimeMs according to the mixer buffer size.
8038 mWaitTimeMs = mNormalFrameCount * 2 * 1000 / mSampleRate;
Eric Laurent81784c32012-11-19 14:55:58 -08008039 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07008040 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008041 if (strong != 0) {
8042 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
8043 if (waitTimeMs < mWaitTimeMs) {
8044 mWaitTimeMs = waitTimeMs;
8045 }
8046 }
8047 }
8048}
8049
Andy Hungee58e4a2023-07-07 13:47:37 -07008050bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08008051{
8052 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07008053 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008054 if (thread == 0) {
8055 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
8056 outputTracks[i].get());
8057 return false;
8058 }
Andy Hung87c693c2023-07-06 20:56:16 -07008059 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08008060 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07008061 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08008062 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
8063 thread.get());
8064 return false;
8065 }
8066 }
8067 return true;
8068}
8069
Andy Hungee58e4a2023-07-07 13:47:37 -07008070void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07008071 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07008072{
Kevin Rocard12381092018-04-11 09:19:59 -07008073 for (auto& outputTrack : outputTracks) { // not mOutputTracks
8074 outputTrack->setMetadatas(metadata.tracks);
8075 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008076}
8077
Andy Hungee58e4a2023-07-07 13:47:37 -07008078uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08008079{
Andy Hung7a6a0f02023-11-29 13:42:08 -08008080 // return half the wait time in microseconds.
8081 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08008082}
8083
Andy Hungee58e4a2023-07-07 13:47:37 -07008084void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008085{
8086 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
8087 updateWaitTime_l();
8088
8089 MixerThread::cacheParameters_l();
8090}
8091
Eric Laurentb3f315a2021-07-13 15:09:05 +02008092// ----------------------------------------------------------------------------
8093
Andy Hungee58e4a2023-07-07 13:47:37 -07008094/* static */
8095sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07008096 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07008097 AudioStreamOut* output,
8098 audio_io_handle_t id,
8099 bool systemReady,
8100 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07008101 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07008102}
8103
Andy Hung583043b2023-07-17 17:05:00 -07008104SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02008105 AudioStreamOut* output,
8106 audio_io_handle_t id,
8107 bool systemReady,
8108 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07008109 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02008110{
8111}
8112
Andy Hungee58e4a2023-07-07 13:47:37 -07008113void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02008114 // if mSupportedLatencyModes is empty, the HAL stream does not support
8115 // latency mode control and we can exit.
8116 if (mSupportedLatencyModes.empty()) {
8117 return;
8118 }
Eric Laurent4c85e372024-02-23 16:50:06 +00008119 // Do not update the HAL latency mode if no track is active
8120 if (mActiveTracks.isEmpty()) {
8121 return;
8122 }
8123
Eric Laurent68a40a82022-05-03 18:15:04 +02008124 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
8125 if (mSupportedLatencyModes.size() == 1) {
8126 // If the HAL only support one latency mode currently, confirm the choice
8127 latencyMode = mSupportedLatencyModes[0];
8128 } else if (mSupportedLatencyModes.size() > 1) {
8129 // Request low latency if:
8130 // - The low latency mode is requested by the spatializer controller
8131 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
8132 // AND
8133 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02008134 for (const auto& track : mActiveTracks) {
8135 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01008136 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02008137 break;
8138 }
8139 }
Eric Laurent68a40a82022-05-03 18:15:04 +02008140 }
8141
8142 if (latencyMode != mSetLatencyMode) {
8143 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08008144 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
8145 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02008146 if (status == NO_ERROR) {
8147 mSetLatencyMode = latencyMode;
8148 }
8149 }
8150}
8151
Andy Hungee58e4a2023-07-07 13:47:37 -07008152status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008153 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008154 return BAD_VALUE;
8155 }
Andy Hung972bec12023-08-31 16:13:39 -07008156 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008157 mRequestedLatencyMode = mode;
8158 return NO_ERROR;
8159}
8160
Andy Hungee58e4a2023-07-07 13:47:37 -07008161void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008162NO_THREAD_SAFETY_ANALYSIS
8163// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008164{
8165 bool hasVirtualizer = false;
8166 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008167 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008168 {
Andy Hung972bec12023-08-31 16:13:39 -07008169 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008170 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008171 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008172 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008173 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8174 }
8175
8176 finalDownMixer = mFinalDownMixer;
8177 mFinalDownMixer.clear();
8178 }
8179
8180 if (hasVirtualizer) {
8181 if (finalDownMixer != nullptr) {
8182 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008183 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008184 }
8185 finalDownMixer.clear();
8186 } else if (!hasDownMixer) {
8187 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008188 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008189 EFFECT_UIID_DOWNMIX, &descriptors);
8190 if (status != NO_ERROR) {
8191 return;
8192 }
8193 ALOG_ASSERT(!descriptors.empty(),
8194 "%s getDescriptors() returned no error but empty list", __func__);
8195
8196 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8197 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008198 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008199
8200 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8201 ALOGW("%s error creating downmixer %d", __func__, status);
8202 finalDownMixer.clear();
8203 } else {
8204 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008205 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008206 }
8207 }
8208
8209 {
Andy Hung972bec12023-08-31 16:13:39 -07008210 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008211 mFinalDownMixer = finalDownMixer;
8212 }
8213}
8214
Andy Hunge2514462023-12-06 14:59:24 -08008215void SpatializerThread::threadLoop_exit()
8216{
8217 // The Spatializer EffectHandle must be released on the PlaybackThread
8218 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8219 mFinalDownMixer.clear();
8220
8221 PlaybackThread::threadLoop_exit();
8222}
8223
Eric Laurent81784c32012-11-19 14:55:58 -08008224// ----------------------------------------------------------------------------
8225// Record
8226// ----------------------------------------------------------------------------
8227
Andy Hung583043b2023-07-17 17:05:00 -07008228sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008229 AudioStreamIn* input,
8230 audio_io_handle_t id,
8231 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008232 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008233}
8234
Andy Hung583043b2023-07-17 17:05:00 -07008235RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008236 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008237 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008238 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008239 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008240 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008241 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008242 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008243 mActiveTracks(&this->mLocalLog),
8244 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008245 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008246 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008247 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8248 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008249 // mFastCapture below
8250 , mFastCaptureFutex(0)
8251 // mInputSource
8252 // mPipeSink
8253 // mPipeSource
8254 , mPipeFramesP2(0)
8255 // mPipeMemory
8256 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008257 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008258 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008259{
Glenn Kastend7dca052015-03-05 16:05:54 -08008260 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hungf767de02024-10-30 19:47:50 -07008261 mFlagsAsString = toString(input->flags);
Andy Hung583043b2023-07-17 17:05:00 -07008262 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008263
George Burgess IVa8f90c12020-05-14 11:27:19 -07008264 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008265 mIsMsdDevice = strcmp(
8266 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8267 }
8268
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008269 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008270
Andy Hungc8fddf32018-08-08 18:32:37 -07008271 // TODO: We may also match on address as well as device type for
8272 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008273 // TODO: This property should be ensure that only contains one single device type.
8274 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8275 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008276 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8277 : AUDIO_DEVICE_NONE));
8278
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008279 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008280 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008281 size_t numCounterOffers = 0;
8282 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008283#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008284 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008285#else
8286 (void)
8287#endif
8288 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008289 ALOG_ASSERT(index == 0);
8290
8291 // initialize fast capture depending on configuration
8292 bool initFastCapture;
8293 switch (kUseFastCapture) {
8294 case FastCapture_Never:
8295 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008296 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008297 break;
8298 case FastCapture_Always:
8299 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008300 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008301 break;
8302 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008303 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008304 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008305 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008306 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8307 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8308 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008309 break;
8310 // case FastCapture_Dynamic:
8311 }
8312
8313 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008314 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008315 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008316 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8317 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008318 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008319 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008320 const sp<MemoryDealer> roHeap(readOnlyHeap());
8321 sp<IMemory> pipeMemory;
8322 if ((roHeap == 0) ||
8323 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008324 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008325 ALOGE("not enough memory for pipe buffer size=%zu; "
8326 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8327 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8328 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008329 goto failed;
8330 }
8331 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8332 memset(pipeBuffer, 0, pipeSize);
8333 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008334 const NBAIO_Format offersFast[1] = {format};
8335 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008336 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008337 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008338 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008339 mPipeSink = pipe;
8340 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008341 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008342 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008343 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008344 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008345 mPipeSource = pipeReader;
8346 mPipeFramesP2 = pipeFramesP2;
8347 mPipeMemory = pipeMemory;
8348
8349 // create fast capture
8350 mFastCapture = new FastCapture();
8351 FastCaptureStateQueue *sq = mFastCapture->sq();
8352#ifdef STATE_QUEUE_DUMP
8353 // FIXME
8354#endif
8355 FastCaptureState *state = sq->begin();
8356 state->mCblk = NULL;
8357 state->mInputSource = mInputSource.get();
8358 state->mInputSourceGen++;
8359 state->mPipeSink = pipe;
8360 state->mPipeSinkGen++;
8361 state->mFrameCount = mFrameCount;
8362 state->mCommand = FastCaptureState::COLD_IDLE;
8363 // already done in constructor initialization list
8364 //mFastCaptureFutex = 0;
8365 state->mColdFutexAddr = &mFastCaptureFutex;
8366 state->mColdGen++;
8367 state->mDumpState = &mFastCaptureDumpState;
8368#ifdef TEE_SINK
8369 // FIXME
8370#endif
Andy Hung583043b2023-07-17 17:05:00 -07008371 mFastCaptureNBLogWriter =
8372 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008373 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8374 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07008375 {
8376 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastCapture->getTid());
8377 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8378 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008379 // start the fast capture
8380 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8381 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008382 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008383 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008384#ifdef AUDIO_WATCHDOG
8385 // FIXME
8386#endif
8387
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008388 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008389 }
Andy Hung8946a282018-04-19 20:04:56 -07008390#ifdef TEE_SINK
8391 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8392 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8393#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008394failed: ;
8395
8396 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008397}
8398
Andy Hungee58e4a2023-07-07 13:47:37 -07008399RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008400{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008401 if (mFastCapture != 0) {
8402 FastCaptureStateQueue *sq = mFastCapture->sq();
8403 FastCaptureState *state = sq->begin();
8404 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8405 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8406 if (old == -1) {
8407 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8408 }
8409 }
8410 state->mCommand = FastCaptureState::EXIT;
8411 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07008412 {
8413 audio_utils::mutex::scoped_join_wait_check queueWaitCheck(mFastCapture->getTid());
8414 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8415 mFastCapture->join();
8416 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008417 mFastCapture.clear();
8418 }
Andy Hung583043b2023-07-17 17:05:00 -07008419 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8420 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008421 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008422}
8423
Andy Hungee58e4a2023-07-07 13:47:37 -07008424void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008425{
Glenn Kastend7dca052015-03-05 16:05:54 -08008426 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008427}
8428
Andy Hungee58e4a2023-07-07 13:47:37 -07008429void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008430{
8431 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008432 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008433 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008434 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008435 track->invalidate();
8436 }
8437 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008438 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008439}
8440
Andy Hungee58e4a2023-07-07 13:47:37 -07008441bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008442{
Eric Laurent81784c32012-11-19 14:55:58 -08008443 nsecs_t lastWarning = 0;
8444
8445 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008446
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008447reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008448 {
Andy Hung972bec12023-08-31 16:13:39 -07008449 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008450 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008451 }
8452
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008453 // used to request a deferred sleep, to be executed later while mutex is unlocked
8454 uint32_t sleepUs = 0;
8455
Andy Hung95c94a22023-10-20 16:41:18 -07008456 // timestamp correction enable is determined under lock, used in processing step.
8457 bool timestampCorrectionEnabled = false;
8458
Andy Hung446f4df2019-02-21 12:26:41 -08008459 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8460
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008461 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008462 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008463 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8464 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008465 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008466 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008467
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008468 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008469 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008470
Glenn Kasten735f45f2014-08-18 15:51:59 -07008471 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008472 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008473
Glenn Kasten735f45f2014-08-18 15:51:59 -07008474 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008475 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008476
Eric Laurent33403f02020-05-29 18:35:06 -07008477 bool silenceFastCapture = false;
8478
Andy Hungc5007f82023-08-29 14:26:09 -07008479 { // scope for mutex()
8480 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008481
Eric Laurent021cf962014-05-13 10:18:14 -07008482 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008483
Eric Laurent000a4192014-01-29 15:17:32 -08008484 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008485 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008486 if (exitPending()) {
8487 break;
8488 }
8489
Eric Laurent5c25d562016-07-13 17:17:45 -07008490 // sleep with mutex unlocked
8491 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008492 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008493 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008494 ATRACE_END();
8495 sleepUs = 0;
8496 continue;
8497 }
8498
Glenn Kasten2b806402013-11-20 16:37:38 -08008499 // if no active track(s), then standby and release wakelock
8500 size_t size = mActiveTracks.size();
8501 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008502 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008503 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008504 releaseWakeLock_l();
8505 ALOGV("RecordThread: loop stopping");
8506 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008507 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008508 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008509 goto reacquire_wakelock;
8510 }
8511
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008512 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008513 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008514 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008515 if (activeTrack) { // ensure track release is outside lock.
8516 oldActiveTracks.emplace_back(std::move(activeTrack));
8517 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008518 activeTrack = mActiveTracks[i];
8519 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008520 if (activeTrack->isFastTrack()) {
8521 ALOG_ASSERT(fastTrackToRemove == 0);
8522 fastTrackToRemove = activeTrack;
8523 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008524 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008525 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008526 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008527 continue;
8528 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008529
Andy Hung8d31fd22023-06-26 19:20:57 -07008530 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008531 switch (activeTrackState) {
8532
Andy Hung8d31fd22023-06-26 19:20:57 -07008533 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008534 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008535 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008536 if (activeTrack->isFastTrack()) {
8537 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8538 // Keep a ref on fast track to wait for FastCapture thread to get updated
8539 // state before potential track removal
8540 fastTrackToRemove = activeTrack;
8541 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008542 doBroadcast = true;
8543 size--;
8544 continue;
8545
Andy Hung8d31fd22023-06-26 19:20:57 -07008546 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008547 sleepUs = 10000;
8548 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008549 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008550 continue;
8551
Andy Hung8d31fd22023-06-26 19:20:57 -07008552 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008553 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008554 if (mStandby) {
8555 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008556 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008557 mStandby = false;
8558 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008559 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008560 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008561 break;
8562
Andy Hung8d31fd22023-06-26 19:20:57 -07008563 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008564 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008565 break;
8566
Andy Hung8d31fd22023-06-26 19:20:57 -07008567 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8568 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8569 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008570 default:
Andy Hungce685402018-10-05 17:23:27 -07008571 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8572 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008573 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008574
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008575 if (activeTrack->isFastTrack()) {
8576 ALOG_ASSERT(!mFastTrackAvail);
8577 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008578 // if the active fast track is silenced either:
8579 // 1) silence the whole capture from fast capture buffer if this is
8580 // the only active track
8581 // 2) invalidate this track: this will cause the client to reconnect and possibly
8582 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008583 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008584 if (activeTrack->isSilenced()) {
8585 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008586 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008587 } else {
8588 silenceFastCapture = true;
8589 }
8590 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008591 // Invalidate fast tracks if access to audio history is required as this is not
8592 // possible with fast tracks. Once the fast track has been invalidated, no new
8593 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8594 if (mMaxSharedAudioHistoryMs != 0) {
8595 invalidate = true;
8596 }
8597 if (invalidate) {
8598 activeTrack->invalidate();
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008599 fastTrackToRemove = activeTrack;
8600 removeTrack_l(activeTrack);
8601 mActiveTracks.remove(activeTrack);
8602 size--;
8603 continue;
8604 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008605 fastTrack = activeTrack;
8606 }
Eric Laurent33403f02020-05-29 18:35:06 -07008607
8608 activeTracks.add(activeTrack);
8609 i++;
8610
Glenn Kasten9e982352013-08-14 14:39:50 -07008611 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008612
Andy Hungab65b182023-09-06 19:41:47 -07008613 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008614
Andy Hungf767de02024-10-30 19:47:50 -07008615 // check if traces have been enabled.
8616 bool atraceEnabled = ATRACE_ENABLED();
8617 if (atraceEnabled != mAtraceEnabled) [[unlikely]] {
8618 mAtraceEnabled = atraceEnabled;
8619 if (atraceEnabled) {
8620 const auto devices = patchSourcesToString(&mPatch);
8621 for (const auto& track : activeTracks) {
8622 track->logRefreshInterval(devices);
8623 }
8624 }
8625 }
8626
Kevin Rocard069c2712018-03-29 19:09:14 -07008627 updateMetadata_l();
8628
Eric Laurent5c25d562016-07-13 17:17:45 -07008629 if (allStopped) {
8630 standbyIfNotAlreadyInStandby();
8631 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008632 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008633 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008634 }
8635
8636 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008637 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008638 if (sleepUs == 0) {
8639 sleepUs = kRecordThreadSleepUs;
8640 }
8641 continue;
8642 }
8643 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008644
Andy Hung95c94a22023-10-20 16:41:18 -07008645 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008646 lockEffectChains_l(effectChains);
Abdelrahman Daimf6a71612024-11-21 08:57:37 -08008647 // We're exiting locked scope with non empty activeTracks, make sure
8648 // that we're not in standby mode which we could have entered if some
8649 // tracks were muted/unmuted.
8650 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08008651 }
8652
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008653 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008654
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008655 size_t size = effectChains.size();
8656 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008657 // thread mutex is not locked, but effect chain is locked
8658 effectChains[i]->process_l();
8659 }
8660
Glenn Kasten735f45f2014-08-18 15:51:59 -07008661 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008662 if (mFastCapture != 0) {
8663 FastCaptureStateQueue *sq = mFastCapture->sq();
8664 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008665 bool didModify = false;
8666 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008667 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8668 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8669 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8670 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8671 if (old == -1) {
8672 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8673 }
8674 }
8675 state->mCommand = FastCaptureState::READ_WRITE;
8676#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008677 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008678 FastThreadDumpState::kSamplingNforLowRamDevice :
8679 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008680#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008681 didModify = true;
8682 }
8683 audio_track_cblk_t *cblkOld = state->mCblk;
8684 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8685 if (cblkNew != cblkOld) {
8686 state->mCblk = cblkNew;
8687 // block until acked if removing a fast track
8688 if (cblkOld != NULL) {
8689 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8690 }
8691 didModify = true;
8692 }
jiabin01c8f562018-07-19 17:47:28 -07008693 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8694 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8695 if (state->mFastPatchRecordBufferProvider != abp) {
8696 state->mFastPatchRecordBufferProvider = abp;
8697 state->mFastPatchRecordFormat = fastTrack == 0 ?
8698 AUDIO_FORMAT_INVALID : fastTrack->format();
8699 didModify = true;
8700 }
Eric Laurent33403f02020-05-29 18:35:06 -07008701 if (state->mSilenceCapture != silenceFastCapture) {
8702 state->mSilenceCapture = silenceFastCapture;
8703 didModify = true;
8704 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008705 sq->end(didModify);
8706 if (didModify) {
8707 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008708#if 0
8709 if (kUseFastCapture == FastCapture_Dynamic) {
8710 mNormalSource = mPipeSource;
8711 }
8712#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008713 }
8714 }
8715
Glenn Kasten735f45f2014-08-18 15:51:59 -07008716 // now run the fast track destructor with thread mutex unlocked
8717 fastTrackToRemove.clear();
8718
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008719 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8720 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8721 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8722 // If destination is non-contiguous, first read past the nominal end of buffer, then
8723 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008724
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008725 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008726 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008727 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008728
8729 // If an NBAIO source is present, use it to read the normal capture's data
8730 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008731 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008732
8733 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8734 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8735 // we immediately retry the read() to get data and prevent another overflow.
8736 for (int retries = 0; retries <= 2; ++retries) {
8737 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8738 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8739 framesToRead);
8740 if (framesRead != OVERRUN) break;
8741 }
8742
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008743 const ssize_t availableToRead = mPipeSource->availableToRead();
8744 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008745 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008746 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008747 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8748 "more frames to read than fifo size, %zd > %zu",
8749 availableToRead, mPipeFramesP2);
8750 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8751 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8752 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8753 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008754 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8755 }
8756 if (framesRead < 0) {
8757 status_t status = (status_t) framesRead;
8758 switch (status) {
8759 case OVERRUN:
8760 ALOGW("overrun on read from pipe");
8761 framesRead = 0;
8762 break;
8763 case NEGOTIATE:
8764 ALOGE("re-negotiation is needed");
8765 framesRead = -1; // Will cause an attempt to recover.
8766 break;
8767 default:
8768 ALOGE("unknown error %d on read from pipe", status);
8769 break;
8770 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008771 }
8772 // otherwise use the HAL / AudioStreamIn directly
8773 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008774 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008775 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008776 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008777 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008778 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008779 if (result < 0) {
8780 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008781 } else {
8782 framesRead = bytesRead / mFrameSize;
8783 }
8784 }
8785
Andy Hung446f4df2019-02-21 12:26:41 -08008786 const int64_t lastIoEndNs = systemTime(); // end IO timing
8787
Andy Hung3f0c9022016-01-15 17:49:46 -08008788 // Update server timestamp with server stats
8789 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008790 if (framesRead >= 0) {
8791 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8792 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8793 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008794
8795 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008796 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008797 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008798 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008799 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8800 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8801 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008802 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008803 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8804
8805 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008806 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008807 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008808 id(), (long long)time, (long long)position);
8809 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8810 position = correctedTimestamp.mFrames;
8811 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008812 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008813 id(), (long long)time, (long long)position);
8814 }
8815
Andy Hung3f0c9022016-01-15 17:49:46 -08008816 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8817 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8818 // Note: In general record buffers should tend to be empty in
8819 // a properly running pipeline.
8820 //
8821 // Also, it is not advantageous to call get_presentation_position during the read
8822 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008823 } else {
8824 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008825 }
8826 }
Andy Hunge6c37112019-02-26 17:38:10 -08008827
8828 // From the timestamp, input read latency is negative output write latency.
8829 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008830 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008831 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8832 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8833 mLatencyMs.add(latencyMs);
8834 }
8835
Andy Hung3f0c9022016-01-15 17:49:46 -08008836 // Use this to track timestamp information
8837 // ALOGD("%s", mTimestamp.toString().c_str());
8838
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008839 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008840 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008841 // Force input into standby so that it tries to recover at next read attempt
8842 inputStandBy();
8843 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008844 }
8845 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008846 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008847 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008848 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008849 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008850
Andy Hung8946a282018-04-19 20:04:56 -07008851#ifdef TEE_SINK
8852 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8853#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008854 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008855 {
8856 size_t part1 = mRsmpInFramesP2 - rear;
8857 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008858 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008859 (framesRead - part1) * mFrameSize);
8860 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008861 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008862 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008863
8864 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008865
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008866 // loop over each active track
8867 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008868 if (activeTrack) { // ensure track release is outside lock.
8869 oldActiveTracks.emplace_back(std::move(activeTrack));
8870 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008871 activeTrack = activeTracks[i];
8872
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008873 // skip fast tracks, as those are handled directly by FastCapture
8874 if (activeTrack->isFastTrack()) {
8875 continue;
8876 }
8877
Andy Hung73c02e42015-03-29 01:13:58 -07008878 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008879 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8880
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008881 enum {
8882 OVERRUN_UNKNOWN,
8883 OVERRUN_TRUE,
8884 OVERRUN_FALSE
8885 } overrun = OVERRUN_UNKNOWN;
8886
8887 // loop over getNextBuffer to handle circular sink
8888 for (;;) {
8889
Andy Hung8d31fd22023-06-26 19:20:57 -07008890 activeTrack->sinkBuffer().frameCount = ~0;
8891 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8892 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008893 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8894
Andy Hung73c02e42015-03-29 01:13:58 -07008895 // check available frames and handle overrun conditions
8896 // if the record track isn't draining fast enough.
8897 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008898 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008899 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008900 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008901 overrun = OVERRUN_TRUE;
8902 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008903 if (framesOut == 0 || framesIn == 0) {
8904 break;
8905 }
8906
Andy Hung6770c6f2015-04-07 13:43:36 -07008907 // Don't allow framesOut to be larger than what is possible with resampling
8908 // from framesIn.
8909 // This isn't strictly necessary but helps limit buffer resizing in
8910 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008911 if (audio_is_linear_pcm(activeTrack->format())) {
8912 framesOut = min(framesOut,
8913 destinationFramesPossible(
8914 framesIn, mSampleRate, activeTrack->sampleRate()));
8915 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008916
8917 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008918 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008919 // straight from RecordThread buffer to RecordTrack buffer.
8920 AudioBufferProvider::Buffer buffer;
8921 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008922 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008923 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008924 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008925 ALOGV_IF(buffer.frameCount != framesOut,
8926 "%s() read less than expected (%zu vs %zu)",
8927 __func__, buffer.frameCount, framesOut);
8928 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008929 memcpy(activeTrack->sinkBuffer().raw,
8930 buffer.raw, buffer.frameCount * mFrameSize);
8931 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008932 } else {
8933 framesOut = 0;
8934 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008935 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008936 }
8937 } else {
8938 // process frames from the RecordThread buffer provider to the RecordTrack
8939 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008940 framesOut = activeTrack->recordBufferConverter()->convert(
8941 activeTrack->sinkBuffer().raw,
8942 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008943 framesOut);
8944 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008945
8946 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8947 overrun = OVERRUN_FALSE;
8948 }
8949
Andy Hung93bb5732023-05-04 21:16:34 -07008950 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8951 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008952 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008953 if (framesToDrop == 0) {
8954 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008955 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008956 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008957 // Sanitize before releasing if the track has no access to the source data
8958 // An idle UID receives silence from non virtual devices until active
8959 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008960 memset(activeTrack->sinkBuffer().raw,
8961 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008962 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008963 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008964 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008965 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008966 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008967 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008968 }
8969 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008970
8971 switch (overrun) {
8972 case OVERRUN_TRUE:
8973 // client isn't retrieving buffers fast enough
8974 if (!activeTrack->setOverflow()) {
8975 nsecs_t now = systemTime();
8976 // FIXME should lastWarning per track?
8977 if ((now - lastWarning) > kWarningThrottleNs) {
8978 ALOGW("RecordThread: buffer overflow");
8979 lastWarning = now;
8980 }
8981 }
8982 break;
8983 case OVERRUN_FALSE:
8984 activeTrack->clearOverflow();
8985 break;
8986 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008987 break;
8988 }
8989
Andy Hung3f0c9022016-01-15 17:49:46 -08008990 // update frame information and push timestamp out
8991 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008992 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008993 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8994 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008995 }
8996
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008997unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008998 // enable changes in effect chain
8999 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07009000 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07009001 if (audio_has_proportional_frames(mFormat)
9002 && loopCount == lastLoopCountRead + 1) {
9003 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
9004 const double jitterMs =
9005 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
9006 {framesRead, readPeriodNs},
9007 {0, 0} /* lastTimestamp */, mSampleRate);
9008 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
9009
Andy Hung972bec12023-08-31 16:13:39 -07009010 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07009011 mIoJitterMs.add(jitterMs);
9012 mProcessTimeMs.add(processMs);
9013 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07009014 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07009015 // update timing info.
9016 mLastIoBeginNs = lastIoBeginNs;
9017 mLastIoEndNs = lastIoEndNs;
9018 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009019 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07009020 mThreadloopExecutor.process(); // process any remaining deferred actions.
9021 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08009022
Glenn Kasten93e471f2013-08-19 08:40:07 -07009023 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08009024
9025 {
Andy Hung972bec12023-08-31 16:13:39 -07009026 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07009027 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009028 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07009029 track->invalidate();
9030 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009031 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07009032 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009033 }
9034
9035 releaseWakeLock();
9036
9037 ALOGV("RecordThread %p exiting", this);
9038 return false;
9039}
9040
Andy Hungee58e4a2023-07-07 13:47:37 -07009041void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08009042{
9043 if (!mStandby) {
9044 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07009045 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009046 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08009047 mStandby = true;
9048 }
9049}
9050
Andy Hungee58e4a2023-07-07 13:47:37 -07009051void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08009052{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009053 // Idle the fast capture if it's currently running
9054 if (mFastCapture != 0) {
9055 FastCaptureStateQueue *sq = mFastCapture->sq();
9056 FastCaptureState *state = sq->begin();
9057 if (!(state->mCommand & FastCaptureState::IDLE)) {
9058 state->mCommand = FastCaptureState::COLD_IDLE;
9059 state->mColdFutexAddr = &mFastCaptureFutex;
9060 state->mColdGen++;
9061 mFastCaptureFutex = 0;
9062 sq->end();
9063 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
Andy Hung82f39d62024-09-30 17:19:14 -07009064 {
9065 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastCapture->getTid());
9066 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
9067 }
9068
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009069#if 0
9070 if (kUseFastCapture == FastCapture_Dynamic) {
9071 // FIXME
9072 }
9073#endif
9074#ifdef AUDIO_WATCHDOG
9075 // FIXME
9076#endif
9077 } else {
9078 sq->end(false /*didModify*/);
9079 }
9080 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07009081 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009082 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07009083
9084 // If going into standby, flush the pipe source.
9085 if (mPipeSource.get() != nullptr) {
9086 const ssize_t flushed = mPipeSource->flush();
9087 if (flushed > 0) {
9088 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
9089 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
9090 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
9091 }
9092 }
Eric Laurent81784c32012-11-19 14:55:58 -08009093}
9094
Andy Hungc5007f82023-08-29 14:26:09 -07009095// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009096sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07009097 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009098 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009099 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08009100 audio_format_t format,
9101 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08009102 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08009103 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009104 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009105 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00009106 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07009107 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08009108 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08009109 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02009110 audio_port_handle_t portId,
9111 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08009112{
Glenn Kasten74935e42013-12-19 08:56:45 -08009113 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009114 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07009115 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08009116 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07009117 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009118 audio_input_flags_t requestedFlags = *flags;
9119 uint32_t sampleRate;
9120
9121 lStatus = initCheck();
9122 if (lStatus != NO_ERROR) {
9123 ALOGE("createRecordTrack_l() audio driver not initialized");
9124 goto Exit;
9125 }
9126
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009127 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
9128 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
9129 lStatus = BAD_VALUE;
9130 goto Exit;
9131 }
9132
Eric Laurentec376dc2021-04-08 20:41:22 +02009133 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01009134 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009135 lStatus = PERMISSION_DENIED;
9136 goto Exit;
9137 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009138 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07009139 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009140 lStatus = BAD_VALUE;
9141 goto Exit;
9142 }
9143 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08009144 if (*pSampleRate == 0) {
9145 *pSampleRate = mSampleRate;
9146 }
9147 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07009148
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009149 // special case for FAST flag considered OK if fast capture is present and access to
9150 // audio history is not required
9151 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07009152 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
9153 }
9154
Eric Laurentf14db3c2017-12-08 14:20:36 -08009155 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07009156 if ((*flags & inputFlags) != *flags) {
9157 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
9158 " input flags (%08x)",
9159 *flags, inputFlags);
9160 *flags = (audio_input_flags_t)(*flags & inputFlags);
9161 }
Eric Laurent81784c32012-11-19 14:55:58 -08009162
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009163 // client expresses a preference for FAST and no access to audio history,
9164 // but we get the final say
9165 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009166 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009167 // we formerly checked for a callback handler (non-0 tid),
9168 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00009169 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009170 //
Phil Burk7ed66a12019-04-18 13:20:30 -07009171 // Frame count is not specified (0), or is less than or equal the pipe depth.
9172 // It is OK to provide a higher capacity than requested.
9173 // We will force it to mPipeFramesP2 below.
9174 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009175 // PCM data
9176 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009177 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009178 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009179 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009180 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009181 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009182 hasFastCapture() &&
9183 // there are sufficient fast track slots available
9184 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009185 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009186 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009187 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009188 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009189 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009190 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009191 audio_input_flags_t old = *flags;
9192 chain->checkInputFlagCompatibility(flags);
9193 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009194 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9195 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009196 }
9197 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009198 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009199 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9200 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009201 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009202 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9203 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009204 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009205 this, frameCount, mFrameCount, mPipeFramesP2,
9206 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009207 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009208 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009209 }
9210 }
9211
Eric Laurentf14db3c2017-12-08 14:20:36 -08009212 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9213 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9214 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9215 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9216 lStatus = BAD_TYPE;
9217 goto Exit;
9218 }
9219
Glenn Kasten74105912014-07-03 12:28:53 -07009220 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009221 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009222 // fast track: frame count is exactly the pipe depth
9223 frameCount = mPipeFramesP2;
9224 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009225 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009226 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009227 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9228 // or 20 ms if there is a fast capture
9229 // TODO This could be a roundupRatio inline, and const
9230 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9231 * sampleRate + mSampleRate - 1) / mSampleRate;
9232 // minimum number of notification periods is at least kMinNotifications,
9233 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9234 static const size_t kMinNotifications = 3;
9235 static const uint32_t kMinMs = 30;
9236 // TODO This could be a roundupRatio inline
9237 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9238 // TODO This could be a roundupRatio inline
9239 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9240 maxNotificationFrames;
9241 const size_t minFrameCount = maxNotificationFrames *
9242 max(kMinNotifications, minNotificationsByMs);
9243 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009244 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9245 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009246 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009247 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009248 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009249 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009250
Andy Hungc5007f82023-08-29 14:26:09 -07009251 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009252 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009253 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009254 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009255 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009256 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009257 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009258 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009259 }
Eric Laurent81784c32012-11-19 14:55:58 -08009260
Andy Hung8d31fd22023-06-26 19:20:57 -07009261 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009262 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009263 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009264 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009265 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009266
Glenn Kasten03003332013-08-06 15:40:54 -07009267 lStatus = track->initCheck();
9268 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009269 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009270 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009271 goto Exit;
9272 }
9273 mTracks.add(track);
9274
Eric Laurent05067782016-06-01 18:27:28 -07009275 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009276 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9277 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9278 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009279 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009280 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009281
9282 if (maxSharedAudioHistoryMs != 0) {
9283 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9284 }
Eric Laurent81784c32012-11-19 14:55:58 -08009285 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009286
Eric Laurent81784c32012-11-19 14:55:58 -08009287 lStatus = NO_ERROR;
9288
9289Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009290 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009291 return track;
9292}
9293
Andy Hungee58e4a2023-07-07 13:47:37 -07009294status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009295 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009296 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009297{
9298 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9299 sp<ThreadBase> strongMe = this;
9300 status_t status = NO_ERROR;
9301
9302 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009303 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009304 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009305 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009306 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009307 event, triggerSession,
9308 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009309 }
9310
9311 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009312 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009313 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009314 if (recordTrack->isInvalid()) {
9315 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009316 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9317 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009318 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009319 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009320 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009321 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9322 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009323 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009324 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009325 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009326 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009327 }
9328 return status;
9329 }
9330
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009331 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9332 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9333 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009334 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009335 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009336 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009337 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009338 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009339 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009340 if (recordTrack->isInvalid()) {
9341 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009342 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9343 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009344 // STARTING_2 forces destroy to call stopInput.
9345 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009346 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9347 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009348 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009349 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009350 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009351 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009352 // Someone else has changed state, let them take over,
9353 // leave mState in the new state.
9354 recordTrack->clearSyncStartEvent();
9355 return INVALID_OPERATION;
9356 }
9357 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009358 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009359 ALOGW("%s(%d): startInput failed, status %d",
9360 __func__, recordTrack->id(), status);
9361 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9362 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009363 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009364 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009365 return status;
9366 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009367 sendIoConfigEvent_l(
9368 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009369 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009370
9371 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9372
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009373 // Catch up with current buffer indices if thread is already running.
9374 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9375 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9376 // see previously buffered data before it called start(), but with greater risk of overrun.
9377
Andy Hung8d31fd22023-06-26 19:20:57 -07009378 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009379 if (!recordTrack->isDirect()) {
9380 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009381 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009382 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009383 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009384 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009385 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009386 return status;
9387 }
Eric Laurent81784c32012-11-19 14:55:58 -08009388}
9389
Andy Hungee58e4a2023-07-07 13:47:37 -07009390void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009391{
Andy Hungee58e4a2023-07-07 13:47:37 -07009392 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009393
9394 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009395 sp<IAfTrackBase> ptr =
9396 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9397 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009398 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009399 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009400 }
Eric Laurent81784c32012-11-19 14:55:58 -08009401 }
9402}
9403
Andy Hungee58e4a2023-07-07 13:47:37 -07009404bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009405 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009406 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009407 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009408 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009409 return false;
9410 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009411 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009412 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009413
Andy Hungabfab202019-03-07 19:45:54 -08009414 // NOTE: Waiting here is important to keep stop synchronous.
9415 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009416 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009417 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009418 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009419 }
Andy Hungce685402018-10-05 17:23:27 -07009420
Andy Hung8d31fd22023-06-26 19:20:57 -07009421 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009422 ALOGV("Record stopped OK");
9423 return true;
9424 }
Andy Hungce685402018-10-05 17:23:27 -07009425
9426 // don't handle anything - we've been invalidated or restarted and in a different state
9427 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009428 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009429 return false;
9430}
9431
Andy Hungee58e4a2023-07-07 13:47:37 -07009432bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009433{
9434 return false;
9435}
9436
Andy Hungee58e4a2023-07-07 13:47:37 -07009437status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009438{
9439#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9440 if (!isValidSyncEvent(event)) {
9441 return BAD_VALUE;
9442 }
9443
Glenn Kastend848eb42016-03-08 13:42:11 -08009444 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009445 status_t ret = NAME_NOT_FOUND;
9446
Andy Hung972bec12023-08-31 16:13:39 -07009447 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009448
9449 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009450 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009451 if (eventSession == track->sessionId()) {
9452 (void) track->setSyncEvent(event);
9453 ret = NO_ERROR;
9454 }
9455 }
9456 return ret;
9457#else
9458 return BAD_VALUE;
9459#endif
9460}
9461
Andy Hungee58e4a2023-07-07 13:47:37 -07009462status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009463 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009464{
9465 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009466 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009467 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009468 return NO_INIT;
9469 }
jiabin9ff780e2018-03-19 18:19:52 -07009470 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9471 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009472}
9473
Andy Hungee58e4a2023-07-07 13:47:37 -07009474status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009475 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009476{
Paul McLean12340082019-03-19 09:35:05 -06009477 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009478 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009479 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009480 return NO_INIT;
9481 }
Paul McLean12340082019-03-19 09:35:05 -06009482 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009483}
9484
Andy Hungee58e4a2023-07-07 13:47:37 -07009485status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009486{
Paul McLean12340082019-03-19 09:35:05 -06009487 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009488 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009489 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009490 return NO_INIT;
9491 }
Paul McLean12340082019-03-19 09:35:05 -06009492 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009493}
9494
Andy Hungee58e4a2023-07-07 13:47:37 -07009495status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009496 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9497 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009498 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009499 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9500}
9501
Andy Hungee58e4a2023-07-07 13:47:37 -07009502status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009503 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9504 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009505
Eric Laurentec376dc2021-04-08 20:41:22 +02009506 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9507 return BAD_VALUE;
9508 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009509
9510 if (sharedAudioStartMs < 0
9511 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009512 return BAD_VALUE;
9513 }
9514
Eric Laurent2407ce32021-04-26 14:56:03 +02009515 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9516 // As we cannot detect more than one wraparound, only accept values up current write position
9517 // after one wraparound
9518 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9519 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009520 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009521 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9522 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009523 // Bring the start frame position within the input buffer to match the documented
9524 // "best effort" behavior of the API.
9525 if (sharedOffset < 0) {
9526 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009527 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009528 sharedAudioStartFrames =
9529 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009530 }
9531
Eric Laurentec376dc2021-04-08 20:41:22 +02009532 mSharedAudioPackageName = sharedAudioPackageName;
9533 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009534 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009535 } else {
9536 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009537 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009538 }
9539 return NO_ERROR;
9540}
9541
Andy Hungee58e4a2023-07-07 13:47:37 -07009542void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009543 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9544 mSharedAudioStartFrames = -1;
9545 mSharedAudioPackageName = "";
9546}
9547
Andy Hungee58e4a2023-07-07 13:47:37 -07009548ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009549{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009550 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009551 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009552 }
9553 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009554 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009555 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009556 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009557 }
9558 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009559 MetadataUpdate change;
9560 change.recordMetadataUpdate = metadata.tracks;
9561 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009562}
9563
Andy Hungc5007f82023-08-29 14:26:09 -07009564// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009565void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009566{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009567 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009568 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009569
Eric Laurent81784c32012-11-19 14:55:58 -08009570 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009571 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009572 removeTrack_l(track);
9573 }
9574}
9575
Andy Hungee58e4a2023-07-07 13:47:37 -07009576void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009577{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009578 String8 result;
9579 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009580 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009581
Eric Laurent81784c32012-11-19 14:55:58 -08009582 mTracks.remove(track);
9583 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009584 if (track->isFastTrack()) {
9585 ALOG_ASSERT(!mFastTrackAvail);
9586 mFastTrackAvail = true;
9587 }
Eric Laurent81784c32012-11-19 14:55:58 -08009588}
9589
Andy Hungee58e4a2023-07-07 13:47:37 -07009590void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009591{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009592 AudioStreamIn *input = mInput;
9593 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9594 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009595 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009596 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009597 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009598 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009599 }
Andy Hungbfa64962017-06-12 14:43:19 -07009600
9601 if (input != nullptr) {
9602 dprintf(fd, " Hal stream dump:\n");
9603 (void)input->stream->dump(fd);
9604 }
9605
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009606 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009607 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009608
Glenn Kasten2f90c512015-12-02 11:40:09 -08009609 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9610 // while we are dumping it. It may be inconsistent, but it won't mutate!
9611 // This is a large object so we place it on the heap.
9612 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009613 const std::unique_ptr<FastCaptureDumpState> copy =
9614 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009615 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009616}
9617
Andy Hungee58e4a2023-07-07 13:47:37 -07009618void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009619{
Eric Laurent81784c32012-11-19 14:55:58 -08009620 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009621 size_t numtracks = mTracks.size();
9622 size_t numactive = mActiveTracks.size();
9623 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009624 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009625 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009626 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009627 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009628 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009629 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009630 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009631 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009632 if (track != 0) {
9633 bool active = mActiveTracks.indexOf(track) >= 0;
9634 if (active) {
9635 numactiveseen++;
9636 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009637 result.append(prefix);
9638 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009639 }
Eric Laurent81784c32012-11-19 14:55:58 -08009640 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009641 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009642 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009643 }
9644
Marco Nelissenb2208842014-02-07 14:00:50 -08009645 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009646 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009647 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009648 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009649 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009650 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009651 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009652 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009653 result.append(prefix);
9654 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009655 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009656 }
Eric Laurent81784c32012-11-19 14:55:58 -08009657
9658 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009659 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009660}
9661
Andy Hungee58e4a2023-07-07 13:47:37 -07009662void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009663{
Andy Hung972bec12023-08-31 16:13:39 -07009664 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009665 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009666 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009667 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009668 track->setSilenced(silenced);
9669 }
9670 }
9671}
Andy Hung73c02e42015-03-29 01:13:58 -07009672
Andy Hung8d31fd22023-06-26 19:20:57 -07009673void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009674{
Andy Hung87c693c2023-07-06 20:56:16 -07009675 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009676 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009677 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009678 const int32_t rear = recordThread->mRsmpInRear;
9679 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009680 if (mRecordTrack->startFrames() >= 0) {
9681 int32_t startFrames = mRecordTrack->startFrames();
9682 // Accept a recent wraparound of mRsmpInRear
9683 if (startFrames <= rear) {
9684 deltaFrames = rear - startFrames;
9685 } else {
9686 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009687 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009688 // start frame cannot be further in the past than start of resampling buffer
9689 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9690 deltaFrames = recordThread->mRsmpInFrames;
9691 }
9692 }
9693 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009694}
9695
Andy Hung8d31fd22023-06-26 19:20:57 -07009696void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009697 size_t *framesAvailable, bool *hasOverrun)
9698{
Andy Hung87c693c2023-07-06 20:56:16 -07009699 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009700 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009701 const int32_t rear = recordThread->mRsmpInRear;
9702 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009703 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009704
9705 size_t framesIn;
9706 bool overrun = false;
9707 if (filled < 0) {
9708 // should not happen, but treat like a massive overrun and re-sync
9709 framesIn = 0;
9710 mRsmpInFront = rear;
9711 overrun = true;
9712 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9713 framesIn = (size_t) filled;
9714 } else {
9715 // client is not keeping up with server, but give it latest data
9716 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009717 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9718 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009719 overrun = true;
9720 }
9721 if (framesAvailable != NULL) {
9722 *framesAvailable = framesIn;
9723 }
9724 if (hasOverrun != NULL) {
9725 *hasOverrun = overrun;
9726 }
9727}
9728
Eric Laurent81784c32012-11-19 14:55:58 -08009729// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009730status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009731 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009732{
Andy Hung87c693c2023-07-06 20:56:16 -07009733 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009734 if (threadBase == 0) {
9735 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009736 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009737 return NOT_ENOUGH_DATA;
9738 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009739 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009740 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009741 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009742 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009743 // FIXME should not be P2 (don't want to increase latency)
9744 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009745 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009746 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009747
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009748 front &= recordThread->mRsmpInFramesP2 - 1;
9749 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009750 if (part1 > (size_t) filled) {
9751 part1 = filled;
9752 }
9753 size_t ask = buffer->frameCount;
9754 ALOG_ASSERT(ask > 0);
9755 if (part1 > ask) {
9756 part1 = ask;
9757 }
9758 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009759 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009760 buffer->raw = NULL;
9761 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009762 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009763 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009764 }
9765
Andy Hung57446612015-04-19 23:56:46 -07009766 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009767 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009768 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009769 return NO_ERROR;
9770}
9771
9772// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009773void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009774 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009775{
Hongwei Wang95e37682019-04-12 11:13:36 -07009776 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009777 if (stepCount == 0) {
9778 return;
9779 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009780 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009781 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009782 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009783 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009784 buffer->frameCount = 0;
9785}
9786
Andy Hungee58e4a2023-07-07 13:47:37 -07009787void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009788{
Andy Hung972bec12023-08-31 16:13:39 -07009789 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009790 checkBtNrec_l();
9791}
9792
Andy Hungee58e4a2023-07-07 13:47:37 -07009793void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009794{
9795 // disable AEC and NS if the device is a BT SCO headset supporting those
9796 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009797 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009798 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009799 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9800 for (size_t i = 0; i < mEffectChains.size(); i++) {
9801 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9802 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9803 }
9804 }
9805}
9806
Andy Hung97a893e2015-03-29 01:03:07 -07009807
Andy Hungee58e4a2023-07-07 13:47:37 -07009808bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009809 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009810{
9811 bool reconfig = false;
9812
Eric Laurent10351942014-05-08 18:49:52 -07009813 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009814
Eric Laurent10351942014-05-08 18:49:52 -07009815 audio_format_t reqFormat = mFormat;
9816 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009817 // 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 +08009818 [[maybe_unused]] audio_channel_mask_t channelMask =
9819 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009820
9821 AudioParameter param = AudioParameter(keyValuePair);
9822 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009823
9824 // scope for AutoPark extends to end of method
9825 AutoPark<FastCapture> park(mFastCapture);
9826
Eric Laurent10351942014-05-08 18:49:52 -07009827 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9828 // channel count change can be requested. Do we mandate the first client defines the
9829 // HAL sampling rate and channel count or do we allow changes on the fly?
9830 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9831 samplingRate = value;
9832 reconfig = true;
9833 }
9834 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009835 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009836 status = BAD_VALUE;
9837 } else {
9838 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009839 reconfig = true;
9840 }
Eric Laurent10351942014-05-08 18:49:52 -07009841 }
9842 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9843 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009844 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009845 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009846 status = BAD_VALUE;
9847 } else {
9848 channelMask = mask;
9849 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009850 }
Eric Laurent10351942014-05-08 18:49:52 -07009851 }
9852 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9853 // do not accept frame count changes if tracks are open as the track buffer
9854 // size depends on frame count and correct behavior would not be guaranteed
9855 // if frame count is changed after track creation
9856 if (mActiveTracks.size() > 0) {
9857 status = INVALID_OPERATION;
9858 } else {
9859 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009860 }
Eric Laurent10351942014-05-08 18:49:52 -07009861 }
9862 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009863 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009864 }
9865 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9866 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009867 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009868 }
Glenn Kastene198c362013-08-13 09:13:36 -07009869
Eric Laurent10351942014-05-08 18:49:52 -07009870 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009871 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009872 if (status == INVALID_OPERATION) {
9873 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009874 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009875 }
9876 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009877 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009878 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9879 if (mInput->stream->getAudioProperties(&config) == OK &&
9880 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9881 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009882 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009883 status = NO_ERROR;
9884 }
Eric Laurent81784c32012-11-19 14:55:58 -08009885 }
Eric Laurent10351942014-05-08 18:49:52 -07009886 if (status == NO_ERROR) {
9887 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009888 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009889 }
9890 }
Eric Laurent81784c32012-11-19 14:55:58 -08009891 }
Eric Laurent10351942014-05-08 18:49:52 -07009892
Eric Laurent81784c32012-11-19 14:55:58 -08009893 return reconfig;
9894}
9895
Andy Hungee58e4a2023-07-07 13:47:37 -07009896String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009897{
Andy Hung972bec12023-08-31 16:13:39 -07009898 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009899 if (initCheck() == NO_ERROR) {
9900 String8 out_s8;
9901 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9902 return out_s8;
9903 }
Eric Laurent81784c32012-11-19 14:55:58 -08009904 }
Andy Hung920f6572022-10-06 12:09:49 -07009905 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009906}
9907
Andy Hungab65b182023-09-06 19:41:47 -07009908void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009909 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009910 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009911 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009912 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009913 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009914 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009915 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9916 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009917 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009918 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009919 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009920 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009921 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009922 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009923 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009924 break;
9925 }
Andy Hungab65b182023-09-06 19:41:47 -07009926 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009927}
9928
Andy Hungee58e4a2023-07-07 13:47:37 -07009929void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009930{
Dean Wheatley6c009512023-10-23 09:34:14 +11009931 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9932 mSampleRate = audioConfig.sample_rate;
9933 mChannelMask = audioConfig.channel_mask;
9934 if (!audio_is_input_channel(mChannelMask)) {
9935 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9936 }
9937
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009938 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009939
9940 // Get actual HAL format.
9941 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9942 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9943 // Get format from the shim, which will be different than the HAL format
9944 // if recording compressed audio from IEC61937 wrapped sources.
9945 mFormat = audioConfig.format;
9946 if (!audio_is_valid_format(mFormat)) {
9947 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9948 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009949 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009950 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9951 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009952 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009953 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009954 ALOGI("HAL format %#x is not linear pcm", mFormat);
9955 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009956 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009957 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9958 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009959 result = mInput->stream->getBufferSize(&mBufferSize);
9960 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009961 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009962 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9963 "mBufferSize=%zu, mFrameCount=%zu",
9964 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009965
Eric Laurentec376dc2021-04-08 20:41:22 +02009966 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9967 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009968 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009969
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009970 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9971 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009972
9973 audio_input_flags_t flags = mInput->flags;
9974 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9975 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009976 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009977 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9978 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9979 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9980 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9981 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9982 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009983}
9984
Andy Hungee58e4a2023-07-07 13:47:37 -07009985uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009986{
Andy Hung972bec12023-08-31 16:13:39 -07009987 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009988 uint32_t result;
9989 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9990 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009991 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009992 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009993}
9994
Andy Hungee58e4a2023-07-07 13:47:37 -07009995KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009996{
Glenn Kastend848eb42016-03-08 13:42:11 -08009997 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009998 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009999 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010000 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -080010001 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -080010002 if (ids.indexOfKey(sessionId) < 0) {
10003 ids.add(sessionId, true);
10004 }
10005 }
10006 return ids;
10007}
10008
Andy Hungee58e4a2023-07-07 13:47:37 -070010009AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -080010010{
Andy Hung972bec12023-08-31 16:13:39 -070010011 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -080010012 AudioStreamIn *input = mInput;
10013 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -070010014 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -080010015 return input;
10016}
10017
Andy Hungc5007f82023-08-29 14:26:09 -070010018// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -070010019sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -080010020{
10021 if (mInput == NULL) {
10022 return NULL;
10023 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -070010024 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -080010025}
10026
Andy Hungee58e4a2023-07-07 13:47:37 -070010027status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -080010028{
Eric Laurent81784c32012-11-19 14:55:58 -080010029 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -070010030 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -080010031 chain->setInBuffer(NULL);
10032 chain->setOutBuffer(NULL);
10033
10034 checkSuspendOnAddEffectChain_l(chain);
10035
Eric Laurent1b928682014-10-02 19:41:47 -070010036 // make sure enabled pre processing effects state is communicated to the HAL as we
10037 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +000010038 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -070010039
Eric Laurent81784c32012-11-19 14:55:58 -080010040 mEffectChains.add(chain);
10041
10042 return NO_ERROR;
10043}
10044
Andy Hungee58e4a2023-07-07 13:47:37 -070010045size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -080010046{
10047 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -070010048
10049 for (size_t i = 0; i < mEffectChains.size(); i++) {
10050 if (chain == mEffectChains[i]) {
10051 mEffectChains.removeAt(i);
10052 break;
10053 }
Eric Laurent81784c32012-11-19 14:55:58 -080010054 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -070010055 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -080010056}
10057
Andy Hungee58e4a2023-07-07 13:47:37 -070010058status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -070010059 audio_patch_handle_t *handle)
10060{
10061 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010062
10063 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -070010064 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010065 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +020010066 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -070010067 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010068 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -070010069 }
10070
Eric Laurentd8365c52017-07-16 15:27:05 -070010071 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -070010072
10073 // store new source and send to effects
10074 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10075 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -070010076 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -070010077 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -070010078 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010079 }
Eric Laurent1c333e22014-05-20 10:48:17 -070010080
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010081 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010082 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10083 status = hwDevice->createAudioPatch(patch->num_sources,
10084 patch->sources,
10085 patch->num_sinks,
10086 patch->sinks,
10087 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010088 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010089 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
10090 patch->sinks[0].ext.mix.usecase.source,
10091 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -070010092 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -070010093 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010094
jiabinc52b1ff2019-10-31 17:20:42 -070010095 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -070010096 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -070010097 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -070010098 }
Eric Laurent296fb132015-05-01 11:38:42 -070010099
Andy Hungc2b11cb2020-04-22 09:04:01 -070010100 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -070010101 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -070010102 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -070010103 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -070010104 // also dispatch to active AudioRecords
10105 for (const auto &track : mActiveTracks) {
10106 track->logEndInterval();
10107 track->logBeginInterval(pathSourcesAsString);
10108 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010109 // Force meteadata update after a route change
10110 mActiveTracks.setHasChanged();
10111
Eric Laurent1c333e22014-05-20 10:48:17 -070010112 return status;
10113}
10114
Andy Hungee58e4a2023-07-07 13:47:37 -070010115status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -070010116{
10117 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010118
jiabinc52b1ff2019-10-31 17:20:42 -070010119 mPatch = audio_patch{};
10120 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -070010121
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010122 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010123 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10124 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010125 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010126 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -070010127 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010128 // Force meteadata update after a route change
10129 mActiveTracks.setHasChanged();
10130
Eric Laurent1c333e22014-05-20 10:48:17 -070010131 return status;
10132}
10133
Andy Hungee58e4a2023-07-07 13:47:37 -070010134void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -070010135{
Andy Hung972bec12023-08-31 16:13:39 -070010136 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -070010137 mOutDevices = outDevices;
10138 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
10139 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010140 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -070010141 }
10142}
10143
Andy Hungee58e4a2023-07-07 13:47:37 -070010144int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +020010145{
10146 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010147 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +020010148 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010149 int32_t oldestFront = mRsmpInRear;
10150 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +020010151 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010152 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +020010153 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +020010154 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +020010155 if (filled > maxFilled) {
10156 oldestFront = front;
10157 maxFilled = filled;
10158 }
Eric Laurentec376dc2021-04-08 20:41:22 +020010159 }
Andy Hung920f6572022-10-06 12:09:49 -070010160 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010161 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
10162 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010163 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +020010164}
10165
Andy Hungee58e4a2023-07-07 13:47:37 -070010166void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +020010167{
10168 if (offset == 0) {
10169 return;
10170 }
10171 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010172 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +020010173 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -070010174 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010175 }
10176}
10177
Andy Hungee58e4a2023-07-07 13:47:37 -070010178void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010179{
10180 // This is the formula for calculating the temporary buffer size.
10181 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10182 // 1 full output buffer, regardless of the alignment of the available input.
10183 // The value is somewhat arbitrary, and could probably be even larger.
10184 // A larger value should allow more old data to be read after a track calls start(),
10185 // without increasing latency.
10186 //
10187 // Note this is independent of the maximum downsampling ratio permitted for capture.
10188 size_t minRsmpInFrames = mFrameCount * 7;
10189
10190 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10191 // capture history available to another client using the same session ID:
10192 // dimension the resampler input buffer accordingly.
10193
10194 // Get oldest client read position: getOldestFront_l() must be called before altering
10195 // mRsmpInRear, or mRsmpInFrames
10196 int32_t previousFront = getOldestFront_l();
10197 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10198 int32_t previousRear = mRsmpInRear;
10199 mRsmpInRear = 0;
10200
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010201 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010202 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010203 "resizeInputBuffer_l() called with invalid max shared history %d",
10204 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010205 if (maxSharedAudioHistoryMs != 0) {
10206 // resizeInputBuffer_l should never be called with a non zero shared history if the
10207 // buffer was not already allocated
10208 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10209 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10210 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10211 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010212 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010213 return;
10214 }
10215 mRsmpInFrames = rsmpInFrames;
10216 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010217 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010218 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10219 // initialized
10220 if (mRsmpInFrames < minRsmpInFrames) {
10221 mRsmpInFrames = minRsmpInFrames;
10222 }
10223 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10224
10225 // TODO optimize audio capture buffer sizes ...
10226 // Here we calculate the size of the sliding buffer used as a source
10227 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10228 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10229 // be better to have it derived from the pipe depth in the long term.
10230 // The current value is higher than necessary. However it should not add to latency.
10231
10232 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10233 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10234
10235 void *rsmpInBuffer;
10236 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10237 // if posix_memalign fails, will segv here.
10238 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10239
10240 // Copy audio history if any from old buffer before freeing it
10241 if (previousRear != 0) {
10242 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10243 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10244
10245 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10246 previousFront &= previousRsmpInFramesP2 - 1;
10247 size_t part1 = previousRsmpInFramesP2 - previousFront;
10248 if (part1 > (size_t) unread) {
10249 part1 = unread;
10250 }
10251 if (part1 != 0) {
10252 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10253 part1 * mFrameSize);
10254 mRsmpInRear = part1;
10255 part1 = unread - part1;
10256 if (part1 != 0) {
10257 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10258 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10259 mRsmpInRear += part1;
10260 }
10261 }
10262 // Update front for all clients according to new rear
10263 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10264 } else {
10265 mRsmpInRear = 0;
10266 }
10267 free(mRsmpInBuffer);
10268 mRsmpInBuffer = rsmpInBuffer;
10269}
10270
Andy Hungee58e4a2023-07-07 13:47:37 -070010271void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010272{
Andy Hung972bec12023-08-31 16:13:39 -070010273 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010274 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010275 if (record->getSource()) {
10276 mSource = record->getSource();
10277 }
Eric Laurent83b88082014-06-20 18:31:16 -070010278}
10279
Andy Hungee58e4a2023-07-07 13:47:37 -070010280void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010281{
Andy Hung972bec12023-08-31 16:13:39 -070010282 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010283 if (mSource == record->getSource()) {
10284 mSource = mInput;
10285 }
Eric Laurent83b88082014-06-20 18:31:16 -070010286 destroyTrack_l(record);
10287}
10288
Andy Hungee58e4a2023-07-07 13:47:37 -070010289void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010290{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010291 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010292 config->role = AUDIO_PORT_ROLE_SINK;
10293 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10294 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010295 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10296 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10297 config->flags.input = mInput->flags;
10298 }
Eric Laurent83b88082014-06-20 18:31:16 -070010299}
Eric Laurent1c333e22014-05-20 10:48:17 -070010300
Atneya Nairaa3afcb2024-10-08 16:36:19 -070010301std::string RecordThread::getLocalLogHeader() const {
10302 using namespace std::literals;
10303 static constexpr auto indent = " "
10304 " "sv;
10305 return std::string{indent}.append(IAfRecordTrack::getLogHeader());
10306}
10307
Eric Laurent6acd1d42017-01-04 14:23:29 -080010308// ----------------------------------------------------------------------------
10309// Mmap
10310// ----------------------------------------------------------------------------
10311
Andy Hung7aa7d102023-07-07 15:58:48 -070010312// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10313// MmapPlaybackThread or MmapCaptureThread instance.
10314class MmapThreadHandle : public MmapStreamInterface {
10315public:
10316 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10317 ~MmapThreadHandle() override;
10318
10319 // MmapStreamInterface virtuals
10320 status_t createMmapBuffer(int32_t minSizeFrames,
10321 struct audio_mmap_buffer_info* info) final;
10322 status_t getMmapPosition(struct audio_mmap_position* position) final;
10323 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10324 status_t start(const AudioClient& client,
10325 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10326 status_t stop(audio_port_handle_t handle) final;
10327 status_t standby() final;
10328 status_t reportData(const void* buffer, size_t frameCount) final;
10329private:
10330 const sp<IAfMmapThread> mThread;
10331};
10332
10333/* static */
10334sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10335 const sp<IAfMmapThread>& mmapThread) {
10336 return sp<MmapThreadHandle>::make(mmapThread);
10337}
10338
10339MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340 : mThread(thread)
10341{
Phil Burk9fabbf82017-08-03 12:02:00 -070010342 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010343}
10344
Andy Hung7aa7d102023-07-07 15:58:48 -070010345// MmapStreamInterface could be directly implemented by MmapThread excepting this
10346// special handling on adapter dtor.
10347MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348{
Phil Burk9fabbf82017-08-03 12:02:00 -070010349 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350}
10351
Andy Hung7aa7d102023-07-07 15:58:48 -070010352status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 struct audio_mmap_buffer_info *info)
10354{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010355 return mThread->createMmapBuffer(minSizeFrames, info);
10356}
10357
Andy Hung7aa7d102023-07-07 15:58:48 -070010358status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010359{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010360 return mThread->getMmapPosition(position);
10361}
10362
Andy Hung7aa7d102023-07-07 15:58:48 -070010363status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010364 int64_t *timeNanos) {
10365 return mThread->getExternalPosition(position, timeNanos);
10366}
10367
Andy Hung7aa7d102023-07-07 15:58:48 -070010368status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010369 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010370{
jiabind1f1cb62020-03-24 11:57:57 -070010371 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010372}
10373
Andy Hung7aa7d102023-07-07 15:58:48 -070010374status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376 return mThread->stop(handle);
10377}
10378
Andy Hung7aa7d102023-07-07 15:58:48 -070010379status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010380{
Eric Laurent18b57012017-02-13 16:23:52 -080010381 return mThread->standby();
10382}
10383
Andy Hung7aa7d102023-07-07 15:58:48 -070010384status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10385{
jiabinfc791ee2023-02-15 19:43:40 +000010386 return mThread->reportData(buffer, frameCount);
10387}
10388
Eric Laurent6acd1d42017-01-04 14:23:29 -080010389
Andy Hungee58e4a2023-07-07 13:47:37 -070010390MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010391 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010392 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010393 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010394 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010395 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010396 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010397 mActiveTracks(&this->mLocalLog),
10398 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10399 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010400{
Eric Laurent18b57012017-02-13 16:23:52 -080010401 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 readHalParameters_l();
10403}
10404
Andy Hungee58e4a2023-07-07 13:47:37 -070010405void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406{
10407 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10408}
10409
Andy Hungee58e4a2023-07-07 13:47:37 -070010410void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010411{
Andy Hung8d31fd22023-06-26 19:20:57 -070010412 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010413 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010414 {
Andy Hung972bec12023-08-31 16:13:39 -070010415 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010416 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010417 activeTracks.add(t);
10418 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010419 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010420 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010421 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422 stop(t->portId());
10423 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010424 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010425 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010426 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010427 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010428 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010429 }
10430}
10431
10432
Andy Hung8d672e02023-09-15 18:19:28 -070010433void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010434 audio_stream_type_t streamType __unused,
10435 audio_session_t sessionId,
10436 const sp<MmapStreamCallback>& callback,
Robert Wuaeb1d002024-10-30 23:19:44 +000010437 const DeviceIdVector& deviceIds,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010438 audio_port_handle_t portId)
10439{
10440 mAttr = *attr;
10441 mSessionId = sessionId;
10442 mCallback = callback;
Robert Wuaeb1d002024-10-30 23:19:44 +000010443 mDeviceIds = deviceIds;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 mPortId = portId;
10445}
10446
Andy Hungee58e4a2023-07-07 13:47:37 -070010447status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448 struct audio_mmap_buffer_info *info)
10449{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010450 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451 if (mHalStream == 0) {
10452 return NO_INIT;
10453 }
Eric Laurent18b57012017-02-13 16:23:52 -080010454 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010455 return mHalStream->createMmapBuffer(minSizeFrames, info);
10456}
10457
Andy Hungee58e4a2023-07-07 13:47:37 -070010458status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010460 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461 if (mHalStream == 0) {
10462 return NO_INIT;
10463 }
10464 return mHalStream->getMmapPosition(position);
10465}
10466
Andy Hungee58e4a2023-07-07 13:47:37 -070010467status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010468{
Eric Laurentdda206a2022-07-08 17:28:35 +020010469 // The HAL must receive track metadata before starting the stream
10470 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010471 status_t ret = mHalStream->start();
10472 if (ret != NO_ERROR) {
10473 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10474 return ret;
10475 }
Andy Hungcf10d742020-04-28 15:38:24 -070010476 if (mStandby) {
10477 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010478 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010479 mStandby = false;
10480 }
Eric Laurent331679c2018-04-16 17:03:16 -070010481 return NO_ERROR;
10482}
10483
Andy Hungee58e4a2023-07-07 13:47:37 -070010484status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010485 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486 audio_port_handle_t *handle)
10487{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010488 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010489 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010490 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 if (mHalStream == 0) {
10492 return NO_INIT;
10493 }
10494
10495 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496
Eric Laurentdda206a2022-07-08 17:28:35 +020010497 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010498 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010499 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010500 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010501 }
10502
10503 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10504
10505 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010506 AttributionSourceState adjAttributionSource;
10507 if (!com::android::media::audio::audioserver_permissions()) {
10508 adjAttributionSource = afutils::checkAttributionSourcePackage(
10509 client.attributionSource);
10510 } else {
10511 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10512 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10513 client.attributionSource,
10514 mAfThreadCallback->getPermissionProvider()
10515 );
10516 if (!validatedRes.has_value()) {
10517 ALOGE("MMAP client package validation fail: %s",
10518 validatedRes.error().toString8().c_str());
10519 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10520 }
10521 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10522 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010523
Andy Hung3f49ebb2023-09-19 14:48:41 -070010524 const auto localSessionId = mSessionId;
10525 auto localAttr = mAttr;
Andy Hung6b137d12024-08-27 22:35:17 +000010526 float volume = 0.0f;
Vlad Popa1e865e62024-08-15 19:11:42 -070010527 bool muted = false;
Eric Laurenta54f1282017-07-01 19:39:32 -070010528 if (isOutput()) {
10529 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10530 config.sample_rate = mSampleRate;
10531 config.channel_mask = mChannelMask;
10532 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010533 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010534 audio_output_flags_t flags =
10535 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Robert Wuaeb1d002024-10-30 23:19:44 +000010536 DeviceIdVector deviceIds = mDeviceIds;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010537 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010538 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010539 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010540 mutex().unlock();
10541 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10542 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010543 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010544 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010545 &config,
10546 flags,
Robert Wufb971192024-10-30 21:54:35 +000010547 &deviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010548 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010549 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010550 &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +000010551 &isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -070010552 &volume,
10553 &muted);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010554 mutex().lock();
10555 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010556 ALOGD_IF(!secondaryOutputs.empty(),
10557 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010559 audio_config_base_t config;
10560 config.sample_rate = mSampleRate;
10561 config.channel_mask = mChannelMask;
10562 config.format = mFormat;
Robert Wuaeb1d002024-10-30 23:19:44 +000010563 audio_port_handle_t deviceId = getFirstDeviceId(mDeviceIds);
Eric Laurentcbc3f6f2025-01-09 10:48:53 +000010564 audio_source_t source = AUDIO_SOURCE_DEFAULT;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010565 mutex().unlock();
10566 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010567 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010568 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010569 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010570 &config,
10571 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10572 &deviceId,
Eric Laurentcbc3f6f2025-01-09 10:48:53 +000010573 &portId,
10574 &source);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010575 mutex().lock();
10576 // localAttr is const for getInputForAttr.
Eric Laurentcbc3f6f2025-01-09 10:48:53 +000010577 localAttr.source = source;
Eric Laurenta54f1282017-07-01 19:39:32 -070010578 }
10579 // APM should not chose a different input or output stream for the same set of attributes
10580 // and audo configuration
10581 if (ret != NO_ERROR || io != mId) {
10582 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10583 __FUNCTION__, ret, io, mId);
10584 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585 }
10586
10587 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010588 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010589 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010590 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 } else {
jiabin09609032022-06-15 19:26:01 +000010592 {
10593 // Add the track record before starting input so that the silent status for the
10594 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010595 setClientSilencedState_l(portId, false /*silenced*/);
10596 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010597 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010598 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010599 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010600 }
10601
10602 // abort if start is rejected by audio policy manager
10603 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010604 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010605 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010606 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010608 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010609 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010610 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010611 }
Andy Hungc5007f82023-08-29 14:26:09 -070010612 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010613 } else {
10614 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615 }
jiabin09609032022-06-15 19:26:01 +000010616 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010617 return PERMISSION_DENIED;
10618 }
10619
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010620 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010621 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10622 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010623 mChannelMask, mSessionId, isOutput(),
10624 client.attributionSource,
Andy Hung6b137d12024-08-27 22:35:17 +000010625 IPCThreadState::self()->getCallingPid(), portId,
Vlad Popa1e865e62024-08-15 19:11:42 -070010626 volume, muted);
jiabin09609032022-06-15 19:26:01 +000010627 if (!isOutput()) {
10628 track->setSilenced_l(isClientSilenced_l(portId));
10629 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630
Eric Laurent4eb58f12018-12-07 16:41:02 -080010631 if (isOutput()) {
10632 // force volume update when a new track is added
10633 mHalVolFloat = -1.0f;
10634 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010635 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010636 if (t->isSilenced_l()
10637 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010638 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010639 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010640 }
10641 }
10642
Eric Laurent6acd1d42017-01-04 14:23:29 -080010643 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010644 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010645 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010646 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010647 chain->incTrackCnt();
10648 chain->incActiveTrackCnt();
10649 }
10650
Andy Hungc2b11cb2020-04-22 09:04:01 -070010651 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010653
10654 if (mActiveTracks.size() == 1) {
10655 ret = exitStandby_l();
10656 }
10657
Eric Laurent6acd1d42017-01-04 14:23:29 -080010658 broadcast_l();
10659
Eric Laurentdda206a2022-07-08 17:28:35 +020010660 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010661
Eric Laurentdda206a2022-07-08 17:28:35 +020010662 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010663}
10664
Andy Hungee58e4a2023-07-07 13:47:37 -070010665status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010666{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010667 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010668 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669
10670 if (mHalStream == 0) {
10671 return NO_INIT;
10672 }
10673
Eric Laurenta54f1282017-07-01 19:39:32 -070010674 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010675 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010676 return NO_ERROR;
10677 }
10678
Andy Hung8d31fd22023-06-26 19:20:57 -070010679 sp<IAfMmapTrack> track;
10680 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010681 if (handle == t->portId()) {
10682 track = t;
10683 break;
10684 }
10685 }
10686 if (track == 0) {
10687 return BAD_VALUE;
10688 }
10689
10690 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010691 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692
Andy Hungc5007f82023-08-29 14:26:09 -070010693 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010694 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010695 AudioSystem::stopOutput(track->portId());
10696 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010698 AudioSystem::stopInput(track->portId());
10699 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700 }
Andy Hungc5007f82023-08-29 14:26:09 -070010701 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702
Andy Hung116bc262023-06-20 18:56:17 -070010703 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010704 if (chain != 0) {
10705 chain->decActiveTrackCnt();
10706 chain->decTrackCnt();
10707 }
10708
Eric Laurentdda206a2022-07-08 17:28:35 +020010709 if (mActiveTracks.isEmpty()) {
10710 mHalStream->stop();
10711 }
10712
Eric Laurent6acd1d42017-01-04 14:23:29 -080010713 broadcast_l();
10714
Eric Laurent6acd1d42017-01-04 14:23:29 -080010715 return NO_ERROR;
10716}
10717
Andy Hungee58e4a2023-07-07 13:47:37 -070010718status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010719NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010720{
10721 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010722 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010723
10724 if (mHalStream == 0) {
10725 return NO_INIT;
10726 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010727 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010728 return INVALID_OPERATION;
10729 }
10730 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010731 if (!mStandby) {
10732 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010733 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010734 mStandby = true;
10735 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010736 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010737 return NO_ERROR;
10738}
10739
Andy Hungee58e4a2023-07-07 13:47:37 -070010740status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010741 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10742 return INVALID_OPERATION;
10743}
10744
Andy Hungee58e4a2023-07-07 13:47:37 -070010745void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010746{
10747 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10748 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10749 mFormat = mHALFormat;
10750 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10751 result = mHalStream->getFrameSize(&mFrameSize);
10752 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010753 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10754 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010755 result = mHalStream->getBufferSize(&mBufferSize);
10756 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10757 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010758
Andy Hungcf10d742020-04-28 15:38:24 -070010759 // TODO: make a readHalParameters call?
10760 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010761 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010762 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010763 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10764 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10765 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10766 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10767 /*
10768 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10769 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10770 (int32_t)mHapticChannelMask)
10771 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10772 (int32_t)mHapticChannelCount)
10773 */
10774 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010775 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010776 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10777 (int32_t)mFrameCount) // sic - added HAL
10778 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779}
10780
Andy Hungee58e4a2023-07-07 13:47:37 -070010781bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010782{
Andy Hungab65b182023-09-06 19:41:47 -070010783 {
10784 audio_utils::unique_lock _l(mutex());
10785 checkSilentMode_l();
10786 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787
10788 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10789
10790 while (!exitPending())
10791 {
Andy Hung116bc262023-06-20 18:56:17 -070010792 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793
Andy Hung13850be2019-03-14 11:33:09 -070010794 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010795 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010796
Eric Laurent6acd1d42017-01-04 14:23:29 -080010797 if (mSignalPending) {
10798 // A signal was raised while we were unlocked
10799 mSignalPending = false;
10800 } else {
10801 if (mConfigEvents.isEmpty()) {
10802 // we're about to wait, flush the binder command buffer
10803 IPCThreadState::self()->flushCommands();
10804
10805 if (exitPending()) {
10806 break;
10807 }
10808
Eric Laurent6acd1d42017-01-04 14:23:29 -080010809 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010810 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010811 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010812 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010813
10814 checkSilentMode_l();
10815
10816 continue;
10817 }
10818 }
10819
10820 processConfigEvents_l();
10821
10822 processVolume_l();
10823
10824 checkInvalidTracks_l();
10825
Andy Hungab65b182023-09-06 19:41:47 -070010826 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010827
Kevin Rocard069c2712018-03-29 19:09:14 -070010828 updateMetadata_l();
10829
Eric Laurent6acd1d42017-01-04 14:23:29 -080010830 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010831 } // release Thread lock
10832
Eric Laurent6acd1d42017-01-04 14:23:29 -080010833 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010834 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010835 }
Andy Hung13850be2019-03-14 11:33:09 -070010836
10837 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010838 unlockEffectChains(effectChains);
10839 // Effect chains will be actually deleted here if they were removed from
10840 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010841 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010842 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010843 mThreadloopExecutor.process(); // process any remaining deferred actions.
10844 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010845
10846 threadLoop_exit();
10847
10848 if (!mStandby) {
10849 threadLoop_standby();
10850 mStandby = true;
10851 }
10852
Eric Laurent6acd1d42017-01-04 14:23:29 -080010853 ALOGV("Thread %p type %d exiting", this, mType);
10854 return false;
10855}
10856
Andy Hungc5007f82023-08-29 14:26:09 -070010857// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010858bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010859 status_t& status)
10860{
10861 AudioParameter param = AudioParameter(keyValuePair);
10862 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010863 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010864 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010865 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010866 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010867 if (sendToHal) {
10868 status = mHalStream->setParameters(keyValuePair);
10869 } else {
10870 status = NO_ERROR;
10871 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010872
10873 return false;
10874}
10875
Andy Hungee58e4a2023-07-07 13:47:37 -070010876String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010877{
Andy Hung972bec12023-08-31 16:13:39 -070010878 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010879 String8 out_s8;
10880 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10881 return out_s8;
10882 }
Andy Hung920f6572022-10-06 12:09:49 -070010883 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010884}
10885
Andy Hungab65b182023-09-06 19:41:47 -070010886void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010887 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010888 sp<AudioIoDescriptor> desc;
10889 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010890 switch (event) {
10891 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010892 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010893 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010894 isInput = true;
10895 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010896 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010897 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010898 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010899 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10900 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010901 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010902 case AUDIO_INPUT_CLOSED:
10903 case AUDIO_OUTPUT_CLOSED:
10904 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010905 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010906 break;
10907 }
Andy Hungab65b182023-09-06 19:41:47 -070010908 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010909}
10910
Andy Hungee58e4a2023-07-07 13:47:37 -070010911status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010913NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010914{
10915 status_t status = NO_ERROR;
10916
10917 // store new device and send to effects
10918 audio_devices_t type = AUDIO_DEVICE_NONE;
Robert Wuaeb1d002024-10-30 23:19:44 +000010919 DeviceIdVector deviceIds;
jiabinc52b1ff2019-10-31 17:20:42 -070010920 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10921 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10922 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010923 if (isOutput()) {
10924 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010925 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10926 && !mAudioHwDev->supportsAudioPatches(),
10927 "Enumerated device type(%#x) must not be used "
10928 "as it does not support audio patches",
10929 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010930 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010931 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10932 patch->sinks[i].ext.device.address);
Robert Wuaeb1d002024-10-30 23:19:44 +000010933 deviceIds.push_back(patch->sinks[i].id);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010934 }
jiabinc52b1ff2019-10-31 17:20:42 -070010935 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010936 } else {
10937 type = patch->sources[0].ext.device.type;
Robert Wuaeb1d002024-10-30 23:19:44 +000010938 deviceIds.push_back(patch->sources[0].id);
jiabinc52b1ff2019-10-31 17:20:42 -070010939 numDevices = mPatch.num_sources;
10940 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010941 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942 }
10943
10944 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010945 if (isOutput()) {
10946 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10947 } else {
10948 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10949 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010950 }
10951
jiabinc52b1ff2019-10-31 17:20:42 -070010952 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010953 // store new source and send to effects
10954 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10955 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10956 for (size_t i = 0; i < mEffectChains.size(); i++) {
10957 mEffectChains[i]->setAudioSource_l(mAudioSource);
10958 }
10959 }
10960 }
10961
jiabin78b86f22024-02-22 00:39:29 +000010962 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10963 // okay to notify the client earlier before the new patch creation.
Robert Wub7f8edc2024-11-04 19:54:38 +000010964 if (!areDeviceIdsEqual(deviceIds, mDeviceIds)) {
jiabin78b86f22024-02-22 00:39:29 +000010965 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10966 // The aaudioservice handle the routing changed event asynchronously. In that case,
10967 // it is safe to hold the lock here.
Robert Wuaeb1d002024-10-30 23:19:44 +000010968 callback->onRoutingChanged(deviceIds);
jiabin78b86f22024-02-22 00:39:29 +000010969 }
10970 }
10971
Eric Laurent6acd1d42017-01-04 14:23:29 -080010972 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010973 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10974 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010975 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010976 audio_port_config port;
10977 std::optional<audio_source_t> source;
10978 if (isOutput()) {
10979 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010980 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010981 port = patch->sources[0];
10982 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010983 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010984 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010985 *handle = AUDIO_PATCH_HANDLE_NONE;
10986 }
10987
Robert Wub7f8edc2024-11-04 19:54:38 +000010988 if (numDevices == 0 || (!areDeviceIdsEqual(deviceIds, mDeviceIds))) {
jiabinc52b1ff2019-10-31 17:20:42 -070010989 if (isOutput()) {
10990 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10991 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010992 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010993 } else {
10994 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10995 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10996 }
jiabinc52b1ff2019-10-31 17:20:42 -070010997 mPatch = *patch;
Robert Wuaeb1d002024-10-30 23:19:44 +000010998 mDeviceIds = deviceIds;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010999 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011000 // Force meteadata update after a route change
11001 mActiveTracks.setHasChanged();
11002
Eric Laurent6acd1d42017-01-04 14:23:29 -080011003 return status;
11004}
11005
Andy Hungee58e4a2023-07-07 13:47:37 -070011006status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011007{
11008 status_t status = NO_ERROR;
11009
jiabinc52b1ff2019-10-31 17:20:42 -070011010 mPatch = audio_patch{};
11011 mOutDeviceTypeAddrs.clear();
11012 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011013
11014 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
11015 supportsAudioPatches : false;
11016
11017 if (supportsAudioPatches) {
11018 status = mHalDevice->releaseAudioPatch(handle);
11019 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080011020 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011021 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011022 // Force meteadata update after a route change
11023 mActiveTracks.setHasChanged();
11024
Eric Laurent6acd1d42017-01-04 14:23:29 -080011025 return status;
11026}
11027
Andy Hungee58e4a2023-07-07 13:47:37 -070011028void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070011029NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080011030{
Mikhail Naganovdc769682018-05-04 15:34:08 -070011031 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011032 if (isOutput()) {
11033 config->role = AUDIO_PORT_ROLE_SOURCE;
11034 config->ext.mix.hw_module = mAudioHwDev->handle();
11035 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
11036 } else {
11037 config->role = AUDIO_PORT_ROLE_SINK;
11038 config->ext.mix.hw_module = mAudioHwDev->handle();
11039 config->ext.mix.usecase.source = mAudioSource;
11040 }
11041}
11042
Andy Hungee58e4a2023-07-07 13:47:37 -070011043status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011044{
11045 audio_session_t session = chain->sessionId();
11046
11047 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
11048 // Attach all tracks with same session ID to this chain.
11049 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070011050 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011051 if (session == track->sessionId()) {
11052 chain->incTrackCnt();
11053 chain->incActiveTrackCnt();
11054 }
11055 }
11056
11057 chain->setThread(this);
11058 chain->setInBuffer(nullptr);
11059 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000011060 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011061
11062 mEffectChains.add(chain);
11063 checkSuspendOnAddEffectChain_l(chain);
11064 return NO_ERROR;
11065}
11066
Andy Hungee58e4a2023-07-07 13:47:37 -070011067size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011068{
11069 audio_session_t session = chain->sessionId();
11070
11071 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
11072
11073 for (size_t i = 0; i < mEffectChains.size(); i++) {
11074 if (chain == mEffectChains[i]) {
11075 mEffectChains.removeAt(i);
11076 // detach all active tracks from the chain
11077 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070011078 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011079 if (session == track->sessionId()) {
11080 chain->decActiveTrackCnt();
11081 chain->decTrackCnt();
11082 }
11083 }
11084 break;
11085 }
11086 }
11087 return mEffectChains.size();
11088}
11089
Andy Hungee58e4a2023-07-07 13:47:37 -070011090void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011091{
11092 mHalStream->standby();
11093}
11094
Andy Hungee58e4a2023-07-07 13:47:37 -070011095void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011096{
Phil Burk7dce7282017-09-27 13:51:41 -070011097 // Do not call callback->onTearDown() because it is redundant for thread exit
11098 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080011099}
11100
Andy Hungee58e4a2023-07-07 13:47:37 -070011101status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011102{
11103 return BAD_VALUE;
11104}
11105
Andy Hungee58e4a2023-07-07 13:47:37 -070011106bool MmapThread::isValidSyncEvent(
11107 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011108{
11109 return false;
11110}
11111
Andy Hungee58e4a2023-07-07 13:47:37 -070011112status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080011113 const effect_descriptor_t *desc, audio_session_t sessionId)
11114{
11115 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080011116 if (audio_is_global_session(sessionId)) {
11117 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080011118 desc->name, mThreadName);
11119 return BAD_VALUE;
11120 }
11121
11122 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
11123 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
11124 desc->name);
11125 return BAD_VALUE;
11126 }
11127 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080011128 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
11129 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011130 return BAD_VALUE;
11131 }
11132
11133 // Only allow effects without processing load or latency
11134 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
11135 return BAD_VALUE;
11136 }
11137
Andy Hung116bc262023-06-20 18:56:17 -070011138 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070011139 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
11140 return BAD_VALUE;
11141 }
11142
Eric Laurent6acd1d42017-01-04 14:23:29 -080011143 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011144}
11145
Andy Hungee58e4a2023-07-07 13:47:37 -070011146void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011147{
Andy Hung8d31fd22023-06-26 19:20:57 -070011148 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011149 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000011150 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
11151 // The aaudioservice handle the routing changed event asynchronously. In that case,
11152 // it is safe to hold the lock here.
Robert Wub7f8edc2024-11-04 19:54:38 +000011153 callback->onRoutingChanged({});
jiabin78b86f22024-02-22 00:39:29 +000011154 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020011155 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
11156 mNoCallbackWarningCount++;
11157 }
11158 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011159 }
11160 }
11161}
11162
Andy Hungee58e4a2023-07-07 13:47:37 -070011163void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011164{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011165 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
11166 mAttr.content_type, mAttr.usage, mAttr.source);
11167 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070011168 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011169 dprintf(fd, " No active clients\n");
11170 }
11171}
11172
Andy Hungee58e4a2023-07-07 13:47:37 -070011173void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011174{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011175 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011176 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011177 dprintf(fd, " %zu Tracks\n", numtracks);
11178 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080011179 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011180 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070011181 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011182 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011183 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011184 result.append(prefix);
11185 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011186 }
11187 } else {
11188 dprintf(fd, "\n");
11189 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011190 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011191}
11192
Atneya Nairaa3afcb2024-10-08 16:36:19 -070011193std::string MmapThread::getLocalLogHeader() const {
11194 using namespace std::literals;
11195 static constexpr auto indent = " "
11196 " "sv;
11197 return std::string{indent}.append(IAfMmapTrack::getLogHeader());
11198}
11199
Andy Hungee58e4a2023-07-07 13:47:37 -070011200/* static */
11201sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011202 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011203 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011204 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011205}
11206
11207MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011208 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011209 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011210 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011211 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011212 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011213{
11214 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
Andy Hungf767de02024-10-30 19:47:50 -070011215 mFlagsAsString = toString(output->flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011216 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011217 mMasterVolume = afThreadCallback->masterVolume_l();
11218 mMasterMute = afThreadCallback->masterMute_l();
Andy Hung6b137d12024-08-27 22:35:17 +000011219 if (!audioserver_flags::portid_volume_management()) {
11220 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11221 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11222 mStreamTypes[stream].volume = 0.0f;
11223 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11224 }
11225 // Audio patch and call assistant volume are always max
11226 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11227 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11228 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11229 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011230 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011231 if (mAudioHwDev) {
11232 if (mAudioHwDev->canSetMasterVolume()) {
11233 mMasterVolume = 1.0;
11234 }
11235
11236 if (mAudioHwDev->canSetMasterMute()) {
11237 mMasterMute = false;
11238 }
11239 }
11240}
11241
Andy Hungee58e4a2023-07-07 13:47:37 -070011242void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011243 audio_stream_type_t streamType,
11244 audio_session_t sessionId,
11245 const sp<MmapStreamCallback>& callback,
Robert Wuaeb1d002024-10-30 23:19:44 +000011246 const DeviceIdVector& deviceIds,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011247 audio_port_handle_t portId)
11248{
Andy Hung8d672e02023-09-15 18:19:28 -070011249 audio_utils::lock_guard l(mutex());
Robert Wuaeb1d002024-10-30 23:19:44 +000011250 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceIds, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011251 mStreamType = streamType;
11252}
11253
Andy Hungee58e4a2023-07-07 13:47:37 -070011254AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011255{
Andy Hung972bec12023-08-31 16:13:39 -070011256 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011257 AudioStreamOut *output = mOutput;
11258 mOutput = NULL;
11259 return output;
11260}
11261
Andy Hungee58e4a2023-07-07 13:47:37 -070011262void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011263{
Andy Hung972bec12023-08-31 16:13:39 -070011264 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011265 // Don't apply master volume in SW if our HAL can do it for us.
11266 if (mAudioHwDev &&
11267 mAudioHwDev->canSetMasterVolume()) {
11268 mMasterVolume = 1.0;
11269 } else {
11270 mMasterVolume = value;
11271 }
11272}
11273
Andy Hungee58e4a2023-07-07 13:47:37 -070011274void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011275{
Andy Hung972bec12023-08-31 16:13:39 -070011276 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011277 // Don't apply master mute in SW if our HAL can do it for us.
11278 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11279 mMasterMute = false;
11280 } else {
11281 mMasterMute = muted;
11282 }
11283}
11284
Vlad Popa1e865e62024-08-15 19:11:42 -070011285void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011286{
Vlad Popa1e865e62024-08-15 19:11:42 -070011287 ALOGV("%s: stream %d value %f muted %d", __func__, stream, value, muted);
Andy Hung972bec12023-08-31 16:13:39 -070011288 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011289 mStreamTypes[stream].volume = value;
Vlad Popa1e865e62024-08-15 19:11:42 -070011290 if (com_android_media_audio_ring_my_car()) {
11291 mStreamTypes[stream].mute = muted;
11292 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011293 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011294 broadcast_l();
11295 }
11296}
11297
Andy Hungee58e4a2023-07-07 13:47:37 -070011298float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011299{
Andy Hung972bec12023-08-31 16:13:39 -070011300 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011301 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011302}
11303
Andy Hungee58e4a2023-07-07 13:47:37 -070011304void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011305{
Andy Hung972bec12023-08-31 16:13:39 -070011306 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011307 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011308 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011309 broadcast_l();
11310 }
11311}
11312
Andy Hung6b137d12024-08-27 22:35:17 +000011313status_t MmapPlaybackThread::setPortsVolume(
Vlad Popa1e865e62024-08-15 19:11:42 -070011314 const std::vector<audio_port_handle_t>& portIds, float volume, bool muted) {
Andy Hung6b137d12024-08-27 22:35:17 +000011315 audio_utils::lock_guard _l(mutex());
11316 for (const auto& portId : portIds) {
11317 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
11318 if (portId == track->portId()) {
11319 track->setPortVolume(volume);
Vlad Popa1e865e62024-08-15 19:11:42 -070011320 track->setPortMute(muted);
Andy Hung6b137d12024-08-27 22:35:17 +000011321 break;
11322 }
11323 }
11324 }
11325 broadcast_l();
11326 return NO_ERROR;
11327}
11328
Andy Hungee58e4a2023-07-07 13:47:37 -070011329void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011330{
Andy Hung972bec12023-08-31 16:13:39 -070011331 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011332 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011333 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011334 track->invalidate();
11335 }
11336 broadcast_l();
11337 }
11338}
11339
Andy Hungee58e4a2023-07-07 13:47:37 -070011340void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011341{
Andy Hung972bec12023-08-31 16:13:39 -070011342 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011343 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011344 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011345 if (portIds.find(track->portId()) != portIds.end()) {
11346 track->invalidate();
11347 trackMatch = true;
11348 portIds.erase(track->portId());
11349 }
11350 if (portIds.empty()) {
11351 break;
11352 }
11353 }
11354 if (trackMatch) {
11355 broadcast_l();
11356 }
11357}
11358
Andy Hungee58e4a2023-07-07 13:47:37 -070011359void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011360NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011361{
Andy Hung6b137d12024-08-27 22:35:17 +000011362 float volume = 0;
11363 if (!audioserver_flags::portid_volume_management()) {
11364 if (mMasterMute || streamMuted_l()) {
11365 volume = 0;
11366 } else {
11367 volume = mMasterVolume * streamVolume_l();
11368 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011369 } else {
Andy Hung6b137d12024-08-27 22:35:17 +000011370 if (mMasterMute) {
11371 volume = 0;
11372 } else {
11373 // All mmap tracks are declared with the same audio attributes to the audio policy
11374 // manager. Hence, they follow the same routing / volume group. Any change of volume
11375 // will be broadcasted to all tracks. Thus, take arbitrarily first track volume.
11376 size_t numtracks = mActiveTracks.size();
11377 if (numtracks) {
Vlad Popa1e865e62024-08-15 19:11:42 -070011378 if (mActiveTracks[0]->getPortMute()) {
11379 volume = 0;
11380 } else {
11381 volume = mMasterVolume * mActiveTracks[0]->getPortVolume();
11382 }
Andy Hung6b137d12024-08-27 22:35:17 +000011383 }
11384 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011385 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011386 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011387 // Convert volumes from float to 8.24
11388 uint32_t vol = (uint32_t)(volume * (1 << 24));
11389
11390 // Delegate volume control to effect in track effect chain if needed
11391 // only one effect chain can be present on DirectOutputThread, so if
11392 // there is one, the track is connected to it
11393 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011394 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011395 volume = (float)vol / (1 << 24);
11396 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011397 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011398 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11399 mHalVolFloat = volume; // HW volume control worked, so update value.
11400 mNoCallbackWarningCount = 0;
11401 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011402 sp<MmapStreamCallback> callback = mCallback.promote();
11403 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011404 mHalVolFloat = volume; // SW volume control worked, so update value.
11405 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011406 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011407 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011408 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011409 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011410 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11411 ALOGW("Could not set MMAP stream volume: no volume callback!");
11412 mNoCallbackWarningCount++;
11413 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011414 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011415 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011416 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011417 track->setMetadataHasChanged();
Andy Hung6b137d12024-08-27 22:35:17 +000011418 if (!audioserver_flags::portid_volume_management()) {
11419 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11420 /*muteState=*/{mMasterMute,
11421 streamVolume_l() == 0.f,
11422 streamMuted_l(),
11423 // TODO(b/241533526): adjust logic to include mute from AppOps
11424 false /*muteFromPlaybackRestricted*/,
11425 false /*muteFromClientVolume*/,
Vlad Popa1e865e62024-08-15 19:11:42 -070011426 false /*muteFromVolumeShaper*/,
11427 false /*muteFromPortVolume*/});
Andy Hung6b137d12024-08-27 22:35:17 +000011428 } else {
11429 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11430 /*muteState=*/{mMasterMute,
11431 track->getPortVolume() == 0.f,
11432 /* muteFromStreamMuted= */ false,
11433 // TODO(b/241533526): adjust logic to include mute from AppOps
11434 false /*muteFromPlaybackRestricted*/,
11435 false /*muteFromClientVolume*/,
Vlad Popa1e865e62024-08-15 19:11:42 -070011436 false /*muteFromVolumeShaper*/,
11437 track->getPortMute()});
Andy Hung6b137d12024-08-27 22:35:17 +000011438 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011439 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011440 }
11441}
11442
Andy Hungee58e4a2023-07-07 13:47:37 -070011443ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011444{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011445 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011446 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011447 }
11448 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011449 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011450 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011451 playback_track_metadata_v7_t trackMetadata;
11452 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011453 .usage = track->attributes().usage,
11454 .content_type = track->attributes().content_type,
11455 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011456 };
11457 trackMetadata.channel_mask = track->channelMask(),
11458 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11459 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011460 }
11461 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011462
11463 MetadataUpdate change;
11464 change.playbackMetadataUpdate = metadata.tracks;
11465 return change;
11466};
Kevin Rocard069c2712018-03-29 19:09:14 -070011467
Andy Hungee58e4a2023-07-07 13:47:37 -070011468void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011469{
Atneya Nair967c85f2024-10-27 16:09:50 -070011470 if (property_get_bool("ro.audio.silent", false)) {
11471 ALOGW("ro.audio.silent is now ignored");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011472 }
11473}
11474
Andy Hungee58e4a2023-07-07 13:47:37 -070011475void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011476{
11477 MmapThread::toAudioPortConfig(config);
11478 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11479 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11480 config->flags.output = mOutput->flags;
11481 }
11482}
11483
Andy Hungee58e4a2023-07-07 13:47:37 -070011484status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011485 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011486{
11487 if (mOutput == nullptr) {
11488 return NO_INIT;
11489 }
11490 struct timespec timestamp;
11491 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11492 if (status == NO_ERROR) {
11493 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11494 }
11495 return status;
11496}
11497
Andy Hungee58e4a2023-07-07 13:47:37 -070011498status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011499 // Send to MelProcessor for sound dose measurement.
11500 auto processor = mMelProcessor.load();
11501 if (processor) {
11502 processor->process(buffer, frameCount * mFrameSize);
11503 }
11504
jiabinfc791ee2023-02-15 19:43:40 +000011505 return NO_ERROR;
11506}
11507
Andy Hungc5007f82023-08-29 14:26:09 -070011508// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011509void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011510 const sp<audio_utils::MelProcessor>& processor)
11511{
11512 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011513 mMelProcessor.store(processor);
11514 if (processor) {
11515 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011516 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011517
11518 // no need to update output format for MMapPlaybackThread since it is
11519 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011520}
11521
Andy Hungc5007f82023-08-29 14:26:09 -070011522// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011523void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011524{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011525 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11526 auto melProcessor = mMelProcessor.load();
11527 if (melProcessor != nullptr) {
11528 melProcessor->pause();
11529 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011530}
11531
Andy Hungee58e4a2023-07-07 13:47:37 -070011532void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011533{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011534 MmapThread::dumpInternals_l(fd, args);
Andy Hung6b137d12024-08-27 22:35:17 +000011535 if (!audioserver_flags::portid_volume_management()) {
11536 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d",
11537 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
11538 } else {
11539 dprintf(fd, " HAL volume: %f", mHalVolFloat);
11540 }
11541 dprintf(fd, "\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011542 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11543}
11544
Andy Hungee58e4a2023-07-07 13:47:37 -070011545/* static */
11546sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011547 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011548 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011549 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011550}
11551
11552MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011553 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011554 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011555 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011556 mInput(input)
11557{
11558 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
Andy Hungf767de02024-10-30 19:47:50 -070011559 mFlagsAsString = toString(input->flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011560 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11561}
11562
Andy Hungee58e4a2023-07-07 13:47:37 -070011563status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011564{
Phil Burkf054fc32018-12-06 09:45:59 -080011565 {
11566 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011567 if (mInput != nullptr && mInput->stream != nullptr) {
11568 mInput->stream->setGain(1.0f);
11569 }
11570 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011571 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011572}
11573
Andy Hungee58e4a2023-07-07 13:47:37 -070011574AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011575{
Andy Hung972bec12023-08-31 16:13:39 -070011576 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011577 AudioStreamIn *input = mInput;
11578 mInput = NULL;
11579 return input;
11580}
Kevin Rocard069c2712018-03-29 19:09:14 -070011581
Andy Hungee58e4a2023-07-07 13:47:37 -070011582void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011583{
11584 bool changed = false;
11585 bool silenced = false;
11586
11587 sp<MmapStreamCallback> callback = mCallback.promote();
11588 if (callback == 0) {
11589 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11590 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11591 mNoCallbackWarningCount++;
11592 }
11593 }
11594
11595 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11596 // track is silenced and unmute otherwise
11597 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11598 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11599 changed = true;
11600 silenced = mActiveTracks[i]->isSilenced_l();
11601 }
11602 }
11603
11604 if (changed) {
11605 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11606 }
11607}
11608
Andy Hungee58e4a2023-07-07 13:47:37 -070011609ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011610{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011611 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011612 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011613 }
11614 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011615 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011616 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011617 record_track_metadata_v7_t trackMetadata;
11618 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011619 .source = track->attributes().source,
11620 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011621 };
11622 trackMetadata.channel_mask = track->channelMask(),
11623 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11624 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011625 }
11626 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011627 MetadataUpdate change;
11628 change.recordMetadataUpdate = metadata.tracks;
11629 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011630}
11631
Andy Hungee58e4a2023-07-07 13:47:37 -070011632void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011633{
Andy Hung972bec12023-08-31 16:13:39 -070011634 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011635 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011636 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011637 mActiveTracks[i]->setSilenced_l(silenced);
11638 broadcast_l();
11639 }
11640 }
jiabin09609032022-06-15 19:26:01 +000011641 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011642}
11643
Andy Hungee58e4a2023-07-07 13:47:37 -070011644void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011645{
11646 MmapThread::toAudioPortConfig(config);
11647 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11648 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11649 config->flags.input = mInput->flags;
11650 }
11651}
11652
Andy Hungee58e4a2023-07-07 13:47:37 -070011653status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011654 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011655{
11656 if (mInput == nullptr) {
11657 return NO_INIT;
11658 }
11659 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11660}
11661
jiabinc658e452022-10-21 20:52:21 +000011662// ----------------------------------------------------------------------------
11663
Andy Hungee58e4a2023-07-07 13:47:37 -070011664/* static */
11665sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011666 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011667 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011668 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011669}
11670
Andy Hung583043b2023-07-17 17:05:00 -070011671BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011672 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011673 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011674
Andy Hungee58e4a2023-07-07 13:47:37 -070011675PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011676 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011677 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11678 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011679 float volumeLeft = 1.0f;
11680 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011681 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11682 bitPerfectTrack != nullptr) {
11683 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011684 mAudioMixer->setParameter(
11685 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11686 mAudioMixer->setParameter(
11687 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11688 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011689 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011690 mIsBitPerfect = true;
11691 } else {
11692 mIsBitPerfect = false;
11693 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11694 // active.
11695 for (const auto& track : mActiveTracks) {
11696 const int trackId = track->id();
11697 mAudioMixer->setParameter(
11698 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11699 }
11700 }
jiabin76d94692022-12-15 21:51:21 +000011701 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11702 mVolumeLeft = volumeLeft;
11703 mVolumeRight = volumeRight;
11704 setVolumeForOutput_l(volumeLeft, volumeRight);
11705 }
jiabinc658e452022-10-21 20:52:21 +000011706 return result;
11707}
11708
Andy Hungee58e4a2023-07-07 13:47:37 -070011709void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011710 MixerThread::threadLoop_mix();
11711 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11712}
11713
jiabin220eea12024-05-17 17:55:20 +000011714void BitPerfectThread::setTracksInternalMute(
11715 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
jiabin783a1eb2024-09-18 22:36:19 +000011716 audio_utils::lock_guard _l(mutex());
jiabin220eea12024-05-17 17:55:20 +000011717 for (auto& track : mTracks) {
11718 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11719 track->setInternalMute(it->second);
11720 tracksInternalMute->erase(it);
11721 }
11722 }
11723}
11724
11725sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11726 if (com::android::media::audioserver::
11727 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11728 sp<IAfTrack> bitPerfectTrack = nullptr;
11729 bool allOtherTracksMuted = true;
11730 // Return the bit perfect track if all other tracks are muted
11731 for (const auto& track : mActiveTracks) {
11732 if (track->isBitPerfect()) {
jiabin783a1eb2024-09-18 22:36:19 +000011733 if (track->getInternalMute()) {
11734 // There can only be one bit-perfect client active. If it is mute internally,
11735 // there is no need to stream bit-perfectly.
11736 break;
11737 }
jiabin220eea12024-05-17 17:55:20 +000011738 bitPerfectTrack = track;
11739 } else if (track->getFinalVolume() != 0.f) {
11740 allOtherTracksMuted = false;
11741 if (bitPerfectTrack != nullptr) {
11742 break;
11743 }
11744 }
11745 }
11746 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11747 } else {
11748 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11749 return mActiveTracks[0];
11750 }
11751 }
11752 return nullptr;
11753}
11754
Glenn Kasten63238ef2015-03-02 15:50:29 -080011755} // namespace android